I have a program that transfer data over Internet sockets (UDP). so there are defined char arrays as data packets. E.g. char packet1[] = 11 (header[2 digit]) + 192.168.100.158 (sender_IP[15 digit]) + 006 (TTL [3 digit])+… (11192.168.100.158006...). The receiver extracts the data according to the index of the array (e.g. 0-1 is header, 2-16 is sender_IP).
My problem is that when I define the sender_IP as [2-16] and if the IP address is shorter than 15 digit (e.g. 192.168.100.5) then the receiver extracts the data wrong. My question is that how can I make sure that sender_IP would be extracted correctly even if the IP address is 15 digit or 14 digit (without adding extra character to define the string length of sender_IP)?
I was thinking to create a struct type and define something like `
struct packet {
char header[1];
char senderIP[15]
, TTL[2];
};
. but I could not figure out what to write instead of buf on this line sendto(s, buf, BUFSIZE, 0,(struct sockaddr *) &si_other, slen), since buf needs to be char as I know. I need the IP address in ASCII representation as send some data to sender_IP address (inet_aton(sender_IP, &si_other.sin_addr).
Send the IP’s as a 32-bit int, or pack the string with zeros so it is the proper length, e.g. 192.168.100.005.