UDP Client.c
#include<stdio.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<netdb.h>
#include<arpa/inet.h>
#include<sys/types.h>
#include<time.h>
#include<errno.h>
#define MAX 100
int main(int argc,char* argv[])
{
int sockfd;
char str[100];
struct sockaddr_in serv_addr;
if((sockfd=socket(AF_INET,SOCK_DGRAM,0))<0)
printf("client:can't open datagram socket");
bzero((char *) &serv_addr,sizeof(serv_addr));
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=inet_addr(argv[1]);;
serv_addr.sin_port=htons(atoi(argv[2]));;
/*if(bind(sockfd,(struct sockaddr*) &cli_addr,sizeof(cli_addr))<0)
printf("client:can't bind the local address");*/
printf("enter message to server:");
gets(str);
if(sendto(sockfd,str,100,0,(struct sockaddr*) &serv_addr,sizeof(serv_addr))<0)
{
printf("\nError connection not established...\n");
exit(0);
}
printf("\nconnected\n");
close(sockfd);
exit(0);
return 0;
}
UDP Server.c
#include<stdio.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<netdb.h>
#include<arpa/inet.h>
#include<sys/types.h>
#include<time.h>
#define MAX 100
int cwork(int);
int main()
{
int sockmain,sockclient,child,n;
struct sockaddr_in serv;
char str[100];
int port=4055;
if((sockmain=socket(AF_INET,SOCK_STREAM,0))<0)
{
printf("server cannot open main socket!");
exit(0);
}
bzero(&serv,sizeof(serv));
serv.sin_family=AF_INET;
serv.sin_addr.s_addr=htonl(INADDR_ANY);
serv.sin_port=htons(port);
for(;;)
{
n=sizeof(serv);
sockclient=recvfrom(sockmain,str,100,0,(struct sockaddr*)&serv,&n);
if(sockclient<0)
{
printf("bad client socket");
exit(0);
}
if((child=fork())<0)
{
printf("failed to create child");
exit(0);
}
else if (child==0)
{
close(sockmain);
n=cwork(sockclient);
close(sockclient);
exit(0);
}
close(sockclient);
}
return 0;
}
#define LEN 100
int cwork(int sockclient)
{
char buf[LEN];
int msglen;
bzero(buf,LEN);
if((msglen=recv(sockclient,buf,LEN,0))<0)
{
printf("Bad recv by child");
exit(1);
}
printf("\nsocket used: %d",sockclient);
buf[msglen]='\0';
printf("\nmessage : %s",buf);
strcpy(buf,"message received ...");
send(sockclient,buf,strlen(buf),0);
return 0;
}
OUTPUT SCREEN:-
cc UDPserver.c
./a.out
UDP socket created……...listening port 4001
Server received the message: hello
From client: hello
Server: hey
Server received the message: HowRU?
From client: HowRU?
Server: fine.
Server received the message: bye
From client: bye
Server: bye
No comments:
Post a Comment