IP地址计算器
专业的IP地址计算工具,支持IP地址运算、范围计算、排序和去重
功能选择
IP地址运算
网络地址范围计算
IP地址排序和去重
IP地址格式转换
计算结果
计算结果:
详细信息:
示例代码
各语言示例代码
-
IPCalculator (JAVA)
1import java.util.*; 2import java.util.regex.Pattern; 3import java.util.regex.Matcher; 4 5/** 6 * IP地址计算器 - Java版本 7 * 支持IP地址运算、范围计算、排序和去重、格式转换等功能 8 */ 9public class IPCalculator { 10 private static final Pattern IP_PATTERN = Pattern.compile("^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$"); 11 12 /** 13 * IP运算结果类 14 */ 15 public static class IPMathResult { 16 private String result; 17 private long resultInt; 18 private long ip1Int; 19 private long ip2Int; 20 private String operation; 21 22 public IPMathResult(String result, long resultInt, long ip1Int, long ip2Int, String operation) { 23 this.result = result; 24 this.resultInt = resultInt; 25 this.ip1Int = ip1Int; 26 this.ip2Int = ip2Int; 27 this.operation = operation; 28 } 29 30 // Getters 31 public String getResult() { return result; } 32 public long getResultInt() { return resultInt; } 33 public long getIp1Int() { return ip1Int; } 34 public long getIp2Int() { return ip2Int; } 35 public String getOperation() { return operation; } 36 } 37 38 /** 39 * IP范围结果类 40 */ 41 public static class IPRangeResult { 42 private String startIP; 43 private String endIP; 44 private long count; 45 private String networkIP; 46 private String broadcastIP; 47 private int suggestedCIDR; 48 private long suggestedHosts; 49 50 public IPRangeResult(String startIP, String endIP, long count, String networkIP, 51 String broadcastIP, int suggestedCIDR, long suggestedHosts) { 52 this.startIP = startIP; 53 this.endIP = endIP; 54 this.count = count; 55 this.networkIP = networkIP; 56 this.broadcastIP = broadcastIP; 57 this.suggestedCIDR = suggestedCIDR; 58 this.suggestedHosts = suggestedHosts; 59 } 60 61 // Getters 62 public String getStartIP() { return startIP; } 63 public String getEndIP() { return endIP; } 64 public long getCount() { return count; } 65 public String getNetworkIP() { return networkIP; } 66 public String getBroadcastIP() { return broadcastIP; } 67 public int getSuggestedCIDR() { return suggestedCIDR; } 68 public long getSuggestedHosts() { return suggestedHosts; } 69 } 70 71 /** 72 * IP列表处理结果类 73 */ 74 public static class IPListResult { 75 private int originalCount; 76 private int validCount; 77 private int invalidCount; 78 private List<String> validIPs; 79 private List<String> invalidIPs; 80 81 public IPListResult(int originalCount, int validCount, int invalidCount, 82 List<String> validIPs, List<String> invalidIPs) { 83 this.originalCount = originalCount; 84 this.validCount = validCount; 85 this.invalidCount = invalidCount; 86 this.validIPs = validIPs; 87 this.invalidIPs = invalidIPs; 88 } 89 90 // Getters 91 public int getOriginalCount() { return originalCount; } 92 public int getValidCount() { return validCount; } 93 public int getInvalidCount() { return invalidCount; } 94 public List<String> getValidIPs() { return validIPs; } 95 public List<String> getInvalidIPs() { return invalidIPs; } 96 } 97 98 /** 99 * IP转换结果类 100 */ 101 public static class IPConvertResult { 102 private String input; 103 private String targetFormat; 104 private String result; 105 private String decimal; 106 private long integer; 107 private String binary; 108 private String hex; 109 110 public IPConvertResult(String input, String targetFormat, String result, 111 String decimal, long integer, String binary, String hex) { 112 this.input = input; 113 this.targetFormat = targetFormat; 114 this.result = result; 115 this.decimal = decimal; 116 this.integer = integer; 117 this.binary = binary; 118 this.hex = hex; 119 } 120 121 // Getters 122 public String getInput() { return input; } 123 public String getTargetFormat() { return targetFormat; } 124 public String getResult() { return result; } 125 public String getDecimal() { return decimal; } 126 public long getInteger() { return integer; } 127 public String getBinary() { return binary; } 128 public String getHex() { return hex; } 129 } 130 131 /** 132 * 验证IP地址格式 133 * @param ip IP地址字符串 134 * @return 是否有效 135 */ 136 public boolean validateIP(String ip) { 137 if (ip == null || ip.isEmpty()) { 138 return false; 139 } 140 141 Matcher matcher = IP_PATTERN.matcher(ip); 142 if (!matcher.matches()) { 143 return false; 144 } 145 146 for (int i = 1; i <= 4; i++) { 147 int part = Integer.parseInt(matcher.group(i)); 148 if (part < 0 || part > 255) { 149 return false; 150 } 151 } 152 return true; 153 } 154 155 /** 156 * IP地址转整数 157 * @param ip IP地址字符串 158 * @return 整数 159 */ 160 public long ipToInt(String ip) throws IllegalArgumentException { 161 if (!validateIP(ip)) { 162 throw new IllegalArgumentException("无效的IP地址: " + ip); 163 } 164 165 String[] parts = ip.split("\\."); 166 long result = 0; 167 for (int i = 0; i < 4; i++) { 168 result |= (Long.parseLong(parts[i]) << ((3 - i) * 8)); 169 } 170 return result; 171 } 172 173 /** 174 * 整数转IP地址 175 * @param ipInt 整数 176 * @return IP地址字符串 177 */ 178 public String intToIP(long ipInt) { 179 return String.format("%d.%d.%d.%d", 180 (ipInt >> 24) & 0xFF, 181 (ipInt >> 16) & 0xFF, 182 (ipInt >> 8) & 0xFF, 183 ipInt & 0xFF 184 ); 185 } 186 187 /** 188 * IP地址运算 189 * @param ip1 第一个IP地址 190 * @param ip2 第二个IP地址或数字 191 * @param operation 运算类型 (add, subtract, multiply, divide) 192 * @return 计算结果 193 */ 194 public IPMathResult calculateIP(String ip1, String ip2, String operation) throws IllegalArgumentException { 195 long ip1Int = ipToInt(ip1); 196 long ip2Int; 197 198 if (validateIP(ip2)) { 199 ip2Int = ipToInt(ip2); 200 } else { 201 try { 202 ip2Int = Long.parseLong(ip2); 203 } catch (NumberFormatException e) { 204 throw new IllegalArgumentException("第二个参数必须是有效的IP地址或数字"); 205 } 206 } 207 208 long result; 209 switch (operation) { 210 case "add": 211 result = ip1Int + ip2Int; 212 break; 213 case "subtract": 214 if (ip1Int < ip2Int) { 215 throw new IllegalArgumentException("减法结果不能为负数"); 216 } 217 result = ip1Int - ip2Int; 218 break; 219 case "multiply": 220 result = ip1Int * ip2Int; 221 break; 222 case "divide": 223 if (ip2Int == 0) { 224 throw new IllegalArgumentException("除数不能为零"); 225 } 226 result = ip1Int / ip2Int; 227 break; 228 default: 229 throw new IllegalArgumentException("不支持的运算类型: " + operation); 230 } 231 232 if (result < 0 || result > 4294967295L) { 233 throw new IllegalArgumentException("计算结果超出IP地址范围"); 234 } 235 236 return new IPMathResult(intToIP(result), result, ip1Int, ip2Int, operation); 237 } 238 239 /** 240 * 计算IP范围 241 * @param startIP 起始IP 242 * @param endIP 结束IP 243 * @return 范围信息 244 */ 245 public IPRangeResult calculateRange(String startIP, String endIP) throws IllegalArgumentException { 246 long startInt = ipToInt(startIP); 247 long endInt = ipToInt(endIP); 248 249 if (startInt > endInt) { 250 throw new IllegalArgumentException("起始IP不能大于结束IP"); 251 } 252 253 long count = endInt - startInt + 1; 254 String networkIP = intToIP(startInt); 255 String broadcastIP = intToIP(endInt); 256 257 // 计算CIDR 258 int cidr = 32; 259 while ((1L << (32 - cidr)) < count) { 260 cidr--; 261 } 262 263 return new IPRangeResult(startIP, endIP, count, networkIP, broadcastIP, cidr, 1L << (32 - cidr)); 264 } 265 266 /** 267 * 处理IP列表(排序和去重) 268 * @param ipList IP地址列表 269 * @param removeDuplicates 是否去重 270 * @param sortAscending 是否升序排列 271 * @param validateIPs 是否验证IP格式 272 * @return 处理结果 273 */ 274 public IPListResult processIPList(List<String> ipList, boolean removeDuplicates, 275 boolean sortAscending, boolean validateIPs) { 276 List<String> validIPs = new ArrayList<>(); 277 List<String> invalidIPs = new ArrayList<>(); 278 279 // 验证IP 280 if (validateIPs) { 281 for (String ip : ipList) { 282 if (validateIP(ip)) { 283 validIPs.add(ip); 284 } else { 285 invalidIPs.add(ip); 286 } 287 } 288 } else { 289 validIPs.addAll(ipList); 290 } 291 292 // 去重 293 if (removeDuplicates) { 294 Set<String> seen = new LinkedHashSet<>(); 295 seen.addAll(validIPs); 296 validIPs = new ArrayList<>(seen); 297 } 298 299 // 排序 300 if (sortAscending) { 301 validIPs.sort((a, b) -> { 302 try { 303 return Long.compare(ipToInt(a), ipToInt(b)); 304 } catch (IllegalArgumentException e) { 305 return 0; 306 } 307 }); 308 } else { 309 validIPs.sort((a, b) -> { 310 try { 311 return Long.compare(ipToInt(b), ipToInt(a)); 312 } catch (IllegalArgumentException e) { 313 return 0; 314 } 315 }); 316 } 317 318 return new IPListResult(ipList.size(), validIPs.size(), invalidIPs.size(), validIPs, invalidIPs); 319 } 320 321 /** 322 * IP地址格式转换 323 * @param input 输入IP地址或整数 324 * @param targetFormat 目标格式 325 * @return 转换结果 326 */ 327 public IPConvertResult convertIP(String input, String targetFormat) throws IllegalArgumentException { 328 long inputInt; 329 String inputIP; 330 331 if (validateIP(input)) { 332 inputIP = input; 333 inputInt = ipToInt(inputIP); 334 } else { 335 try { 336 inputInt = Long.parseLong(input); 337 inputIP = intToIP(inputInt); 338 } catch (NumberFormatException e) { 339 throw new IllegalArgumentException("输入必须是有效的IP地址或数字"); 340 } 341 } 342 343 String result; 344 switch (targetFormat) { 345 case "decimal": 346 result = inputIP; 347 break; 348 case "binary": 349 String binary = String.format("%32s", Long.toBinaryString(inputInt)).replace(' ', '0'); 350 result = String.format("%s.%s.%s.%s", 351 binary.substring(0, 8), 352 binary.substring(8, 16), 353 binary.substring(16, 24), 354 binary.substring(24, 32) 355 ); 356 break; 357 case "hex": 358 result = String.format("0x%08X", inputInt); 359 break; 360 case "integer": 361 result = String.valueOf(inputInt); 362 break; 363 case "reverse": 364 String[] parts = inputIP.split("\\."); 365 result = String.format("%s.%s.%s.%s", parts[3], parts[2], parts[1], parts[0]); 366 break; 367 default: 368 throw new IllegalArgumentException("不支持的转换格式: " + targetFormat); 369 } 370 371 String binary = String.format("%32s", Long.toBinaryString(inputInt)).replace(' ', '0'); 372 String binaryFormatted = String.format("%s.%s.%s.%s", 373 binary.substring(0, 8), 374 binary.substring(8, 16), 375 binary.substring(16, 24), 376 binary.substring(24, 32) 377 ); 378 379 return new IPConvertResult(input, targetFormat, result, inputIP, inputInt, binaryFormatted, 380 String.format("0x%08X", inputInt)); 381 } 382 383 /** 384 * 主函数 - 使用示例 385 */ 386 public static void main(String[] args) { 387 IPCalculator calculator = new IPCalculator(); 388 389 System.out.println("=== IP地址计算器示例 ===\n"); 390 391 // IP地址运算示例 392 System.out.println("IP运算结果:"); 393 try { 394 IPMathResult mathResult = calculator.calculateIP("192.168.1.1", "1", "add"); 395 System.out.printf(" 192.168.1.1 + 1 = %s%n", mathResult.getResult()); 396 System.out.printf(" 整数表示: %d%n", mathResult.getResultInt()); 397 } catch (Exception e) { 398 System.out.printf("IP运算错误: %s%n", e.getMessage()); 399 } 400 401 System.out.println(); 402 403 // 范围计算示例 404 System.out.println("范围计算结果:"); 405 try { 406 IPRangeResult rangeResult = calculator.calculateRange("192.168.1.1", "192.168.1.254"); 407 System.out.printf(" 起始IP: %s%n", rangeResult.getStartIP()); 408 System.out.printf(" 结束IP: %s%n", rangeResult.getEndIP()); 409 System.out.printf(" IP数量: %d%n", rangeResult.getCount()); 410 System.out.printf(" 建议CIDR: /%d%n", rangeResult.getSuggestedCIDR()); 411 } catch (Exception e) { 412 System.out.printf("范围计算错误: %s%n", e.getMessage()); 413 } 414 415 System.out.println(); 416 417 // IP列表处理示例 418 System.out.println("IP列表处理结果:"); 419 List<String> ipList = Arrays.asList("192.168.1.1", "10.0.0.1", "172.16.0.1", "192.168.1.1", "192.168.1.100"); 420 IPListResult listResult = calculator.processIPList(ipList, true, true, true); 421 System.out.printf(" 原始数量: %d%n", listResult.getOriginalCount()); 422 System.out.printf(" 有效数量: %d%n", listResult.getValidCount()); 423 System.out.printf(" 无效数量: %d%n", listResult.getInvalidCount()); 424 System.out.printf(" 处理后的IP: %s%n", listResult.getValidIPs()); 425 426 System.out.println(); 427 428 // 格式转换示例 429 System.out.println("格式转换结果:"); 430 try { 431 IPConvertResult convertResult = calculator.convertIP("192.168.1.1", "binary"); 432 System.out.printf(" 输入: %s%n", convertResult.getInput()); 433 System.out.printf(" 目标格式: %s%n", convertResult.getTargetFormat()); 434 System.out.printf(" 结果: %s%n", convertResult.getResult()); 435 System.out.printf(" 二进制: %s%n", convertResult.getBinary()); 436 System.out.printf(" 十六进制: %s%n", convertResult.getHex()); 437 } catch (Exception e) { 438 System.out.printf("格式转换错误: %s%n", e.getMessage()); 439 } 440 } 441}
-
ip_calculator (GO)
1package main 2 3import ( 4 "fmt" 5 "net" 6 "regexp" 7 "sort" 8 "strconv" 9 "strings" 10) 11 12// IPCalculator IP地址计算器结构体 13type IPCalculator struct { 14 ipRegex *regexp.Regexp 15} 16 17// IPMathResult IP运算结果 18type IPMathResult struct { 19 Result string `json:"result"` 20 ResultInt uint32 `json:"result_int"` 21 IP1Int uint32 `json:"ip1_int"` 22 IP2Int uint32 `json:"ip2_int"` 23 Operation string `json:"operation"` 24} 25 26// IPRangeResult IP范围结果 27type IPRangeResult struct { 28 StartIP string `json:"start_ip"` 29 EndIP string `json:"end_ip"` 30 Count uint32 `json:"count"` 31 NetworkIP string `json:"network_ip"` 32 BroadcastIP string `json:"broadcast_ip"` 33 SuggestedCIDR int `json:"suggested_cidr"` 34 SuggestedHosts uint32 `json:"suggested_hosts"` 35} 36 37// IPListResult IP列表处理结果 38type IPListResult struct { 39 OriginalCount int `json:"original_count"` 40 ValidCount int `json:"valid_count"` 41 InvalidCount int `json:"invalid_count"` 42 ValidIPs []string `json:"valid_ips"` 43 InvalidIPs []string `json:"invalid_ips"` 44} 45 46// IPConvertResult IP转换结果 47type IPConvertResult struct { 48 Input string `json:"input"` 49 TargetFormat string `json:"target_format"` 50 Result string `json:"result"` 51 Decimal string `json:"decimal"` 52 Integer uint32 `json:"integer"` 53 Binary string `json:"binary"` 54 Hex string `json:"hex"` 55} 56 57// NewIPCalculator 创建新的IP计算器 58func NewIPCalculator() *IPCalculator { 59 ipRegex := regexp.MustCompile(`^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$`) 60 return &IPCalculator{ 61 ipRegex: ipRegex, 62 } 63} 64 65// ValidateIP 验证IP地址格式 66func (c *IPCalculator) ValidateIP(ip string) bool { 67 if !c.ipRegex.MatchString(ip) { 68 return false 69 } 70 71 parts := strings.Split(ip, ".") 72 for _, part := range parts { 73 num, err := strconv.Atoi(part) 74 if err != nil || num < 0 || num > 255 { 75 return false 76 } 77 } 78 return true 79} 80 81// IPToInt IP地址转整数 82func (c *IPCalculator) IPToInt(ip string) (uint32, error) { 83 if !c.ValidateIP(ip) { 84 return 0, fmt.Errorf("无效的IP地址: %s", ip) 85 } 86 87 parts := strings.Split(ip, ".") 88 var result uint32 89 for i, part := range parts { 90 num, _ := strconv.Atoi(part) 91 result |= uint32(num) << ((3 - i) * 8) 92 } 93 return result, nil 94} 95 96// IntToIP 整数转IP地址 97func (c *IPCalculator) IntToIP(ipInt uint32) string { 98 parts := make([]string, 4) 99 for i := 0; i < 4; i++ { 100 parts[i] = strconv.Itoa(int((ipInt >> ((3 - i) * 8)) & 0xFF)) 101 } 102 return strings.Join(parts, ".") 103} 104 105// CalculateIP IP地址运算 106func (c *IPCalculator) CalculateIP(ip1, ip2 string, operation string) (*IPMathResult, error) { 107 ip1Int, err := c.IPToInt(ip1) 108 if err != nil { 109 return nil, fmt.Errorf("第一个IP地址无效: %v", err) 110 } 111 112 var ip2Int uint32 113 if c.ValidateIP(ip2) { 114 ip2Int, err = c.IPToInt(ip2) 115 if err != nil { 116 return nil, fmt.Errorf("第二个IP地址无效: %v", err) 117 } 118 } else { 119 // 尝试解析为数字 120 num, err := strconv.ParseUint(ip2, 10, 32) 121 if err != nil { 122 return nil, fmt.Errorf("第二个参数必须是有效的IP地址或数字") 123 } 124 ip2Int = uint32(num) 125 } 126 127 var result uint32 128 switch operation { 129 case "add": 130 result = ip1Int + ip2Int 131 case "subtract": 132 if ip1Int < ip2Int { 133 return nil, fmt.Errorf("减法结果不能为负数") 134 } 135 result = ip1Int - ip2Int 136 case "multiply": 137 result = ip1Int * ip2Int 138 case "divide": 139 if ip2Int == 0 { 140 return nil, fmt.Errorf("除数不能为零") 141 } 142 result = ip1Int / ip2Int 143 default: 144 return nil, fmt.Errorf("不支持的运算类型: %s", operation) 145 } 146 147 return &IPMathResult{ 148 Result: c.IntToIP(result), 149 ResultInt: result, 150 IP1Int: ip1Int, 151 IP2Int: ip2Int, 152 Operation: operation, 153 }, nil 154} 155 156// CalculateRange 计算IP范围 157func (c *IPCalculator) CalculateRange(startIP, endIP string) (*IPRangeResult, error) { 158 startInt, err := c.IPToInt(startIP) 159 if err != nil { 160 return nil, fmt.Errorf("起始IP无效: %v", err) 161 } 162 163 endInt, err := c.IPToInt(endIP) 164 if err != nil { 165 return nil, fmt.Errorf("结束IP无效: %v", err) 166 } 167 168 if startInt > endInt { 169 return nil, fmt.Errorf("起始IP不能大于结束IP") 170 } 171 172 count := endInt - startInt + 1 173 networkIP := c.IntToIP(startInt) 174 broadcastIP := c.IntToIP(endInt) 175 176 // 计算CIDR 177 cidr := 32 178 for (1 << (32 - cidr)) < int(count) { 179 cidr-- 180 } 181 182 return &IPRangeResult{ 183 StartIP: startIP, 184 EndIP: endIP, 185 Count: count, 186 NetworkIP: networkIP, 187 BroadcastIP: broadcastIP, 188 SuggestedCIDR: cidr, 189 SuggestedHosts: uint32(1 << (32 - cidr)), 190 }, nil 191} 192 193// ProcessIPList 处理IP列表(排序和去重) 194func (c *IPCalculator) ProcessIPList(ipList []string, removeDuplicates, sortAscending, validateIPs bool) *IPListResult { 195 validIPs := make([]string, 0) 196 invalidIPs := make([]string, 0) 197 198 // 验证IP 199 if validateIPs { 200 for _, ip := range ipList { 201 if c.ValidateIP(ip) { 202 validIPs = append(validIPs, ip) 203 } else { 204 invalidIPs = append(invalidIPs, ip) 205 } 206 } 207 } else { 208 validIPs = append(validIPs, ipList...) 209 } 210 211 // 去重 212 if removeDuplicates { 213 seen := make(map[string]bool) 214 uniqueIPs := make([]string, 0) 215 for _, ip := range validIPs { 216 if !seen[ip] { 217 seen[ip] = true 218 uniqueIPs = append(uniqueIPs, ip) 219 } 220 } 221 validIPs = uniqueIPs 222 } 223 224 // 排序 225 if sortAscending { 226 sort.Slice(validIPs, func(i, j int) bool { 227 ip1Int, _ := c.IPToInt(validIPs[i]) 228 ip2Int, _ := c.IPToInt(validIPs[j]) 229 return ip1Int < ip2Int 230 }) 231 } else { 232 sort.Slice(validIPs, func(i, j int) bool { 233 ip1Int, _ := c.IPToInt(validIPs[i]) 234 ip2Int, _ := c.IPToInt(validIPs[j]) 235 return ip1Int > ip2Int 236 }) 237 } 238 239 return &IPListResult{ 240 OriginalCount: len(ipList), 241 ValidCount: len(validIPs), 242 InvalidCount: len(invalidIPs), 243 ValidIPs: validIPs, 244 InvalidIPs: invalidIPs, 245 } 246} 247 248// ConvertIP IP地址格式转换 249func (c *IPCalculator) ConvertIP(input, targetFormat string) (*IPConvertResult, error) { 250 var inputInt uint32 251 var inputIP string 252 253 if c.ValidateIP(input) { 254 inputIP = input 255 var err error 256 inputInt, err = c.IPToInt(input) 257 if err != nil { 258 return nil, err 259 } 260 } else { 261 // 尝试解析为数字 262 num, err := strconv.ParseUint(input, 10, 32) 263 if err != nil { 264 return nil, fmt.Errorf("输入必须是有效的IP地址或数字") 265 } 266 inputInt = uint32(num) 267 inputIP = c.IntToIP(inputInt) 268 } 269 270 var result string 271 switch targetFormat { 272 case "decimal": 273 result = inputIP 274 case "binary": 275 binary := fmt.Sprintf("%032b", inputInt) 276 parts := make([]string, 4) 277 for i := 0; i < 4; i++ { 278 parts[i] = binary[i*8 : (i+1)*8] 279 } 280 result = strings.Join(parts, ".") 281 case "hex": 282 result = fmt.Sprintf("0x%08X", inputInt) 283 case "integer": 284 result = fmt.Sprintf("%d", inputInt) 285 case "reverse": 286 parts := strings.Split(inputIP, ".") 287 for i, j := 0, len(parts)-1; i < j; i, j = i+1, j-1 { 288 parts[i], parts[j] = parts[j], parts[i] 289 } 290 result = strings.Join(parts, ".") 291 default: 292 return nil, fmt.Errorf("不支持的转换格式: %s", targetFormat) 293 } 294 295 binary := fmt.Sprintf("%032b", inputInt) 296 binaryParts := make([]string, 4) 297 for i := 0; i < 4; i++ { 298 binaryParts[i] = binary[i*8 : (i+1)*8] 299 } 300 301 return &IPConvertResult{ 302 Input: input, 303 TargetFormat: targetFormat, 304 Result: result, 305 Decimal: inputIP, 306 Integer: inputInt, 307 Binary: strings.Join(binaryParts, "."), 308 Hex: fmt.Sprintf("0x%08X", inputInt), 309 }, nil 310} 311 312// GetSubnetInfo 获取子网信息 313func (c *IPCalculator) GetSubnetInfo(ip string, cidr int) (map[string]interface{}, error) { 314 if !c.ValidateIP(ip) { 315 return nil, fmt.Errorf("无效的IP地址: %s", ip) 316 } 317 318 if cidr < 0 || cidr > 32 { 319 return nil, fmt.Errorf("CIDR必须在0-32之间") 320 } 321 322 // 使用net包计算子网信息 323 _, network, err := net.ParseCIDR(fmt.Sprintf("%s/%d", ip, cidr)) 324 if err != nil { 325 return nil, fmt.Errorf("子网计算错误: %v", err) 326 } 327 328 // 计算网络地址和广播地址 329 networkIP := network.IP.To4() 330 if networkIP == nil { 331 return nil, fmt.Errorf("不是有效的IPv4地址") 332 } 333 334 // 计算广播地址 335 broadcastIP := make(net.IP, len(networkIP)) 336 copy(broadcastIP, networkIP) 337 for i := range broadcastIP { 338 broadcastIP[i] |= ^network.Mask[i] 339 } 340 341 // 计算主机数量 342 numAddresses := uint32(1) << (32 - cidr) 343 numHosts := numAddresses - 2 // 减去网络地址和广播地址 344 345 return map[string]interface{}{ 346 "network_address": networkIP.String(), 347 "broadcast_address": broadcastIP.String(), 348 "netmask": net.IP(network.Mask).String(), 349 "num_addresses": numAddresses, 350 "num_hosts": numHosts, 351 }, nil 352} 353 354func main() { 355 calculator := NewIPCalculator() 356 357 fmt.Println("=== IP地址计算器示例 ===\n") 358 359 // IP地址运算示例 360 fmt.Println("IP运算结果:") 361 mathResult, err := calculator.CalculateIP("192.168.1.1", "1", "add") 362 if err != nil { 363 fmt.Printf("IP运算错误: %v\n", err) 364 } else { 365 fmt.Printf(" 192.168.1.1 + 1 = %s\n", mathResult.Result) 366 fmt.Printf(" 整数表示: %d\n", mathResult.ResultInt) 367 } 368 369 fmt.Println() 370 371 // 范围计算示例 372 fmt.Println("范围计算结果:") 373 rangeResult, err := calculator.CalculateRange("192.168.1.1", "192.168.1.254") 374 if err != nil { 375 fmt.Printf("范围计算错误: %v\n", err) 376 } else { 377 fmt.Printf(" 起始IP: %s\n", rangeResult.StartIP) 378 fmt.Printf(" 结束IP: %s\n", rangeResult.EndIP) 379 fmt.Printf(" IP数量: %d\n", rangeResult.Count) 380 fmt.Printf(" 建议CIDR: /%d\n", rangeResult.SuggestedCIDR) 381 } 382 383 fmt.Println() 384 385 // IP列表处理示例 386 fmt.Println("IP列表处理结果:") 387 ipList := []string{"192.168.1.1", "10.0.0.1", "172.16.0.1", "192.168.1.1", "192.168.1.100"} 388 listResult := calculator.ProcessIPList(ipList, true, true, true) 389 fmt.Printf(" 原始数量: %d\n", listResult.OriginalCount) 390 fmt.Printf(" 有效数量: %d\n", listResult.ValidCount) 391 fmt.Printf(" 无效数量: %d\n", listResult.InvalidCount) 392 fmt.Printf(" 处理后的IP: %v\n", listResult.ValidIPs) 393 394 fmt.Println() 395 396 // 格式转换示例 397 fmt.Println("格式转换结果:") 398 convertResult, err := calculator.ConvertIP("192.168.1.1", "binary") 399 if err != nil { 400 fmt.Printf("格式转换错误: %v\n", err) 401 } else { 402 fmt.Printf(" 输入: %s\n", convertResult.Input) 403 fmt.Printf(" 目标格式: %s\n", convertResult.TargetFormat) 404 fmt.Printf(" 结果: %s\n", convertResult.Result) 405 fmt.Printf(" 二进制: %s\n", convertResult.Binary) 406 fmt.Printf(" 十六进制: %s\n", convertResult.Hex) 407 } 408 409 fmt.Println() 410 411 // 子网信息示例 412 fmt.Println("子网信息:") 413 subnetResult, err := calculator.GetSubnetInfo("192.168.1.0", 24) 414 if err != nil { 415 fmt.Printf("子网信息错误: %v\n", err) 416 } else { 417 fmt.Printf(" 网络地址: %s\n", subnetResult["network_address"]) 418 fmt.Printf(" 广播地址: %s\n", subnetResult["broadcast_address"]) 419 fmt.Printf(" 子网掩码: %s\n", subnetResult["netmask"]) 420 fmt.Printf(" 总地址数: %d\n", subnetResult["num_addresses"]) 421 fmt.Printf(" 可用主机数: %d\n", subnetResult["num_hosts"]) 422 } 423}
-
ip_calculator (JAVA)
1import java.util.*; 2import java.util.regex.Pattern; 3import java.util.regex.Matcher; 4 5/** 6 * IP地址计算器 - Java版本 7 * 支持IP地址运算、范围计算、排序和去重、格式转换等功能 8 */ 9public class IPCalculator { 10 private static final Pattern IP_PATTERN = Pattern.compile("^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$"); 11 12 /** 13 * IP运算结果类 14 */ 15 public static class IPMathResult { 16 private String result; 17 private long resultInt; 18 private long ip1Int; 19 private long ip2Int; 20 private String operation; 21 22 public IPMathResult(String result, long resultInt, long ip1Int, long ip2Int, String operation) { 23 this.result = result; 24 this.resultInt = resultInt; 25 this.ip1Int = ip1Int; 26 this.ip2Int = ip2Int; 27 this.operation = operation; 28 } 29 30 // Getters 31 public String getResult() { return result; } 32 public long getResultInt() { return resultInt; } 33 public long getIp1Int() { return ip1Int; } 34 public long getIp2Int() { return ip2Int; } 35 public String getOperation() { return operation; } 36 } 37 38 /** 39 * IP范围结果类 40 */ 41 public static class IPRangeResult { 42 private String startIP; 43 private String endIP; 44 private long count; 45 private String networkIP; 46 private String broadcastIP; 47 private int suggestedCIDR; 48 private long suggestedHosts; 49 50 public IPRangeResult(String startIP, String endIP, long count, String networkIP, 51 String broadcastIP, int suggestedCIDR, long suggestedHosts) { 52 this.startIP = startIP; 53 this.endIP = endIP; 54 this.count = count; 55 this.networkIP = networkIP; 56 this.broadcastIP = broadcastIP; 57 this.suggestedCIDR = suggestedCIDR; 58 this.suggestedHosts = suggestedHosts; 59 } 60 61 // Getters 62 public String getStartIP() { return startIP; } 63 public String getEndIP() { return endIP; } 64 public long getCount() { return count; } 65 public String getNetworkIP() { return networkIP; } 66 public String getBroadcastIP() { return broadcastIP; } 67 public int getSuggestedCIDR() { return suggestedCIDR; } 68 public long getSuggestedHosts() { return suggestedHosts; } 69 } 70 71 /** 72 * IP列表处理结果类 73 */ 74 public static class IPListResult { 75 private int originalCount; 76 private int validCount; 77 private int invalidCount; 78 private List<String> validIPs; 79 private List<String> invalidIPs; 80 81 public IPListResult(int originalCount, int validCount, int invalidCount, 82 List<String> validIPs, List<String> invalidIPs) { 83 this.originalCount = originalCount; 84 this.validCount = validCount; 85 this.invalidCount = invalidCount; 86 this.validIPs = validIPs; 87 this.invalidIPs = invalidIPs; 88 } 89 90 // Getters 91 public int getOriginalCount() { return originalCount; } 92 public int getValidCount() { return validCount; } 93 public int getInvalidCount() { return invalidCount; } 94 public List<String> getValidIPs() { return validIPs; } 95 public List<String> getInvalidIPs() { return invalidIPs; } 96 } 97 98 /** 99 * IP转换结果类 100 */ 101 public static class IPConvertResult { 102 private String input; 103 private String targetFormat; 104 private String result; 105 private String decimal; 106 private long integer; 107 private String binary; 108 private String hex; 109 110 public IPConvertResult(String input, String targetFormat, String result, 111 String decimal, long integer, String binary, String hex) { 112 this.input = input; 113 this.targetFormat = targetFormat; 114 this.result = result; 115 this.decimal = decimal; 116 this.integer = integer; 117 this.binary = binary; 118 this.hex = hex; 119 } 120 121 // Getters 122 public String getInput() { return input; } 123 public String getTargetFormat() { return targetFormat; } 124 public String getResult() { return result; } 125 public String getDecimal() { return decimal; } 126 public long getInteger() { return integer; } 127 public String getBinary() { return binary; } 128 public String getHex() { return hex; } 129 } 130 131 /** 132 * 验证IP地址格式 133 * @param ip IP地址字符串 134 * @return 是否有效 135 */ 136 public boolean validateIP(String ip) { 137 if (ip == null || ip.isEmpty()) { 138 return false; 139 } 140 141 Matcher matcher = IP_PATTERN.matcher(ip); 142 if (!matcher.matches()) { 143 return false; 144 } 145 146 for (int i = 1; i <= 4; i++) { 147 int part = Integer.parseInt(matcher.group(i)); 148 if (part < 0 || part > 255) { 149 return false; 150 } 151 } 152 return true; 153 } 154 155 /** 156 * IP地址转整数 157 * @param ip IP地址字符串 158 * @return 整数 159 */ 160 public long ipToInt(String ip) throws IllegalArgumentException { 161 if (!validateIP(ip)) { 162 throw new IllegalArgumentException("无效的IP地址: " + ip); 163 } 164 165 String[] parts = ip.split("\\."); 166 long result = 0; 167 for (int i = 0; i < 4; i++) { 168 result |= (Long.parseLong(parts[i]) << ((3 - i) * 8)); 169 } 170 return result; 171 } 172 173 /** 174 * 整数转IP地址 175 * @param ipInt 整数 176 * @return IP地址字符串 177 */ 178 public String intToIP(long ipInt) { 179 return String.format("%d.%d.%d.%d", 180 (ipInt >> 24) & 0xFF, 181 (ipInt >> 16) & 0xFF, 182 (ipInt >> 8) & 0xFF, 183 ipInt & 0xFF 184 ); 185 } 186 187 /** 188 * IP地址运算 189 * @param ip1 第一个IP地址 190 * @param ip2 第二个IP地址或数字 191 * @param operation 运算类型 (add, subtract, multiply, divide) 192 * @return 计算结果 193 */ 194 public IPMathResult calculateIP(String ip1, String ip2, String operation) throws IllegalArgumentException { 195 long ip1Int = ipToInt(ip1); 196 long ip2Int; 197 198 if (validateIP(ip2)) { 199 ip2Int = ipToInt(ip2); 200 } else { 201 try { 202 ip2Int = Long.parseLong(ip2); 203 } catch (NumberFormatException e) { 204 throw new IllegalArgumentException("第二个参数必须是有效的IP地址或数字"); 205 } 206 } 207 208 long result; 209 switch (operation) { 210 case "add": 211 result = ip1Int + ip2Int; 212 break; 213 case "subtract": 214 if (ip1Int < ip2Int) { 215 throw new IllegalArgumentException("减法结果不能为负数"); 216 } 217 result = ip1Int - ip2Int; 218 break; 219 case "multiply": 220 result = ip1Int * ip2Int; 221 break; 222 case "divide": 223 if (ip2Int == 0) { 224 throw new IllegalArgumentException("除数不能为零"); 225 } 226 result = ip1Int / ip2Int; 227 break; 228 default: 229 throw new IllegalArgumentException("不支持的运算类型: " + operation); 230 } 231 232 if (result < 0 || result > 4294967295L) { 233 throw new IllegalArgumentException("计算结果超出IP地址范围"); 234 } 235 236 return new IPMathResult(intToIP(result), result, ip1Int, ip2Int, operation); 237 } 238 239 /** 240 * 计算IP范围 241 * @param startIP 起始IP 242 * @param endIP 结束IP 243 * @return 范围信息 244 */ 245 public IPRangeResult calculateRange(String startIP, String endIP) throws IllegalArgumentException { 246 long startInt = ipToInt(startIP); 247 long endInt = ipToInt(endIP); 248 249 if (startInt > endInt) { 250 throw new IllegalArgumentException("起始IP不能大于结束IP"); 251 } 252 253 long count = endInt - startInt + 1; 254 String networkIP = intToIP(startInt); 255 String broadcastIP = intToIP(endInt); 256 257 // 计算CIDR 258 int cidr = 32; 259 while ((1L << (32 - cidr)) < count) { 260 cidr--; 261 } 262 263 return new IPRangeResult(startIP, endIP, count, networkIP, broadcastIP, cidr, 1L << (32 - cidr)); 264 } 265 266 /** 267 * 处理IP列表(排序和去重) 268 * @param ipList IP地址列表 269 * @param removeDuplicates 是否去重 270 * @param sortAscending 是否升序排列 271 * @param validateIPs 是否验证IP格式 272 * @return 处理结果 273 */ 274 public IPListResult processIPList(List<String> ipList, boolean removeDuplicates, 275 boolean sortAscending, boolean validateIPs) { 276 List<String> validIPs = new ArrayList<>(); 277 List<String> invalidIPs = new ArrayList<>(); 278 279 // 验证IP 280 if (validateIPs) { 281 for (String ip : ipList) { 282 if (validateIP(ip)) { 283 validIPs.add(ip); 284 } else { 285 invalidIPs.add(ip); 286 } 287 } 288 } else { 289 validIPs.addAll(ipList); 290 } 291 292 // 去重 293 if (removeDuplicates) { 294 Set<String> seen = new LinkedHashSet<>(); 295 seen.addAll(validIPs); 296 validIPs = new ArrayList<>(seen); 297 } 298 299 // 排序 300 if (sortAscending) { 301 validIPs.sort((a, b) -> { 302 try { 303 return Long.compare(ipToInt(a), ipToInt(b)); 304 } catch (IllegalArgumentException e) { 305 return 0; 306 } 307 }); 308 } else { 309 validIPs.sort((a, b) -> { 310 try { 311 return Long.compare(ipToInt(b), ipToInt(a)); 312 } catch (IllegalArgumentException e) { 313 return 0; 314 } 315 }); 316 } 317 318 return new IPListResult(ipList.size(), validIPs.size(), invalidIPs.size(), validIPs, invalidIPs); 319 } 320 321 /** 322 * IP地址格式转换 323 * @param input 输入IP地址或整数 324 * @param targetFormat 目标格式 325 * @return 转换结果 326 */ 327 public IPConvertResult convertIP(String input, String targetFormat) throws IllegalArgumentException { 328 long inputInt; 329 String inputIP; 330 331 if (validateIP(input)) { 332 inputIP = input; 333 inputInt = ipToInt(inputIP); 334 } else { 335 try { 336 inputInt = Long.parseLong(input); 337 inputIP = intToIP(inputInt); 338 } catch (NumberFormatException e) { 339 throw new IllegalArgumentException("输入必须是有效的IP地址或数字"); 340 } 341 } 342 343 String result; 344 switch (targetFormat) { 345 case "decimal": 346 result = inputIP; 347 break; 348 case "binary": 349 String binary = String.format("%32s", Long.toBinaryString(inputInt)).replace(' ', '0'); 350 result = String.format("%s.%s.%s.%s", 351 binary.substring(0, 8), 352 binary.substring(8, 16), 353 binary.substring(16, 24), 354 binary.substring(24, 32) 355 ); 356 break; 357 case "hex": 358 result = String.format("0x%08X", inputInt); 359 break; 360 case "integer": 361 result = String.valueOf(inputInt); 362 break; 363 case "reverse": 364 String[] parts = inputIP.split("\\."); 365 result = String.format("%s.%s.%s.%s", parts[3], parts[2], parts[1], parts[0]); 366 break; 367 default: 368 throw new IllegalArgumentException("不支持的转换格式: " + targetFormat); 369 } 370 371 String binary = String.format("%32s", Long.toBinaryString(inputInt)).replace(' ', '0'); 372 String binaryFormatted = String.format("%s.%s.%s.%s", 373 binary.substring(0, 8), 374 binary.substring(8, 16), 375 binary.substring(16, 24), 376 binary.substring(24, 32) 377 ); 378 379 return new IPConvertResult(input, targetFormat, result, inputIP, inputInt, binaryFormatted, 380 String.format("0x%08X", inputInt)); 381 } 382 383 /** 384 * 主函数 - 使用示例 385 */ 386 public static void main(String[] args) { 387 IPCalculator calculator = new IPCalculator(); 388 389 System.out.println("=== IP地址计算器示例 ===\n"); 390 391 // IP地址运算示例 392 System.out.println("IP运算结果:"); 393 try { 394 IPMathResult mathResult = calculator.calculateIP("192.168.1.1", "1", "add"); 395 System.out.printf(" 192.168.1.1 + 1 = %s%n", mathResult.getResult()); 396 System.out.printf(" 整数表示: %d%n", mathResult.getResultInt()); 397 } catch (Exception e) { 398 System.out.printf("IP运算错误: %s%n", e.getMessage()); 399 } 400 401 System.out.println(); 402 403 // 范围计算示例 404 System.out.println("范围计算结果:"); 405 try { 406 IPRangeResult rangeResult = calculator.calculateRange("192.168.1.1", "192.168.1.254"); 407 System.out.printf(" 起始IP: %s%n", rangeResult.getStartIP()); 408 System.out.printf(" 结束IP: %s%n", rangeResult.getEndIP()); 409 System.out.printf(" IP数量: %d%n", rangeResult.getCount()); 410 System.out.printf(" 建议CIDR: /%d%n", rangeResult.getSuggestedCIDR()); 411 } catch (Exception e) { 412 System.out.printf("范围计算错误: %s%n", e.getMessage()); 413 } 414 415 System.out.println(); 416 417 // IP列表处理示例 418 System.out.println("IP列表处理结果:"); 419 List<String> ipList = Arrays.asList("192.168.1.1", "10.0.0.1", "172.16.0.1", "192.168.1.1", "192.168.1.100"); 420 IPListResult listResult = calculator.processIPList(ipList, true, true, true); 421 System.out.printf(" 原始数量: %d%n", listResult.getOriginalCount()); 422 System.out.printf(" 有效数量: %d%n", listResult.getValidCount()); 423 System.out.printf(" 无效数量: %d%n", listResult.getInvalidCount()); 424 System.out.printf(" 处理后的IP: %s%n", listResult.getValidIPs()); 425 426 System.out.println(); 427 428 // 格式转换示例 429 System.out.println("格式转换结果:"); 430 try { 431 IPConvertResult convertResult = calculator.convertIP("192.168.1.1", "binary"); 432 System.out.printf(" 输入: %s%n", convertResult.getInput()); 433 System.out.printf(" 目标格式: %s%n", convertResult.getTargetFormat()); 434 System.out.printf(" 结果: %s%n", convertResult.getResult()); 435 System.out.printf(" 二进制: %s%n", convertResult.getBinary()); 436 System.out.printf(" 十六进制: %s%n", convertResult.getHex()); 437 } catch (Exception e) { 438 System.out.printf("格式转换错误: %s%n", e.getMessage()); 439 } 440 } 441}
-
ip_calculator (JS)
1/** 2 * IP地址计算器 - JavaScript版本 3 * 支持IP地址运算、范围计算、排序和去重、格式转换等功能 4 */ 5 6class IPCalculator { 7 constructor() { 8 this.ipRegex = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/; 9 } 10 11 /** 12 * 验证IP地址格式 13 * @param {string} ip - IP地址 14 * @returns {boolean} 是否有效 15 */ 16 validateIP(ip) { 17 if (!this.ipRegex.test(ip)) return false; 18 19 const parts = ip.split('.').map(Number); 20 return parts.every(part => part >= 0 && part <= 255); 21 } 22 23 /** 24 * IP地址转整数 25 * @param {string} ip - IP地址 26 * @returns {number} 整数 27 */ 28 ipToInt(ip) { 29 const parts = ip.split('.').map(Number); 30 return (parts[0] << 24) + (parts[1] << 16) + (parts[2] << 8) + parts[3]; 31 } 32 33 /** 34 * 整数转IP地址 35 * @param {number} int - 整数 36 * @returns {string} IP地址 37 */ 38 intToIP(int) { 39 return [ 40 (int >>> 24) & 255, 41 (int >>> 16) & 255, 42 (int >>> 8) & 255, 43 int & 255 44 ].join('.'); 45 } 46 47 /** 48 * IP地址运算 49 * @param {string} ip1 - 第一个IP地址 50 * @param {string} ip2 - 第二个IP地址或数字 51 * @param {string} operation - 运算类型 (add, subtract, multiply, divide) 52 * @returns {object} 计算结果 53 */ 54 calculateIP(ip1, ip2, operation) { 55 if (!this.validateIP(ip1)) { 56 throw new Error('第一个IP地址格式无效'); 57 } 58 59 const ip1Int = this.ipToInt(ip1); 60 let ip2Int; 61 62 if (this.validateIP(ip2)) { 63 ip2Int = this.ipToInt(ip2); 64 } else if (/^\d+$/.test(ip2)) { 65 ip2Int = parseInt(ip2); 66 } else { 67 throw new Error('第二个参数必须是有效的IP地址或数字'); 68 } 69 70 let result; 71 switch (operation) { 72 case 'add': 73 result = ip1Int + ip2Int; 74 break; 75 case 'subtract': 76 result = ip1Int - ip2Int; 77 break; 78 case 'multiply': 79 result = ip1Int * ip2Int; 80 break; 81 case 'divide': 82 result = Math.floor(ip1Int / ip2Int); 83 break; 84 default: 85 throw new Error('不支持的运算类型'); 86 } 87 88 if (result < 0 || result > 4294967295) { 89 throw new Error('计算结果超出IP地址范围'); 90 } 91 92 return { 93 result: this.intToIP(result), 94 resultInt: result, 95 ip1Int: ip1Int, 96 ip2Int: ip2Int, 97 operation: operation 98 }; 99 } 100 101 /** 102 * 计算IP范围 103 * @param {string} startIP - 起始IP 104 * @param {string} endIP - 结束IP 105 * @returns {object} 范围信息 106 */ 107 calculateRange(startIP, endIP) { 108 if (!this.validateIP(startIP) || !this.validateIP(endIP)) { 109 throw new Error('IP地址格式无效'); 110 } 111 112 const startInt = this.ipToInt(startIP); 113 const endInt = this.ipToInt(endIP); 114 115 if (startInt > endInt) { 116 throw new Error('起始IP不能大于结束IP'); 117 } 118 119 const count = endInt - startInt + 1; 120 const networkIP = this.intToIP(startInt); 121 const broadcastIP = this.intToIP(endInt); 122 123 // 计算CIDR 124 let cidr = 32; 125 while (Math.pow(2, 32 - cidr) < count) { 126 cidr--; 127 } 128 129 return { 130 startIP: startIP, 131 endIP: endIP, 132 count: count, 133 networkIP: networkIP, 134 broadcastIP: broadcastIP, 135 suggestedCIDR: cidr, 136 suggestedHosts: Math.pow(2, 32 - cidr) 137 }; 138 } 139 140 /** 141 * 处理IP列表(排序和去重) 142 * @param {string[]} ipList - IP地址列表 143 * @param {object} options - 选项 144 * @returns {object} 处理结果 145 */ 146 processIPList(ipList, options = {}) { 147 const { 148 removeDuplicates = true, 149 sortAscending = true, 150 validateIPs = true 151 } = options; 152 153 let validIPs = []; 154 let invalidIPs = []; 155 156 // 验证IP 157 if (validateIPs) { 158 ipList.forEach(ip => { 159 if (this.validateIP(ip)) { 160 validIPs.push(ip); 161 } else { 162 invalidIPs.push(ip); 163 } 164 }); 165 } else { 166 validIPs = [...ipList]; 167 } 168 169 // 去重 170 if (removeDuplicates) { 171 validIPs = [...new Set(validIPs)]; 172 } 173 174 // 排序 175 if (sortAscending) { 176 validIPs.sort((a, b) => this.ipToInt(a) - this.ipToInt(b)); 177 } else { 178 validIPs.sort((a, b) => this.ipToInt(b) - this.ipToInt(a)); 179 } 180 181 return { 182 originalCount: ipList.length, 183 validCount: validIPs.length, 184 invalidCount: invalidIPs.length, 185 validIPs: validIPs, 186 invalidIPs: invalidIPs 187 }; 188 } 189 190 /** 191 * IP地址格式转换 192 * @param {string} input - 输入IP地址或整数 193 * @param {string} targetFormat - 目标格式 194 * @returns {object} 转换结果 195 */ 196 convertIP(input, targetFormat) { 197 let inputInt, inputIP; 198 199 if (this.validateIP(input)) { 200 inputIP = input; 201 inputInt = this.ipToInt(inputIP); 202 } else if (/^\d+$/.test(input)) { 203 inputInt = parseInt(input); 204 inputIP = this.intToIP(inputInt); 205 } else { 206 throw new Error('输入必须是有效的IP地址或数字'); 207 } 208 209 let result; 210 switch (targetFormat) { 211 case 'decimal': 212 result = inputIP; 213 break; 214 case 'binary': 215 result = inputInt.toString(2).padStart(32, '0').match(/.{1,8}/g).join('.'); 216 break; 217 case 'hex': 218 result = '0x' + inputInt.toString(16).toUpperCase().padStart(8, '0'); 219 break; 220 case 'integer': 221 result = inputInt.toString(); 222 break; 223 case 'reverse': 224 result = inputIP.split('.').reverse().join('.'); 225 break; 226 default: 227 throw new Error('不支持的转换格式'); 228 } 229 230 return { 231 input: input, 232 targetFormat: targetFormat, 233 result: result, 234 decimal: inputIP, 235 integer: inputInt, 236 binary: inputInt.toString(2).padStart(32, '0').match(/.{1,8}/g).join('.'), 237 hex: '0x' + inputInt.toString(16).toUpperCase().padStart(8, '0') 238 }; 239 } 240} 241 242// 使用示例 243const calculator = new IPCalculator(); 244 245// IP地址运算示例 246try { 247 const mathResult = calculator.calculateIP('192.168.1.1', '1', 'add'); 248 console.log('IP运算结果:', mathResult); 249} catch (error) { 250 console.error('IP运算错误:', error.message); 251} 252 253// 范围计算示例 254try { 255 const rangeResult = calculator.calculateRange('192.168.1.1', '192.168.1.254'); 256 console.log('范围计算结果:', rangeResult); 257} catch (error) { 258 console.error('范围计算错误:', error.message); 259} 260 261// IP列表处理示例 262try { 263 const ipList = ['192.168.1.1', '10.0.0.1', '172.16.0.1', '192.168.1.1', '192.168.1.100']; 264 const processResult = calculator.processIPList(ipList, { 265 removeDuplicates: true, 266 sortAscending: true, 267 validateIPs: true 268 }); 269 console.log('IP列表处理结果:', processResult); 270} catch (error) { 271 console.error('IP列表处理错误:', error.message); 272} 273 274// 格式转换示例 275try { 276 const convertResult = calculator.convertIP('192.168.1.1', 'binary'); 277 console.log('格式转换结果:', convertResult); 278} catch (error) { 279 console.error('格式转换错误:', error.message); 280}
-
ip_calculator (PHP)
1<?php 2/** 3 * IP地址计算器 - PHP版本 4 * 支持IP地址运算、范围计算、排序和去重、格式转换等功能 5 */ 6 7class IPCalculator { 8 private $ipRegex; 9 10 public function __construct() { 11 $this->ipRegex = '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/'; 12 } 13 14 /** 15 * 验证IP地址格式 16 * @param string $ip IP地址字符串 17 * @return bool 是否有效 18 */ 19 public function validateIP($ip) { 20 if (empty($ip)) { 21 return false; 22 } 23 24 if (!preg_match($this->ipRegex, $ip, $matches)) { 25 return false; 26 } 27 28 for ($i = 1; $i <= 4; $i++) { 29 $part = intval($matches[$i]); 30 if ($part < 0 || $part > 255) { 31 return false; 32 } 33 } 34 return true; 35 } 36 37 /** 38 * IP地址转整数 39 * @param string $ip IP地址字符串 40 * @return int 整数 41 * @throws Exception 42 */ 43 public function ipToInt($ip) { 44 if (!$this->validateIP($ip)) { 45 throw new Exception("无效的IP地址: $ip"); 46 } 47 48 $parts = explode('.', $ip); 49 $result = 0; 50 for ($i = 0; $i < 4; $i++) { 51 $result |= (intval($parts[$i]) << ((3 - $i) * 8)); 52 } 53 return $result; 54 } 55 56 /** 57 * 整数转IP地址 58 * @param int $ipInt 整数 59 * @return string IP地址字符串 60 */ 61 public function intToIP($ipInt) { 62 return sprintf('%d.%d.%d.%d', 63 ($ipInt >> 24) & 0xFF, 64 ($ipInt >> 16) & 0xFF, 65 ($ipInt >> 8) & 0xFF, 66 $ipInt & 0xFF 67 ); 68 } 69 70 /** 71 * IP地址运算 72 * @param string $ip1 第一个IP地址 73 * @param string $ip2 第二个IP地址或数字 74 * @param string $operation 运算类型 (add, subtract, multiply, divide) 75 * @return array 计算结果 76 * @throws Exception 77 */ 78 public function calculateIP($ip1, $ip2, $operation) { 79 $ip1Int = $this->ipToInt($ip1); 80 $ip2Int = null; 81 82 if ($this->validateIP($ip2)) { 83 $ip2Int = $this->ipToInt($ip2); 84 } elseif (is_numeric($ip2)) { 85 $ip2Int = intval($ip2); 86 } else { 87 throw new Exception("第二个参数必须是有效的IP地址或数字"); 88 } 89 90 switch ($operation) { 91 case 'add': 92 $result = $ip1Int + $ip2Int; 93 break; 94 case 'subtract': 95 if ($ip1Int < $ip2Int) { 96 throw new Exception("减法结果不能为负数"); 97 } 98 $result = $ip1Int - $ip2Int; 99 break; 100 case 'multiply': 101 $result = $ip1Int * $ip2Int; 102 break; 103 case 'divide': 104 if ($ip2Int == 0) { 105 throw new Exception("除数不能为零"); 106 } 107 $result = intval($ip1Int / $ip2Int); 108 break; 109 default: 110 throw new Exception("不支持的运算类型: $operation"); 111 } 112 113 if ($result < 0 || $result > 4294967295) { 114 throw new Exception("计算结果超出IP地址范围"); 115 } 116 117 return [ 118 'result' => $this->intToIP($result), 119 'result_int' => $result, 120 'ip1_int' => $ip1Int, 121 'ip2_int' => $ip2Int, 122 'operation' => $operation 123 ]; 124 } 125 126 /** 127 * 计算IP范围 128 * @param string $startIP 起始IP 129 * @param string $endIP 结束IP 130 * @return array 范围信息 131 * @throws Exception 132 */ 133 public function calculateRange($startIP, $endIP) { 134 $startInt = $this->ipToInt($startIP); 135 $endInt = $this->ipToInt($endIP); 136 137 if ($startInt > $endInt) { 138 throw new Exception("起始IP不能大于结束IP"); 139 } 140 141 $count = $endInt - $startInt + 1; 142 $networkIP = $this->intToIP($startInt); 143 $broadcastIP = $this->intToIP($endInt); 144 145 // 计算CIDR 146 $cidr = 32; 147 while (pow(2, 32 - $cidr) < $count) { 148 $cidr--; 149 } 150 151 return [ 152 'start_ip' => $startIP, 153 'end_ip' => $endIP, 154 'count' => $count, 155 'network_ip' => $networkIP, 156 'broadcast_ip' => $broadcastIP, 157 'suggested_cidr' => $cidr, 158 'suggested_hosts' => pow(2, 32 - $cidr) 159 ]; 160 } 161 162 /** 163 * 处理IP列表(排序和去重) 164 * @param array $ipList IP地址列表 165 * @param bool $removeDuplicates 是否去重 166 * @param bool $sortAscending 是否升序排列 167 * @param bool $validateIPs 是否验证IP格式 168 * @return array 处理结果 169 */ 170 public function processIPList($ipList, $removeDuplicates = true, $sortAscending = true, $validateIPs = true) { 171 $validIPs = []; 172 $invalidIPs = []; 173 174 // 验证IP 175 if ($validateIPs) { 176 foreach ($ipList as $ip) { 177 if ($this->validateIP($ip)) { 178 $validIPs[] = $ip; 179 } else { 180 $invalidIPs[] = $ip; 181 } 182 } 183 } else { 184 $validIPs = $ipList; 185 } 186 187 // 去重 188 if ($removeDuplicates) { 189 $validIPs = array_unique($validIPs); 190 $validIPs = array_values($validIPs); // 重新索引 191 } 192 193 // 排序 194 if ($sortAscending) { 195 usort($validIPs, function($a, $b) { 196 try { 197 return $this->ipToInt($a) - $this->ipToInt($b); 198 } catch (Exception $e) { 199 return 0; 200 } 201 }); 202 } else { 203 usort($validIPs, function($a, $b) { 204 try { 205 return $this->ipToInt($b) - $this->ipToInt($a); 206 } catch (Exception $e) { 207 return 0; 208 } 209 }); 210 } 211 212 return [ 213 'original_count' => count($ipList), 214 'valid_count' => count($validIPs), 215 'invalid_count' => count($invalidIPs), 216 'valid_ips' => $validIPs, 217 'invalid_ips' => $invalidIPs 218 ]; 219 } 220 221 /** 222 * IP地址格式转换 223 * @param string $input 输入IP地址或整数 224 * @param string $targetFormat 目标格式 225 * @return array 转换结果 226 * @throws Exception 227 */ 228 public function convertIP($input, $targetFormat) { 229 $inputInt = null; 230 $inputIP = null; 231 232 if ($this->validateIP($input)) { 233 $inputIP = $input; 234 $inputInt = $this->ipToInt($inputIP); 235 } elseif (is_numeric($input)) { 236 $inputInt = intval($input); 237 $inputIP = $this->intToIP($inputInt); 238 } else { 239 throw new Exception("输入必须是有效的IP地址或数字"); 240 } 241 242 switch ($targetFormat) { 243 case 'decimal': 244 $result = $inputIP; 245 break; 246 case 'binary': 247 $binary = str_pad(decbin($inputInt), 32, '0', STR_PAD_LEFT); 248 $result = sprintf('%s.%s.%s.%s', 249 substr($binary, 0, 8), 250 substr($binary, 8, 8), 251 substr($binary, 16, 8), 252 substr($binary, 24, 8) 253 ); 254 break; 255 case 'hex': 256 $result = sprintf('0x%08X', $inputInt); 257 break; 258 case 'integer': 259 $result = strval($inputInt); 260 break; 261 case 'reverse': 262 $parts = explode('.', $inputIP); 263 $result = implode('.', array_reverse($parts)); 264 break; 265 default: 266 throw new Exception("不支持的转换格式: $targetFormat"); 267 } 268 269 $binary = str_pad(decbin($inputInt), 32, '0', STR_PAD_LEFT); 270 $binaryFormatted = sprintf('%s.%s.%s.%s', 271 substr($binary, 0, 8), 272 substr($binary, 8, 8), 273 substr($binary, 16, 8), 274 substr($binary, 24, 8) 275 ); 276 277 return [ 278 'input' => $input, 279 'target_format' => $targetFormat, 280 'result' => $result, 281 'decimal' => $inputIP, 282 'integer' => $inputInt, 283 'binary' => $binaryFormatted, 284 'hex' => sprintf('0x%08X', $inputInt) 285 ]; 286 } 287 288 /** 289 * 获取子网信息 290 * @param string $ip IP地址 291 * @param int $cidr CIDR前缀长度 292 * @return array 子网信息 293 * @throws Exception 294 */ 295 public function getSubnetInfo($ip, $cidr) { 296 if (!$this->validateIP($ip)) { 297 throw new Exception("无效的IP地址: $ip"); 298 } 299 300 if ($cidr < 0 || $cidr > 32) { 301 throw new Exception("CIDR必须在0-32之间"); 302 } 303 304 // 使用PHP内置函数计算子网信息 305 $network = long2ip(ip2long($ip) & (-1 << (32 - $cidr))); 306 $broadcast = long2ip(ip2long($network) | ((1 << (32 - $cidr)) - 1)); 307 $netmask = long2ip(-1 << (32 - $cidr)); 308 309 $numAddresses = pow(2, 32 - $cidr); 310 $numHosts = $numAddresses - 2; // 减去网络地址和广播地址 311 312 return [ 313 'network_address' => $network, 314 'broadcast_address' => $broadcast, 315 'netmask' => $netmask, 316 'num_addresses' => $numAddresses, 317 'num_hosts' => $numHosts 318 ]; 319 } 320} 321 322// 使用示例 323function main() { 324 $calculator = new IPCalculator(); 325 326 echo "=== IP地址计算器示例 ===\n\n"; 327 328 // IP地址运算示例 329 echo "IP运算结果:\n"; 330 try { 331 $mathResult = $calculator->calculateIP('192.168.1.1', '1', 'add'); 332 echo " 192.168.1.1 + 1 = " . $mathResult['result'] . "\n"; 333 echo " 整数表示: " . $mathResult['result_int'] . "\n"; 334 } catch (Exception $e) { 335 echo "IP运算错误: " . $e->getMessage() . "\n"; 336 } 337 338 echo "\n"; 339 340 // 范围计算示例 341 echo "范围计算结果:\n"; 342 try { 343 $rangeResult = $calculator->calculateRange('192.168.1.1', '192.168.1.254'); 344 echo " 起始IP: " . $rangeResult['start_ip'] . "\n"; 345 echo " 结束IP: " . $rangeResult['end_ip'] . "\n"; 346 echo " IP数量: " . $rangeResult['count'] . "\n"; 347 echo " 建议CIDR: /" . $rangeResult['suggested_cidr'] . "\n"; 348 } catch (Exception $e) { 349 echo "范围计算错误: " . $e->getMessage() . "\n"; 350 } 351 352 echo "\n"; 353 354 // IP列表处理示例 355 echo "IP列表处理结果:\n"; 356 $ipList = ['192.168.1.1', '10.0.0.1', '172.16.0.1', '192.168.1.1', '192.168.1.100']; 357 $listResult = $calculator->processIPList($ipList, true, true, true); 358 echo " 原始数量: " . $listResult['original_count'] . "\n"; 359 echo " 有效数量: " . $listResult['valid_count'] . "\n"; 360 echo " 无效数量: " . $listResult['invalid_count'] . "\n"; 361 echo " 处理后的IP: " . implode(', ', $listResult['valid_ips']) . "\n"; 362 363 echo "\n"; 364 365 // 格式转换示例 366 echo "格式转换结果:\n"; 367 try { 368 $convertResult = $calculator->convertIP('192.168.1.1', 'binary'); 369 echo " 输入: " . $convertResult['input'] . "\n"; 370 echo " 目标格式: " . $convertResult['target_format'] . "\n"; 371 echo " 结果: " . $convertResult['result'] . "\n"; 372 echo " 二进制: " . $convertResult['binary'] . "\n"; 373 echo " 十六进制: " . $convertResult['hex'] . "\n"; 374 } catch (Exception $e) { 375 echo "格式转换错误: " . $e->getMessage() . "\n"; 376 } 377 378 echo "\n"; 379 380 // 子网信息示例 381 echo "子网信息:\n"; 382 try { 383 $subnetResult = $calculator->getSubnetInfo('192.168.1.0', 24); 384 echo " 网络地址: " . $subnetResult['network_address'] . "\n"; 385 echo " 广播地址: " . $subnetResult['broadcast_address'] . "\n"; 386 echo " 子网掩码: " . $subnetResult['netmask'] . "\n"; 387 echo " 总地址数: " . $subnetResult['num_addresses'] . "\n"; 388 echo " 可用主机数: " . $subnetResult['num_hosts'] . "\n"; 389 } catch (Exception $e) { 390 echo "子网信息错误: " . $e->getMessage() . "\n"; 391 } 392} 393 394// 如果直接运行此文件,则执行示例 395if (basename(__FILE__) == basename($_SERVER['SCRIPT_NAME'])) { 396 main(); 397} 398?>
-
ip_calculator (PY)
1#!/usr/bin/env python3 2# -*- coding: utf-8 -*- 3""" 4IP地址计算器 - Python版本 5支持IP地址运算、范围计算、排序和去重、格式转换等功能 6""" 7 8import re 9import ipaddress 10from typing import Dict, List, Tuple, Optional, Union 11 12 13class IPCalculator: 14 """IP地址计算器类""" 15 16 def __init__(self): 17 self.ip_regex = re.compile(r'^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$') 18 19 def validate_ip(self, ip: str) -> bool: 20 """ 21 验证IP地址格式 22 :param ip: IP地址字符串 23 :return: 是否有效 24 """ 25 if not self.ip_regex.match(ip): 26 return False 27 28 parts = [int(part) for part in ip.split('.')] 29 return all(0 <= part <= 255 for part in parts) 30 31 def ip_to_int(self, ip: str) -> int: 32 """ 33 IP地址转整数 34 :param ip: IP地址字符串 35 :return: 整数 36 """ 37 parts = [int(part) for part in ip.split('.')] 38 return (parts[0] << 24) + (parts[1] << 16) + (parts[2] << 8) + parts[3] 39 40 def int_to_ip(self, ip_int: int) -> str: 41 """ 42 整数转IP地址 43 :param ip_int: 整数 44 :return: IP地址字符串 45 """ 46 return '.'.join([ 47 str((ip_int >> 24) & 255), 48 str((ip_int >> 16) & 255), 49 str((ip_int >> 8) & 255), 50 str(ip_int & 255) 51 ]) 52 53 def calculate_ip(self, ip1: str, ip2: Union[str, int], operation: str) -> Dict: 54 """ 55 IP地址运算 56 :param ip1: 第一个IP地址 57 :param ip2: 第二个IP地址或数字 58 :param operation: 运算类型 (add, subtract, multiply, divide) 59 :return: 计算结果 60 """ 61 if not self.validate_ip(ip1): 62 raise ValueError('第一个IP地址格式无效') 63 64 ip1_int = self.ip_to_int(ip1) 65 ip2_int = None 66 67 if isinstance(ip2, str) and self.validate_ip(ip2): 68 ip2_int = self.ip_to_int(ip2) 69 elif isinstance(ip2, (int, str)) and str(ip2).isdigit(): 70 ip2_int = int(ip2) 71 else: 72 raise ValueError('第二个参数必须是有效的IP地址或数字') 73 74 if operation == 'add': 75 result = ip1_int + ip2_int 76 elif operation == 'subtract': 77 result = ip1_int - ip2_int 78 elif operation == 'multiply': 79 result = ip1_int * ip2_int 80 elif operation == 'divide': 81 result = ip1_int // ip2_int 82 else: 83 raise ValueError('不支持的运算类型') 84 85 if result < 0 or result > 4294967295: 86 raise ValueError('计算结果超出IP地址范围') 87 88 return { 89 'result': self.int_to_ip(result), 90 'result_int': result, 91 'ip1_int': ip1_int, 92 'ip2_int': ip2_int, 93 'operation': operation 94 } 95 96 def calculate_range(self, start_ip: str, end_ip: str) -> Dict: 97 """ 98 计算IP范围 99 :param start_ip: 起始IP 100 :param end_ip: 结束IP 101 :return: 范围信息 102 """ 103 if not self.validate_ip(start_ip) or not self.validate_ip(end_ip): 104 raise ValueError('IP地址格式无效') 105 106 start_int = self.ip_to_int(start_ip) 107 end_int = self.ip_to_int(end_ip) 108 109 if start_int > end_int: 110 raise ValueError('起始IP不能大于结束IP') 111 112 count = end_int - start_int + 1 113 network_ip = self.int_to_ip(start_int) 114 broadcast_ip = self.int_to_ip(end_int) 115 116 # 计算CIDR 117 cidr = 32 118 while 2 ** (32 - cidr) < count: 119 cidr -= 1 120 121 return { 122 'start_ip': start_ip, 123 'end_ip': end_ip, 124 'count': count, 125 'network_ip': network_ip, 126 'broadcast_ip': broadcast_ip, 127 'suggested_cidr': cidr, 128 'suggested_hosts': 2 ** (32 - cidr) 129 } 130 131 def process_ip_list(self, ip_list: List[str], options: Optional[Dict] = None) -> Dict: 132 """ 133 处理IP列表(排序和去重) 134 :param ip_list: IP地址列表 135 :param options: 选项 136 :return: 处理结果 137 """ 138 if options is None: 139 options = {} 140 141 remove_duplicates = options.get('remove_duplicates', True) 142 sort_ascending = options.get('sort_ascending', True) 143 validate_ips = options.get('validate_ips', True) 144 145 valid_ips = [] 146 invalid_ips = [] 147 148 # 验证IP 149 if validate_ips: 150 for ip in ip_list: 151 if self.validate_ip(ip): 152 valid_ips.append(ip) 153 else: 154 invalid_ips.append(ip) 155 else: 156 valid_ips = ip_list.copy() 157 158 # 去重 159 if remove_duplicates: 160 valid_ips = list(dict.fromkeys(valid_ips)) # 保持顺序的去重 161 162 # 排序 163 if sort_ascending: 164 valid_ips.sort(key=lambda x: self.ip_to_int(x)) 165 else: 166 valid_ips.sort(key=lambda x: self.ip_to_int(x), reverse=True) 167 168 return { 169 'original_count': len(ip_list), 170 'valid_count': len(valid_ips), 171 'invalid_count': len(invalid_ips), 172 'valid_ips': valid_ips, 173 'invalid_ips': invalid_ips 174 } 175 176 def convert_ip(self, input_value: Union[str, int], target_format: str) -> Dict: 177 """ 178 IP地址格式转换 179 :param input_value: 输入IP地址或整数 180 :param target_format: 目标格式 181 :return: 转换结果 182 """ 183 input_int = None 184 input_ip = None 185 186 if isinstance(input_value, str) and self.validate_ip(input_value): 187 input_ip = input_value 188 input_int = self.ip_to_int(input_ip) 189 elif isinstance(input_value, (int, str)) and str(input_value).isdigit(): 190 input_int = int(input_value) 191 input_ip = self.int_to_ip(input_int) 192 else: 193 raise ValueError('输入必须是有效的IP地址或数字') 194 195 if target_format == 'decimal': 196 result = input_ip 197 elif target_format == 'binary': 198 binary = format(input_int, '032b') 199 result = '.'.join([binary[i:i+8] for i in range(0, 32, 8)]) 200 elif target_format == 'hex': 201 result = f'0x{input_int:08X}' 202 elif target_format == 'integer': 203 result = str(input_int) 204 elif target_format == 'reverse': 205 result = '.'.join(input_ip.split('.')[::-1]) 206 else: 207 raise ValueError('不支持的转换格式') 208 209 return { 210 'input': str(input_value), 211 'target_format': target_format, 212 'result': result, 213 'decimal': input_ip, 214 'integer': input_int, 215 'binary': '.'.join([format(input_int, '032b')[i:i+8] for i in range(0, 32, 8)]), 216 'hex': f'0x{input_int:08X}' 217 } 218 219 def get_subnet_info(self, ip: str, cidr: int) -> Dict: 220 """ 221 获取子网信息(使用ipaddress模块) 222 :param ip: IP地址 223 :param cidr: CIDR前缀长度 224 :return: 子网信息 225 """ 226 try: 227 network = ipaddress.IPv4Network(f'{ip}/{cidr}', strict=False) 228 return { 229 'network_address': str(network.network_address), 230 'broadcast_address': str(network.broadcast_address), 231 'netmask': str(network.netmask), 232 'num_addresses': network.num_addresses, 233 'num_hosts': network.num_addresses - 2, 234 'hosts': [str(host) for host in network.hosts()] 235 } 236 except Exception as e: 237 raise ValueError(f'子网计算错误: {e}') 238 239 240def main(): 241 """主函数 - 使用示例""" 242 calculator = IPCalculator() 243 244 print("=== IP地址计算器示例 ===\n") 245 246 # IP地址运算示例 247 try: 248 math_result = calculator.calculate_ip('192.168.1.1', '1', 'add') 249 print("IP运算结果:") 250 print(f" 192.168.1.1 + 1 = {math_result['result']}") 251 print(f" 整数表示: {math_result['result_int']}") 252 except Exception as e: 253 print(f"IP运算错误: {e}") 254 255 print() 256 257 # 范围计算示例 258 try: 259 range_result = calculator.calculate_range('192.168.1.1', '192.168.1.254') 260 print("范围计算结果:") 261 print(f" 起始IP: {range_result['start_ip']}") 262 print(f" 结束IP: {range_result['end_ip']}") 263 print(f" IP数量: {range_result['count']}") 264 print(f" 建议CIDR: /{range_result['suggested_cidr']}") 265 except Exception as e: 266 print(f"范围计算错误: {e}") 267 268 print() 269 270 # IP列表处理示例 271 try: 272 ip_list = ['192.168.1.1', '10.0.0.1', '172.16.0.1', '192.168.1.1', '192.168.1.100'] 273 process_result = calculator.process_ip_list(ip_list, { 274 'remove_duplicates': True, 275 'sort_ascending': True, 276 'validate_ips': True 277 }) 278 print("IP列表处理结果:") 279 print(f" 原始数量: {process_result['original_count']}") 280 print(f" 有效数量: {process_result['valid_count']}") 281 print(f" 无效数量: {process_result['invalid_count']}") 282 print(f" 处理后的IP: {process_result['valid_ips']}") 283 except Exception as e: 284 print(f"IP列表处理错误: {e}") 285 286 print() 287 288 # 格式转换示例 289 try: 290 convert_result = calculator.convert_ip('192.168.1.1', 'binary') 291 print("格式转换结果:") 292 print(f" 输入: {convert_result['input']}") 293 print(f" 目标格式: {convert_result['target_format']}") 294 print(f" 结果: {convert_result['result']}") 295 print(f" 二进制: {convert_result['binary']}") 296 print(f" 十六进制: {convert_result['hex']}") 297 except Exception as e: 298 print(f"格式转换错误: {e}") 299 300 print() 301 302 # 子网信息示例 303 try: 304 subnet_result = calculator.get_subnet_info('192.168.1.0', 24) 305 print("子网信息:") 306 print(f" 网络地址: {subnet_result['network_address']}") 307 print(f" 广播地址: {subnet_result['broadcast_address']}") 308 print(f" 子网掩码: {subnet_result['netmask']}") 309 print(f" 总地址数: {subnet_result['num_addresses']}") 310 print(f" 可用主机数: {subnet_result['num_hosts']}") 311 except Exception as e: 312 print(f"子网信息错误: {e}") 313 314 315if __name__ == "__main__": 316 main()
使用说明
IP地址运算:
- 支持IP地址与数值的加减乘除运算
- 支持两个IP地址之间的运算
- 自动处理进位和借位
范围计算:
- 计算两个IP地址之间的IP数量
- 显示网络地址和广播地址
- 提供CIDR表示法
排序去重:
- 支持批量IP地址处理
- 自动去除重复IP地址
- 支持升序和降序排列
格式转换:
- 点分十进制 ↔ 二进制
- 点分十进制 ↔ 十六进制
- 点分十进制 ↔ 整数
- IP地址反向转换