I am new to C and I am trying to build a UDP datagram and then send it from a client program to a server program on an different machine.
I have run into some problem when trying to build the datagram, specifically the fixed size (IPv4) header: The format of the header is (client IP (32 bit) | client port (16 bit) | packet length (32 bit) | ... etc.)
The approach I choose to go with was to gather the necessary header and body information and then cast them into char*
and then concatenate them together to generate the datagram. However, when I cast int
and long
to char*
(port number and packet length) it does not guarantee a fixed size char*
(for example, if the packet length (datatype long) is calculated to be 440 and I convert it to char*
, then strlen will show the length of the char*
to be 2 instead of 4 since the number is not big enough to take all 4 bytes, I would assume...)
I tried a different way of converting long into fixed size char* by bit-wise operation:
//assume the datagram size was calculated to be 440 bits
unsigned long len = 440;
unsigned char dg_len [4];
dg_len[0] = (len >> 24) & 0xFF;
dg_len[1] = (len >> 16) & 0xFF;
dg_len[2] = (len >> 8) & 0xFF;
dg_len[3] = len & 0xFF;
printf("%d" ,strlen(dg_lenPtr)); //this would display 0
printf("%d" ,(unsigned long)dg_lenPtr); //this display some random number
The only explanation I thought of for this is that the unused 2 higher bytes of dg_lenPtr are being read as null character since strlen shows the length to be 0.
I am starting to think that char*
is not the data structure I need to use to build the datagram. Can someone point me to the right direction on what I need to do to build the fix sized header for the datagram?
You are not responsible for generating the IPv4 header. The
send()
andsendto()
functions handle that for you. All you have to focus on is sending your desired datagram payload to the desired destination IP:Port (by specifying it directly tosendto()
, or toconnect()
in the case ofsend()
).