一种IP的表示方式为192.168.1.1/24,其数字24的含义为24位掩码,即掩码为255.255.255.0,程序中读入的类似192.168.1.1/24的字符串可能需要转换为IP地址和掩码两个字符串保存或处理,即将192.168.1.1/24转换为192.168.1.1和255.255.255.0,一种程序的实现方法如下
<pre lang="C">
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
int main()
{
char ip[] = "192.168.1.1/24";
uint8_t *ipPrint = NULL;
uint32_t ipAddr;
uint32_t *ipPtr = &ipAddr;
uint32_t mask = 0;
uint32_t value = 0;
uint32_t i = 0, j = 0;
uint8_t *ptr = NULL;
struct in_addr in;
ptr = strtok(ip, "/");
inet_aton(ptr, (struct in_addr *)ipPtr);
ptr = strtok(NULL, "/");
value = atoi(ptr);
for(i = 0; i<value; i++)
{
j = value-i-1;
mask |= 1<<j;
}
printf("%.8x\n%.8x\n",ipAddr,mask);
in.s_addr = ipAddr;
ipPrint = inet_ntoa(in);
printf("%s\n",ipPrint);
in.s_addr = mask;
ipPrint = inet_ntoa(in);
printf("%s\n",ipPrint);
return 0;
}
</pre>