![](/img/trans.png)
[英]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.