Linux网络编程----IP转换函数--inet_addr和inet_ntoa

Linux网络编程----IP转换函数--inet_addr和inet_ntoa

Linux下IP转换工具::

#Include <sys/types.h>

#include <sys/socket.h>

#include <arpa/inet.h>

 

strcut sockaddr_in   src;

 

src.sin_addr.s_addr   =  inet_addr("*.*.*.*");                 //构建网络地址。

 

printf("%s\n",inet_ntoa(src.sin_addr));             //将网络地址转换成字符串。

 

 

注意::

inet_ntoa存在的问题是inet_ntoa的返回值是一个static类型的char *指针,所以会出现问题::

 

char *a1,a2;

src.sin_addr.s_addr  =  inet_addr("192.168.1.123");

a1   =inet_ntoa(src.sin_addr);                  

src.sin_addr.s_addr = inet_addr("192.168.1.124");

a2 = inet_ntoa(src.sin_addr);

 

printf("a1:%s\n",a1);

显示为::         a1:192.168.1.124

printf("a2:%s\n",a2);

显示为:          a2:192.168.1.124

 

原因是静态的static   char *

 

man   inet_ntoa
The   inet_ntoa()   function   converts   the   Internet   host   address   in   given   in
              network     byte     order   to   a   string   in   standard   numbers-and-dots   notation.
              The   string   is   returned   in   a   statically   allocated   buffer,     which     subse-
              quent   calls   will   overwrite.
改调用已经清楚地说明,返回的字符串使用内部的静态变量,随后的调用将恢覆盖以前的内容。
所以,你如果需要多次结果,应该没调用一次,使用strcpy复制到你的缓冲区


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值