#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<string.h>
int
main(int argc,char **argv){
if(argc<2)
{
printf("insuffcient
parameters");
exit(0);
}
struct sockaddr_in servsock;
int sockfd,size;
char msg[1024],str[1024];
if((sockfd=socket(AF_INET,SOCK_DGRAM,0))<0)
{
perror("");
exit(0); }
printf("socket
created\n");
size=sizeof(struct sockaddr);
socklen_t len=sizeof(servsock);
bzero(&servsock,size);
servsock.sin_port=htons(3000);
servsock.sin_family=AF_INET;
servsock.sin_addr.s_addr=inet_addr(argv[1]);
if(strcmp(msg,"bye")==0)
exit(0);
while(strcmp(msg,"bye")!=0)
{ printf("\n
client: ");
scanf("%s",msg);
if((sendto(sockfd,msg,sizeof(msg),0,(struct
sockaddr*)&servsock,len))<0)
{perror("not
send");
exit(0); }
if(strcmp(msg,"bye")==0)
exit(0);
printf("\n from
server: ");
if((recvfrom(sockfd,str,1024,0,NULL,NULL))<0)
{
perror("not
received");
exit(0); }
printf("%s",str);
}
close(sockfd);
return 0;
}
Server Side:-
//server
program
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<string.h>
int
main(int argc,char **argv)
{
struct sockaddr_in mysock,newsock;
int sockfd;
char buf[1024];
int size,val;
if((sockfd=socket(AF_INET,SOCK_DGRAM,0))<0){
perror("no
socket");
exit(0);}
size=sizeof(struct sockaddr);
socklen_t len=sizeof(newsock);
bzero(&mysock,size);
mysock.sin_family=AF_INET;
mysock.sin_port=htons(3000);
mysock.sin_addr.s_addr=htonl(INADDR_ANY);
if((bind(sockfd,(struct
sockaddr*)&mysock,size))<0){
perror("no bind");
exit(0);}
if(strcmp(buf,"bye")==0)
exit(0);
while(strcmp(buf,"bye")!=0)
{
if((val=recvfrom(sockfd,buf,1024,0,(struct
sockaddr*)&newsock,&len))<0){
perror("
");
exit(0);}
printf("\n from
client: ");
printf("%s",buf);
if(strcmp(buf,"bye")==0){
printf("\nserver:
");
scanf("%s",buf);
exit(0);}
printf("\n server:
");
scanf("%s",buf);
if((sendto(sockfd,buf,val,0,(struct
sockaddr*)&newsock,len))<0){
perror("\n
no send");
exit(0);}
}
close(sockfd);
return 0;
}
No comments:
Post a Comment
Have some problem with this code? or Request the code you want if you cant find it in Blog Archive.