IP地址转换函数--inet_addr和inet_ntoa使用笔记

【inet_addr.c测试代码】

#include 
#include 
#include 
#include 
#include 
int main(int aargc, char* argv[])
{
         struct in_addr addr1,addr2;
         ulong   l1,l2;
         l1= inet_addr("192.168.0.74");
         l2 = inet_addr("211.100.21.179");
         memcpy(&addr1, &l1, 4);
         memcpy(&addr2, &l2, 4);


         printf("%s : %s\n", inet_ntoa(addr1), inet_ntoa(addr2)); //注意这一句的运行结果


         printf("\"%s\" = inet_ntoa(0x%08x);\n", inet_ntoa(addr1),addr1);
         printf("\"%s\" = inet_ntoa(0x%08x);\n", inet_ntoa(addr2),addr2);
         
         printf("0x%08x == ntohl(0x%08x)\n",ntohl(l1),l1); 
         printf("0x%08x == ntohl(0x%08x)\n",ntohl(addr1.s_addr),l1); 
         printf("0x%08x == htonl(0x%08x)\n\n",htonl(addr2.s_addr),addr2.s_addr); 
         
         sockaddr_in socketaddr;
         memset(&socketaddr, 0, sizeof(sockaddr_in));
         socketaddr.sin_addr.s_addr = addr2.s_addr;
         socketaddr.sin_port = htons(12233);//端口
         printf("addr2 [ip: port] == [%s:%d]\n", inet_ntoa(socketaddr.sin_addr),ntohs(socketaddr.sin_port));
         return 0;
}

【Linux系统,CenOS6.4上,make编译,GCC4.8.2 运行结果】

[root@localhost ~]# cp inet_addr.c test.c -a
cp: overwrite `test.c'? y
[root@localhost ~]# make
g++ -c test.c
g++ -o test test.o
[root@localhost ~]# ./test 

192.168.0.74 : 192.168.0.74
"192.168.0.74" = inet_ntoa(0x4a00a8c0);
"211.100.21.179" = inet_ntoa(0xb31564d3);
0xc0a8004a == ntohl(0x4a00a8c0)
0xc0a8004a == ntohl(0x4a00a8c0)
0xd36415b3 == htonl(0xb31564d3)


addr2 [ip: port] == [211.100.21.179:51503]
[root@localhost ~]# 


[root@localhost ~]# 

【makefile 文件】

test:test.o
	g++ -o test test.o

test.o:test.c
	g++ -c test.c
          
clean:
	rm -f *.o test




你可能感兴趣的:(socket)