UDP socket programming
Client-side program:
#include<stdio.h> #include<stdlib.h> #include<sys/socket.h> #include<netinet/in.h> #include<string.h> #include<netdb.h> int main(int argc, char * argv[]) { int sockfd,bindfd,fromlen,n; struct sockaddr_in server, from; struct hostent *hp; char buff[50]; if(argc<3) { printf("insufficient argument"); exit(1); } sockfd=socket(AF_INET,SOCK_DGRAM,0); if(sockfd<0) { printf("could not create the socket."); exit(1); } server.sin_family=AF_INET; server.sin_port=htons(atoi(argv[2])); hp=gethostbyname(argv[1]); memcpy((char*)hp->h_addr,(char *)&server.sin_addr.s_addr,hp->h_length); fromlen=sizeof(server); printf("Enter the value to request the server:"); fgets(buff,sizeof(buff),stdin); n=sendto(sockfd,buff,sizeof(buff),0,(struct sockaddr *)&server,fromlen); if(n<0) { printf("could not send message."); } n=recvfrom(sockfd,buff,50,0,(struct sockaddr *)&server,&fromlen); if(n<0) { printf("No data to receive."); } printf("Response sent by server is:%s",buff); return 0; }
Server Side Program:
#include<stdio.h> #include<stdlib.h> #include<sys/socket.h> #include<netinet/in.h> #include<string.h> #include<netdb.h> int main(int argc, char * argv[]) { int sockfd,bindfd,fromlen,n; struct sockaddr_in server; struct sockaddr_in from; char buff[50]; if(argc<2) { printf("insufficient argument"); exit(1); } sockfd=socket(AF_INET,SOCK_DGRAM,0); if(sockfd<0) { printf("could not create the socket."); exit(1); } memset((char*)&server,0,sizeof(server)); server.sin_family=AF_INET; server.sin_port=htons(atoi(argv[1])); server.sin_addr.s_addr=INADDR_ANY; bindfd=bind(sockfd,(struct sockaddr *)&server,sizeof(server)); if(bindfd<0) { printf("could not bind."); } fromlen=sizeof(from); while(1) { n=recvfrom(sockfd,buff,sizeof(buff),0,(struct sockaddr *)&from,&fromlen); if(n<0) { printf("No data to receive."); } printf("Message received from client is:%s",buff); printf("type the response to be sent:"); fgets(buff,sizeof(buff),stdin); n=sendto(sockfd,buff,sizeof(buff),0,(struct sockaddr *)&from,fromlen); if(n<0) { printf("could not send message."); } } return 0; }
Execution Instruction:
To compile server.c:
$gcc -o exe_filename server.c
To run exe_filename:
$./exe_filename port_number
Whatever may be the executable file name.
port_number should be the 16-bit integer number.
You have to make sure the server is in listen mode.
To compile client.c:
$gcc -o exe_filename1 client.c
To run exe_filename1:
$./exe_filename1 localhost port_number
in place of localhost, you have to mention the IP address of the server, if your server is listening in another machine.
TCP client-server programming in C