首页 > 代码库 > 判断IP地址与掩码是否合法程序
判断IP地址与掩码是否合法程序
#include <stdio.h>
#include <arpa/inet.h>
#include <errno.h>
#include <string.h>
int if_a_string_is_a_valid_ipv4_address(const char *str)
{
struct in_addr addr;
int ret;
volatile int local_errno;
errno = 0;
ret = inet_pton(AF_INET, str, &addr);
local_errno = errno;
if (ret > 0);
else if (ret < 0)
printf("EAFNOSUPPORT: %s\n", strerror(local_errno));
else
printf("\"%s\" is not a valid IPv4 address\n", str);
return ret;
}
bool IsSubnetMask_and_Is_ipv4_address(const char *ip_address, char *subnet)
{
if ( if_a_string_is_a_valid_ipv4_address(ip_address) )
{
unsigned int b = 0, i, n[4];
sscanf(subnet, "%u.%u.%u.%u", &n[3], &n[2], &n[1], &n[0]); //subnet 为子网掩码
for(i = 0; i < 4; ++i) //将子网掩码存入32位无符号整型
b += n[i] << (i * 8);
b = ~b + 1;
if((b & (b - 1)) == 0) //判断是否为2^n
return true;
}
return false;
}
int main(int argc, char *argv[])
{
if ( argc == 3 )
{
if ( IsSubnetMask_and_Is_ipv4_address(argv[1], argv[2]) )
{
printf("ip yanma address is success.\n");
}
else
{
printf("no\n");
}
}
else
{
printf("INVALIUD ARGS.\n");
}
return 0;
}
判断IP地址与掩码是否合法程序