Reputation: 1330
I'm concerned about endianness when it comes to this problem. Maybe I am overthinking what I have to worry about.
The input to my code is a packet that looks like:
I've received a network packet that contains some bytes. If I know the index in the byte array (and have valid data) of where the in_addr
is, is it safe to do something like:
uint8_t* addrPtr = packet[IP_IDX];
struct in_addr addr;
memcpy((void*) addr, addrPtr, sizeof(in_addr));
Is this safe regardless of Endianness?
What about for in6_addr which is actually 16 bytes?
Thanks.
Upvotes: 1
Views: 3894
Reputation: 3006
if you do this:
uint8_t* addrPtr = packet + IP_IDX; // or &packet[IP_IDX]; whichever makes you happy
struct in_addr addr;
memcpy((void*) &addr, addrPtr, sizeof(in_addr));
you should be good, memcpy doesn't do anything with endianess, it just copies bytes, so as long as you aren't pulling offsets out of the packet you don't need to worry about memcpy... unless I don't understand what your question is.
If you want to handle IPv6 you'll probably need seperate code for it since the offsets and address sizes are different.
Basically aside from forgeting the 'address of' operator in two places your code looks fine.
Upvotes: 1
Reputation: 225042
struct in_addr
is supposed to be in network byte order, IIRC. Assuming your packet is also delivered in network byte order, you're good to go.
Upvotes: 5