I had written a small client-server code where in I was sending integers and characters from my client to server. So I know the basics of socket programming in C like the steps to follow and all. Now I want to create a packet and send it to my server. I thought that I will create a structure
struct packet
{
int srcID;
long int data;
.....
.....
.....
};
struct packet * pkt;
Before doing send(), I thought that I will write values inside the packet using
pkt-> srcID = 01
pkt-> data = 1 2 3 4
I need to know whether I am on the right path, and if yes then can I send using
send(sockfd, &packet, sizeof(packet), 0)
for receiving
recv(newsockfd, &PACKET, sizeof(PACKET), 0)
I have just started with network programming, so I am not sure whether i am on the right path or not. It would be of great help if anyone can guide me with my question in any form (theoretical,examples etc). Thanks in advance.
The pointer
pktis NOT defined in your application. You have two options:1) Declare
pktas a normal variable2) The second approach is useful when your packet contains a header followed by a payload:
UPDATED (to answer your comment):
First, you should know that receiving from a TCP socket MAY NOT provide the whole packet. You need to implement loop (as suggested by Nemo) to read the whole packet. Since you prefer the second option, then you need two loops. The first loop is to read the packet header to extract the payload size and the second loop to read the data. In case of UDP, you don’t need to worry about partial receiving. Here is a sample code (without looping) where sockfd is a UDP socket:
Remember:
* you need to implement serialization as mentioned by other users
* UDP is unreliable transport protocol while TCP is a reliable transport protocol.