<2011年8月>
31123456
78910111213
14151617181920
21222324252627
28293031123
45678910

统计

  • 随笔 - 21
  • 文章 - 0
  • 评论 - 2
  • 引用 - 0

常用链接

留言簿

随笔档案

搜索

  •  

最新评论

阅读排行榜

评论排行榜

[导入]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复制到你的缓冲区


文章来源:http://fengqing888.blog.163.com/blog/static/33011416201171344022967

posted on 2011-08-13 16:40 FengRalf 阅读(10401) 评论(1)  编辑 收藏 引用

评论

# re: [导入]Linux网络编程----IP转换函数--inet_addr和inet_ntoa 2016-01-16 18:59 losemyheaven

char *a1,a2
应该改为 char *a1,*a2
  回复  更多评论    

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理