C实现判断两个IP是否在同一个子网
在进行网络程序的时候避免不了对给定IP是否跨子网段进行判断。相关原理倒是简单, 贴出相关代码:
1 #include <stdio.h> 2 #include <math.h> 3 #include <string.h> 4 #include <stdlib.h> 5 #include <unistd.h> 6 7 #define ALL_BIT 32 /* ip address have 32 bits */ 8 9 /* 10 ** description: juge the ip_a and ip_b is in the same subnet or not 11 ** this functio is used IPv4 only, and did not check the input parameter's 12 ** correctness, so make sure the value of parameter before call it 13 ** para: sub_mask is a decimal subnet mask , not dotted decimal 14 ** ip_a/ip_b: the ip address string, in dotted decimal 15 ** return: 0 for the same, -1 for the not 16 */ 17 int same_subnet (int sub_mask, char *ip_a, char *ip_b) 18 { 19 int mask = 0xFFFFFFFF; 20 mask = mask << (ALL_BIT - sub_mask); 21 22 double cnt_a = 0.0; 23 double cnt_b = 0.0; 24 double tmp = 0.0; 25 26 char *token = NULL; 27 28 int i = 3; 29 30 for (token = strtok (ip_a, "."); token != NULL; token = strtok (NULL, ".")) { 31 tmp = atoi (token); 32 tmp = tmp * pow (256, i--); /* what dose this mean? do you understand */ 33 cnt_a += tmp; 34 } 35 36 i = 3; /* reset i */ 37 for (token = strtok (ip_b, "."); token != NULL; token = strtok (NULL, ".")) { 38 tmp = atoi (token); 39 tmp = tmp * pow (256, i--); 40 cnt_b += tmp; 41 } 42 43 unsigned long mask_a = (unsigned long)cnt_a; 44 unsigned long mask_b = (unsigned long)cnt_b; 45 46 //printf ("mask_a %u\tmask_b %u\n", mask_a, mask_b); 47 48 mask_a &= mask; /* get the ip's netmask for compare */ 49 mask_b &= mask; 50 //printf ("mask_a %u\tmask_b %u\n", mask_a, mask_b); 51 52 if (mask_a == mask_b) 53 return 0; 54 else 55 return -1; 56 } 57 58 /* 59 ** test code 60 */ 61 int main (int argc, char **argv) 62 { 63 int i = same_subnet (atoi (argv[1]), argv[2], argv[3]); 64 printf ("%s subnet\n", i == 0? "same":"not same"); 65 return 0; 66 } 67 68 69 70 代码在gcc version 4.7.2 20121109 (Red Hat 4.7.2-8) (GCC)编译通过。