Code:
//Server
#include<stdio.h> //printf
#include<string.h> //memset
#include<stdlib.h> //exit(0)
#include<netinet/in.h>
#include<sys/socket.h>
#define BUFLEN 512 //Max length of buffer
#define PORT 10003 //The port on which to listen for incoming data
//error check fucntion
void die(char *sockS)
{
perror(sockS);
exit(1);
}
int main(void)
{
struct sockaddr_in S_Serv, S_Cli;
int sockS,slen=sizeof(S_Cli),recv_len;
char buf[BUFLEN];
char hostname[128];
// To get host name
gethostname(hostname, sizeof hostname);
printf("My hostname: %s\n", hostname);
//create a UDP server socket
if((sockS=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP))==-1)
{
die("socket");
}
//zero out the structure
memset((char *)&S_Serv,0,sizeof(S_Serv));
S_Serv.sin_family= AF_INET;
S_Serv.sin_port= htons(PORT);
S_Serv.sin_addr.s_addr=htonl(INADDR_ANY);
//bind socket to port
if (bind(sockS, (struct sockaddr *)&S_Serv,sizeof(S_Serv))==-1)
{
die("bind");
}
//keep listening for data
while(1)
{
printf("waiting for data.......");
fflush(stdout);
//try to receive some data (blocking call)
if ((recv_len=recvfrom(sockS,buf,BUFLEN,0,(struct sockaddr *)&S_Cli,&slen)) == -1)
{
die("recvfrom()");
}
//print details of the client/peer and the data received
printf("Received packet from client %d:%d\n",inet_ntoa(S_Cli.sin_addr),ntohs(S_Cli.sin_port));
printf("data: %s\n",buf);
//reply the client with the same data
if(sendto(sockS, buf, recv_len,0,(struct sockaddr *) &S_Serv, slen) == -1)
{
die("sendto()");
}
}
close(sockS);
return 0;
}
Client
#include<stdio.h> //printf
#include<string.h> //memset
#include<stdlib.h> //exit(0)
#include<netinet/in.h>
#include<sys/socket.h>
#define BUFLEN 512 //Max length of buffer
#define PORT 10003 //The port on which to send data
#define SERVER "127.0.0.1"
void die(char *sockC)
{
perror(sockC);
exit(0);
}
int main(void)
{
struct sockaddr_in S_Cli;
int sockC,slen=sizeof(S_Cli);
char buf[BUFLEN];
char message[BUFLEN];
if ((sockC=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP))==-1)
{
die("socket");
}
memset((char *)& S_Cli,0,sizeof(S_Cli));
S_Cli.sin_family=AF_INET;
S_Cli.sin_port=htons(PORT);
if(inet_aton(SERVER,&S_Cli.sin_addr)==0)
{
fprintf(stderr,"inet_aton() failed \n");
exit(1);
}
while(1)
{
printf("enter message: ");
gets(message);
//send the message
if(sendto(sockC,message,strlen(message),0,(struct sockaddr *)&S_Cli, slen)==-1)
{
die("sendto()");
}
//receive a reply and print it
//clear the buffer by filling null, as it might have previous received data
memset(buf,'0',BUFLEN);
//try to receive some data
if (recvfrom(sockC,buf, BUFLEN,0,(struct sockaddr *)&S_Cli,&slen)==-1)
{
die("recvfrom()");
}
puts(buf);
}
close(sockC);
return 0;
}