[英]C socket programming: get IP address (IPv6 or IPv4) server bounds to, and client connected to?
[英]How do I assign an u_int32_t IPv4 address to the address parameter of sockaddr_in in C? (Socket Programming in C)
我设法将广播地址作为 u_int32_t 获取,我的目标是将广播地址分配给 saddr.sin_addr.s_addr 参数,这样我就可以使用 inet_ntoa() 将其转换为字符串:
struct sockaddr_in *broadcastInfo;
char *broadcastAddress;
// the ip and mask are both initialized as u_int32_t earlier in the code
u_int32_t broadcast = (ip | (~mask)); // broadcast address = ip OR `netmask
// the broadcast address now equals c0a807ff or 192.168.7.255
broadcastInfo->sin_addr.s_addr = htonl(broadcast);
broadcastAddress = inet_ntoa(broadcastInfo->sin_addr);
printf("Broadcast Address: %s\n", broadcastAddress);
根据 arpa/inet.h 文档, htonl() 将 u_int32_t 作为参数,因此该部分应该可以工作。 Some unofficial documentation I looked at for socket programming in C implied that I could then assign the output of htonl() to broadcastInfo->sin_addr.s_addr, but I get Segmentation fault: 11 as an output when I try to. 我在这里想念什么? 抱歉,如果这是一个明显的解决方法,但我已经坚持了一段时间。 提前致谢:)
编辑
此外,根据 Beej 的网络编程指南, sin_addr 结构应该是:
struct in_addr {
uint32_t s_addr; // that's a 32-bit int (4 bytes)
};
那么为什么不将 32 位 int 分配给 s_addr 工作呢?
请考虑@David C。 Rankin 评论网络编程的良好指南,认为您的问题与网络无关。
我去删除了您的几行代码以使其更加明显:
struct sockaddr_in *broadcastInfo;
broadcastInfo->sin_addr.s_addr = htonl(broadcast);
所以,发生的事情是您正在使用广播信息,它是一个指针,没有给它一个实际值,所以指针很有可能指向一个无效的地址,因此就是 SEGFAULT。
考虑到您的用例,您可能只想按值而不是按指针获得结构:
struct sockaddr_in broadcasrInfo = {};
/* The rest of your code here. */
broadcastInfo.sin_addr.s_addr - htonl(broadcast);
当然,在那里,将您使用广播信息的地方更改为 &broadcastInfo。
祝你有美好的一天,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.