inet_ntoa的实现

从一段代码开始:

  1. int test_ntoa() 
  2.     struct sockaddr_in recv = {0}; 
  3.     struct sockaddr_in sa   = {0}; 
  4.     recv.sin_addr.s_addr = -217732928; //192.168.5.243   
  5.     sa.sin_addr.s_addr   = -939415360; //192.168.5.200 
  6.     printf("ip of recv:%s ip of sa:%s\n", inet_ntoa(recv.sin_addr), inet_ntoa(sa.sin_addr)); 
  7.     printf("ip of recv:%s\n", inet_ntoa(recv.sin_addr)); 
  8.     printf("ip of sa  :%s\n", inet_ntoa(sa.sin_addr));  
  9.     return 0;    

结果有点诧异:

  1. ip of recv:192.168.5.243 ip of sa:192.168.5.243 
  2. ip of recv:192.168.5.243 
  3. ip of sa   :192.168.1.200 

C函数出现这类问题,多半是由于其实现使用了静态内存所知.


google其源码:

  1. char
  2. inet_ntoa (struct in_addr in) 
  3.   __libc_once_define (static, once); 
  4.   char *buffer; 
  5.   unsigned char *bytes; 
  6.  
  7.   /* If we have not yet initialized the buffer do it now.  */ 
  8.   __libc_once (once, init); 
  9.  
  10.   if (static_buf != NULL) 
  11.     buffer = static_buf; 
  12.   else 
  13.     { 
  14.       /* We don't use the static buffer and so we have a key.  Use it
  15.      to get the thread-specific buffer.  */ 
  16.       buffer = __libc_getspecific (key); 
  17.       if (buffer == NULL) 
  18.     { 
  19.       /* No buffer allocated so far.  */ 
  20.       buffer = malloc (18); 
  21.       if (buffer == NULL) 
  22.         /* No more memory available.  We use the static buffer.  */ 
  23.         buffer = local_buf; 
  24.       else 
  25.         __libc_setspecific (key, buffer); 
  26.     } 
  27.     } 
  28.  
  29.   bytes = (unsigned char *) ∈ 
  30.   __snprintf (buffer, 18, "%d.%d.%d.%d"
  31.           bytes[0], bytes[1], bytes[2], bytes[3]); 
  32.  
  33.   return buffer; 

这里使用了静态的缓存buffer,函数把转换后的ip写入缓存buffer,然后返回buffer的首地址值.

看似无奈的选择.glibc里的某些底层函数都使用这类处理方式.

其实也可以选择外部传参的做法解决:

  1. <pre name="code"class="cpp">char
  2. inet_ntoa (struct in_addr in, char* buf, int buflen) 
  3.       ... ... 
 这样的处理方式,效率略低于第一种.或许这也是glibc选择第一种方式的原因.
                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值