UDP Programming for client
#include<stdio.h> #include<sys/ipc.h> #include<sys/socket.h> #include<sys/stat.h> #include<stdlib.h> #include<netinet/in.h> #include<string.h> main(int argc,char **argv) { int sd,newsd,ret; socklen_t len; char buf[20]; struct sockaddr_in cAddr,sAddr; sd=socket(PF_INET,SOCK_DGRAM,0); if(sd==-1) { perror("socket"); return; } sAddr.sin_family=PF_INET; sAddr.sin_port=htons(atoi(argv[2])); sAddr.sin_addr.s_addr=inet_addr(argv[1]); while(1) { printf("enter msg:"); scanf("%s",buf); sendto(sd,buf,strlen(buf),0,(struct sockaddr*)&sAddr,sizeof(sAddr)); printf("connect successful\n"); } close(sd); }UDP Programming for Server
#include<stdio.h> #include<sys/ipc.h> #include<sys/socket.h> #include<sys/stat.h> #include<stdlib.h> #include<netinet/in.h> #include<string.h> main(int argc,char **argv) { int sd,newsd,ret; socklen_t len; char buf[20]; struct sockaddr_in cAddr,sAddr; sd=socket(PF_INET,SOCK_DGRAM,0); if(sd==-1) { perror("socket"); return; } sAddr.sin_family=PF_INET; sAddr.sin_port=htons(atoi(argv[1])); sAddr.sin_addr.s_addr=inet_addr("0.0.0.0"); if(bind(sd,(struct sockaddr*)&sAddr,sizeof(sAddr))==-1) perror("bind"); else printf("bind sucess\n"); while(1) { printf("waiting for message....\n"); bzero(buf,20); socklen_t y=sizeof(cAddr); recvfrom(sd,buf,20,0,(struct sockaddr *)&cAddr,&y); printf("%s %s\n",inet_ntoa(cAddr.sin_addr.s_addr),buf); } close(sd); close(newsd); }