inet_addr,inet_pton,inet_aton 效果相同,点分十进制 转成 二进制。
函数原型略过
windows下:
#include <winsock2.h>
#pragma comment (lib, "ws2_32")
优先使用 inet_pton,inet_aton
Linux下:
#include <netinet./in.h>
#include <arpa/inet.h>
下面测试环境Ubuntu16.04
#include <cstdio>
#include <string>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc,char** argv){
char str[] = "127.0.0.1";
long r1,r2,r3;
r1=r2=r3=0;
struct in_addr addr;
r1 = inet_addr(str);
if(r1 == -1)
printf("inet_addr change fail\n");
else
printf("inet_addr change %lu\n",r1);
r2 = inet_pton(AF_INET,str,&addr);
if(r1 == -1)
printf("inet_pton change fail\n");
else
printf("inet_pton change %lu\n",(unsigned long)addr.s_addr);
r3 = inet_aton(str,&addr);
if(r1 == -1)
printf("inet_aton change fail\n");
else
printf("inet_aton change %lu\n",(unsigned long)addr.s_addr);
}
运行结果
inet_addr change 16777343
inet_pton change 16777343
inet_aton change 16777343