inet_ntoa的实现

从一段代码开始:

int test_ntoa()
{
	struct sockaddr_in recv = {0};
	struct sockaddr_in sa   = {0};
	recv.sin_addr.s_addr = -217732928; //192.168.5.243	
	sa.sin_addr.s_addr   = -939415360; //192.168.5.200
	printf("ip of recv:%s ip of sa:%s\n", inet_ntoa(recv.sin_addr), inet_ntoa(sa.sin_addr));
	printf("ip of recv:%s\n", inet_ntoa(recv.sin_addr));
	printf("ip of sa  :%s\n", inet_ntoa(sa.sin_addr)); 
	return 0;	
}

结果有点诧异:

ip of recv:192.168.5.243 ip of sa:192.168.5.243
ip of recv:192.168.5.243
ip of sa   :192.168.1.200

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


google其源码:

char *
inet_ntoa (struct in_addr in)
{
  __libc_once_define (static, once);
  char *buffer;
  unsigned char *bytes;

  /* If we have not yet initialized the buffer do it now.  */
  __libc_once (once, init);

  if (static_buf != NULL)
    buffer = static_buf;
  else
    {
      /* We don't use the static buffer and so we have a key.  Use it
	 to get the thread-specific buffer.  */
      buffer = __libc_getspecific (key);
      if (buffer == NULL)
	{
	  /* No buffer allocated so far.  */
	  buffer = malloc (18);
	  if (buffer == NULL)
	    /* No more memory available.  We use the static buffer.  */
	    buffer = local_buf;
	  else
	    __libc_setspecific (key, buffer);
	}
    }

  bytes = (unsigned char *) ∈
  __snprintf (buffer, 18, "%d.%d.%d.%d",
	      bytes[0], bytes[1], bytes[2], bytes[3]);

  return buffer;
}

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

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

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

char *
inet_ntoa (struct in_addr in, char* buf, int buflen)
{
      ... ...
}

这样的处理方式,效率略低于第一种.或许这也是glibc选择第一种方式的原因.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值