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

【inet_addr.c测试代码】

#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
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




  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值