找到一个线程安全的函数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函数,避免一些不必要的问题。
阅读(6187) | 评论(2) | 转发(0) |