recvfrom()保存src_addr的字节顺序是什么?

3

size_t recvfrom(int sockfd, void *buf, size_t len, int flags, struct sockaddr *src_addr, socklen_t *addrlen)

src_addr参数采用哪种字节顺序进行编写?是网络字节顺序还是主机字节顺序?我无法在recvfrom手册页或通过Google和SO搜索找到相关信息。


1个回答

6
假设套接字是IPv4或IPv6套接字,则存储在src_addr中的主机和端口将以网络字节顺序呈现。
这在IPv4手册(man 7 ip中有记录:

Address format

An IP socket address is defined as a combination of an IP interface address and a 16-bit port number. The basic IP protocol does not supply port numbers, they are implemented by higher level protocols
like udp(7) and tcp(7). On raw sockets sin_port is set to the IP protocol.

   struct sockaddr_in {
       sa_family_t    sin_family; /* address family: AF_INET */
       in_port_t      sin_port;   /* port in network byte order */
       struct in_addr sin_addr;   /* internet address */
   };

   /* Internet address. */
   struct in_addr {
       uint32_t       s_addr;     /* address in network byte order */
   };

sin_family is always set to AF_INET. This is required; in Linux 2.2 most networking functions return EINVAL when this setting is missing. sin_port contains the port in network byte order. The port numbers below 1024 are called privileged ports (or sometimes: reserved ports). Only a privileged process (on Linux: a process that has the CAP_NET_BIND_SERVICE capability in the user namespace governing its network namespace) may bind(2) to these sockets. Note that the raw IPv4 protocol as such has no concept of a port, they are implemented only by higher protocols like tcp(7) and udp(7).

sin_addr is the IP host address. The s_addr member of struct in_addr contains the host interface address in network byte order. in_addr should be assigned one of the INADDR_* values (e.g., INADDR_LOOPBACK) using htonl(3) or set using the inet_aton(3), inet_addr(3), inet_makeaddr(3) library functions or directly with the name resolver (see gethostbyname(3)).

IPv6手册的措辞类似。

因此,在读取端口号时,使用ntohs来提取它。在读取地址时,使用inet_ntop将其转换为文本形式。


谢谢 - 你知道我可以在哪里查找吗?我有点惊讶手册中没有这个内容。或者这是网络编程的“领域知识”? - StoneThrow
1
@StoneThrow man 7 ipman 7 ipv6 分别包含有关使用IPv4和IPv6套接字的一般信息。 - dbush
1
@bishop:您正在使用过时的版本6。当前版本7在此处可用:http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/netinet_in.h.html。 - alk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接