Need help with loading and extracting bytes from a packet -network byte order trouble
Hi guys, I'm relatively new to C programming, and am having a hard time with the network byte order stuff. It seems like it should be simple, htons/htonl before writing, and ntohs/ntohl when reading. And yet I run into problems. I think it's the way I am handling my bytes. Can you guys look at my approach and see if there's something that raises any flags with you?
Packing bytes for SENDING
I'm implementing a protocol over TCP. And I want to send a packet that is 6 bytes.
format: [4 bytes for IP address] [2 bytes for TCP PORT]
Code:
// variables I want to load into packet
//addr is a struct sockaddr_in, filled in via getsockname(), getaddrinfo(), etc
uint32_t state_to_load = htonl(addr.sin_addr.s_addr);
uint16_t length_to_load = htons(addr.sin_port)
char packet[6];
uint16_t *state = (uint32_t *)(pack);
uint16_t *len = (uint16_t *)(pack + 4);
*state = state_to_load;
*len = length_to_load;
write(fd, packet, 6);
Extracting Bytes after READING
format: [4 bytes for IP address] [2 bytes for TCP PORT]
Code:
char packet[6];
read(fd, packet, 6);
int extracted_state = (packet[0] << 24) | (packet[1] << 16) | (packet[2] << 8) | packet[3];
int extracted_length = (packet[4] << 8) | packet[5];
I extract data from packets different from how I pack them in, because I can't think of a good way to pack them. I heard that extracting bytes this way avoids network byte order.
From your expert opinions, is this a good way to pack and extract bytes for sending/receiving?