今天写了一段socket代码,大致是这样的:
struct sockaddr_in cliaddr;
inet_aton("192.168.2.12", &addr);
cliaddr.sin_family = AF_INET;
cliaddr.sin_addr.s_addr = htonl(addr.s_addr);
cliaddr.sin_port = htons(5000);
if(bind(sockfd, (const struct sockaddr *)&cliaddr, sizeof(cliaddr)) == -1)
{
perror("bind failed\n");
}
执行时,总报错:
Cannot assign requested address
花了比较多的时间,也没找出原因。
后来在网上搜了下,才知道,原来 函数 inet_aton已经把IP地址保存为network order了,所以不需要再用htonl()转了。
其实inet_aton()的man里面说的很清楚的。
inet_aton() converts the Internet host address cp from the IPv4 num‐
bers-and-dots notation into binary form (in network byte order) and
stores it in the structure that inp points to.
以后还是要仔细了解每个函数的具体作用啊。
本文记录了一次socket编程中bind函数出现“Cannot assign requested address”错误的排查过程。作者通过研究发现,问题在于使用了不必要的 htonl 函数转换 IP 地址。
8531

被折叠的 条评论
为什么被折叠?



