【C语言实现】根据子网掩码来判断两个IP是否在一个子网

mac2024-07-21  61

编译:

gcc isSameSubnet.c -o isSameSubnet -g -Wall

自测:

./isSameSubnet 192.168.1.1 192.168.2.2 255.255.0.0 result = same  

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <netinet/in.h> //根据IP地址去本地查询对应的掩码 char* getMaskByIP(const char* szIPAddr) { static char szNetMask[20] = {}; char* szNetMaskDesc = "netmask"; FILE* netinfo = popen("/sbin/ifconfig", "r"); if(!netinfo){ puts("error while open pipe"); exit(1); } char strTmp[200]; char* strMaskBegin = 0; char* strMaskEnd = 0; while( fgets(strTmp, sizeof(strTmp) - 1, netinfo) != NULL ) { if(strstr(strTmp, szIPAddr)) { strMaskBegin = strstr(strTmp, szNetMaskDesc); if(!strMaskBegin) { goto end; } strMaskBegin += strlen(szNetMaskDesc); while(*strMaskBegin == ' ') { strMaskBegin++; } strMaskEnd = strstr(strMaskBegin, " "); if(!strMaskBegin) { goto end; } strncpy(szNetMask, strMaskBegin, strMaskEnd - strMaskBegin); //printf("NetMask=%s\n", szNetMask); break; } } end: pclose(netinfo); return szNetMask; } //根据szNetMask,判断szIP1、szIP2是否属于一个子网. //如果是则返回1,否则返回0 int isSameSubNet(const char* szIP1, const char* szIP2, const char* szNetMask) { struct in_addr ip1; struct in_addr ip2; struct in_addr netMask; if(0 == szIP1 || 0 == szIP2 || 0 == szNetMask) return 0; if(0 == inet_aton(szIP1, &ip1)) { printf("IP1 invalid.\n"); return 0; } if(0 == inet_aton(szIP2, &ip2)) { printf("IP2 invalid.\n"); return 0; } if(0 == inet_aton(szNetMask, &netMask)) { printf("Netmask invalid.\n"); return 0; } if ((ip1.s_addr & netMask.s_addr) == (ip2.s_addr & netMask.s_addr)) { return 1; } return 0; } int main(int argc, char *argv[]) { int ret = 0; if (argc != 3 && argc != 4) { fprintf(stderr, "Usage1: %s localIP DstIP\n", argv[0]); fprintf(stderr, "Usage2: %s IP1 IP2 NetMask\n", argv[0]); return -1; } if(3 == argc) { ret = isSameSubNet(argv[1], argv[2], getMaskByIP(argv[1])); } else if (4 == argc) { ret = isSameSubNet(argv[1], argv[2], argv[3]); } printf("result = %s\n", (ret == 1)?"same":"not same"); return 0; }

 

最新回复(0)