简体   繁体   中英

How do I assign an u_int32_t IPv4 address to the address parameter of sockaddr_in in C? (Socket Programming in C)

I've managed to get the broadcast address as a u_int32_t, and my goal is to assign the broadcast address to the saddr.sin_addr.s_addr parameter so I can turn it into a string with 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);

According to the arpa/inet.h documentation, htonl() takes an u_int32_t as a parameter, so that part should work. 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. What am I missing here? Apologies if this is an obvious fix, but I've been stuck on this for awhile. Thanks in advance:)

edit

Also, according to Beej's Guide to Network Programming the sin_addr struct should be:

struct in_addr {
uint32_t s_addr; // that's a 32-bit int (4 bytes)
};

So why wouldn't assigning a 32-bit int to s_addr work?

do consider @David C. Rankin comment for a good guide on Network programming, thought your issue has nothing to do with networking.

I went and removed a few lines of your code to make it more obvious:

struct sockaddr_in *broadcastInfo;
broadcastInfo->sin_addr.s_addr = htonl(broadcast);

So, what's happening is that you are using broadcastInfo, which is a pointer, without ever giving it an actual value, so the pointer has high chances of pointing to an invalid address, thus the SEGFAULT.

Considering your use case, you probably simply want to have a struct by value rather than by pointer:

struct sockaddr_in broadcasrInfo = {};
/* The rest of your code here. */
broadcastInfo.sin_addr.s_addr - htonl(broadcast);

And there, of course, change the places where you were using broadcastInfo for &broadcastInfo.

Have a great day,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM