如何将sockaddr_in结构体的in_addr赋值给uint8_t数组?
addr[0] = help->sin_addr fill the entire addr array? Short answer: No, this won't work—here's why, and what to do instead.
Why the original line fails
First, there's a fundamental type mismatch:
addr[0]is a singleuint8_t(1 byte)help->sin_addris astruct in_addr, which on most systems contains auint32_tfield (s_addr) holding the 4-byte network-order IP address.
Assigning a struct to a single byte will either:
- Throw a compiler error (since you can't implicitly convert a struct to a uint8_t), or
- If your compiler allows it (via non-standard extensions), only copy the first byte of the struct into
addr[0], leaving the other 3 elements ofaddruninitialized. Either way, you won't get the full IP address into the array.
Correct ways to fill addr from sin_addr
Since sin_addr.s_addr is already in network byte order (same format as what inet_pton outputs), you have a few safe options:
Use
memcpy(most portable)
This copies the 4 bytes directly from thes_addrfield into theaddrarray, regardless of system endianness:#include <string.h> // For memcpy memcpy(addr, &help->sin_addr.s_addr, sizeof(addr));Manually extract each byte (explicit and endian-safe)
If you want to avoidmemcpy, you can shift the 32-bit network-order value to get each octet:addr[0] = (help->sin_addr.s_addr >> 24) & 0xFF; addr[1] = (help->sin_addr.s_addr >> 16) & 0xFF; addr[2] = (help->sin_addr.s_addr >> 8) & 0xFF; addr[3] = help->sin_addr.s_addr & 0xFF;This works because
s_addris stored in big-endian (network order), so shifting right by 24 gives the first octet, and so on.Cast the array to a
uint32_t*(use with caution)
You can assign thes_addrvalue directly to the array treated as a 32-bit integer, but this depends on your system's endianness matching network order (big-endian) to get the bytes in the correct order. This is less portable, but works if you're targeting systems where this is consistent:*(uint32_t*)addr = help->sin_addr.s_addr;Note: This may trigger strict aliasing warnings in some compilers—
memcpyis safer for cross-platform code.
内容的提问来源于stack exchange,提问作者Luk

