Proper way to create packets along with sending and receiving them in socket programming using C -
i had written small client-server code in sending integers , characters client server. know basics of socket programming in c steps follow , all. want create packet , send server. thought create structure
struct packet { int srcid; long int data; ..... ..... ..... }; struct packet * pkt;
before doing send(), thought write values inside packet using
pkt-> srcid = 01 pkt-> data = 1 2 3 4
i need know whether on right path, , if yes can send using
send(sockfd, &packet, sizeof(packet), 0)
for receiving
recv(newsockfd, &packet, sizeof(packet), 0)
i have started network programming, not sure whether on right path or not. of great if can guide me question in form (theoretical,examples etc). in advance.
the pointer pkt
not defined in application. have 2 options: 1) declare pkt
normal variable
struct packet pkt; pkt.srcid = 01; .... send(sockfd, &pkt, sizeof(struct packet), 0);
2) second approach useful when packet contains header followed payload:
char buffer[max_packet_size]; struct packet *pkt = (struct packet *) buffer; char *payload = buffer + sizeof(struct packet); int packet_size; /* should computed header size + payload size */ pkt->srcid = 01; ... packet_size = sizeof(struct packet) /* + payload size */ ; send(sockfd, pkt, packet_size, 0); ....
updated (to answer comment): first, should know receiving tcp socket may not provide whole packet. need implement loop (as suggested nemo) read whole packet. since prefer second option, need 2 loops. first loop read packet header extract payload size , second loop read data. in case of udp, don't need worry partial receiving. here sample code (without looping) sockfd udp socket:
char buffer[max_packet_size]; struct packet *pkt = (struct packet *) buffer; char *payload = buffer + sizeof(struct packet); int packet_size; /* should computed header size + payload size */ ..... /* read whole packet */ if (recv(sockfd, pkt, max_packet_size, 0) < 0) { /* error in receiving packet. how handle */ } /* now, can extract srcid pkt->srcid */ /* can data processing payload variable */
remember: * need implement serialization mentioned other users * udp unreliable transport protocol while tcp reliable transport protocol.
Comments
Post a Comment