I am writing a sample chat-like function to learn how to use sockets in unix. I am using gcc.

To send between clients of a tcp connection I need to encapsulate a bunch of different data:

typedef struct
{

short type;
int messageID1;
int messageID2;
short messageID3;

int ipAddr;

short tcp_port;
short udp_port; 
int pid; 
int payloadLength;

char * stringSend;

} ping_packet;

After filling out this info, I am using memmove() to put all of the data into a char array and use send() to send the information. All of the sent data (except sendString) is converted to network byte ordering.

When a socket has new data, it is read using recv(). The returned char is casted to my "ping_packet" struct, and all of my information is maintained correctly with the exception of the actual message (stringSend). stringSend is a null-terminated string.

How exactly do I parse out the stringSend message data? The payloadLength, by definition is the length of the string sendString. I guess I'm not sure how to retrieve this information correctly, any help would be appreciated.

The stringSend member should not be part of the structure you send. It is just a 4 byte ptr that will be meaningless to the receiver.

Thus when you send it will be sizeof(struct) - sizeof(char *) bytes. Then you send the payloadLength bytes at stringSend;

When you receive do the same. Recv sizeof(struct)-sizeof(char *), allocate a payloadLength sized buffer then Recv payloadLength bytes.

It would be simpler to leave off the stringSend member and keep track another way. Perhaps define a base header and a derived type with the data ptr.

1. why do you do this "After filling out this info, I am using memmove() to put all of the data into a char array and use send() to send the information. All of the sent data (except sendString) is converted to network byte ordering." just cast the structure to char* and send the structure.

2. You can't/shouldn't send a char pointer across a network, its has no meaning in the new address space. Instead just send the message as a character array...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.