线程安全的inet_ntop

找到一个线程安全的函数inet_ntop
NAME
       inet_ntop - Parse network address structures

SYNOPSIS
       #include 
       #include 
       #include 

       const char *inet_ntop(int af, const void *src,
                             char *dst, socklen_t cnt);

DESCRIPTION
       This  function  converts the network address structure src in the af address family into a character string, which
       is copied to a character buffer dst, which is cnt bytes long.

       inet_ntop(3) extends the inet_ntoa(3) function to support multiple address families, inet_ntoa(3) is  now  consid‐
       ered to be deprecated in favor of inet_ntop(3).  The following address families are currently supported:

       AF_INET
              src points to a struct in_addr (network byte order format) which is converted to an IPv4 network address in
              the dotted-quad format, "ddd.ddd.ddd.ddd".  The buffer dst must be at least INET_ADDRSTRLEN bytes long.

       AF_INET6
              src points to a struct in6_addr (network byte order format) which is converted to a representation of  this
              address  in  the  most appropriate IPv6 network address format for this address.  The buffer dst must be at
              least INET6_ADDRSTRLEN bytes long.

RETURN VALUE
       inet_ntop() returns a non-null pointer to dst.  NULL is returned if there was an error, with errno set  to  EAFNO‐
       SUPPORT if af was not set to a valid address family, or to ENOSPC if the converted address string would exceed the
       size of dst given by the cnt argument.

u_char ip_src_address[16],ip_dst_address[16]; inet_ntop(AF_INET,&ip_protocol->ip_src_address,ip_src_address,16);
    inet_ntop(AF_INET,&ip_protocol->ip_dst_address,ip_dst_address,16);
    printf("%s--->%s\n",ip_src_address,ip_dst_address);
但是这样的话,就会用到两个额外的数组。总要有些牺牲的。

使用inet_ntoa的话,就不能够在同一个函数的几个参数里面出席那两次inet_ntoa,或者是第一个inet_ntoa未使用结束之前,不要使用第二个。

 printf("%s:%d--->",inet_ntoa(ip_protocol->ip_src_address),ntohs(tcp_protocol->tcp_src_port) );
   printf("%s:%d\n",inet_ntoa(ip_protocol->ip_dst_address),ntohs(tcp_protocol->tcp_dst_port));

但是,以后还是尽量的使用线程安全的inet_ntop函数,避免一些不必要的问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值