Q:

Networking message formatting a lot of char, int, converting in C\C++

I am doing networking programming in C\C++ and the assignment asks me to send a formatted message.
The format is below:
bits:    0.....15 16....31  
          update#  port#           
             Sever-IP

As you seen first line ask me to:

Convert int into 16 bits so 2 ints make up 32 bits.
Convert xxx.xxx.xxx.xxx into 32 bits. 

I am using UDP, so I need get these info into a char[], and that is the hard part. In my program, I have the update# and port # as int, and server IP address as a string. How could I convert them into these bits?
Here is what I have tried:

Casting them into char. But, I need get one int into two char.
Convert them into a string, and then string.c_str(), but it gives me a 4 bytes pointer.

A:

The easiest way to do this is to create a struct for your header like this:
#pragma pack(push,1)

struct header
{
    unsigned short updateNumber;
    unsigned short port;
    unsigned long ip;
};
#pragma pack(pop)

And use it like this:
char *buffer = new char[sizeof(header)+sizeOfRemainingMessage];
header *head = (header*)buffer;
head->update = 1;
head->port = 80;
head->ip = // convert ip string to unsigned long*
send(buffer); 

*To convert the ip string to the unsigned long refer to inet_addr().

