udpserver.c
#include "stdio.h" #include "stdlib.h" #include "sys/types.h" #include "sys/socket.h" #include "arpa/inet.h" #include "netinet/in.h" #include "string.h" #define SA struct sockaddr #define MAX 1024 int main(int argc,char** argv) { int sockfd,n; socklen_t len; struct sockaddr_in servaddr,cliaddr; char buff[MAX],tmp[MAX]; //create socket sockfd = socket(AF_INET,SOCK_DGRAM,0); //fill socket servaddr.sin_family = AF_INET; servaddr.sin_port = htons(atoi(argv[1])); servaddr.sin_addr.s_addr = htonl(INADDR_ANY); //bind bind(sockfd,(SA*)&servaddr,sizeof(servaddr)); for(;;) { bzero(buff,sizeof(buff)); len = sizeof(cliaddr); n=recvfrom(sockfd,buff,MAX,0,(SA*)&cliaddr,&len); strcpy(tmp,buff); printf("received : %s",tmp); if(n < 6) { perror("send message"); exit(0); } sendto(sockfd,tmp,MAX,0,(SA*)&cliaddr,len); bzero(buff,sizeof(buff)); } close(sockfd); return 0; }udpclient.c
#include "stdio.h" #include "stdlib.h" #include "sys/types.h" #include "sys/socket.h" #include "arpa/inet.h" #include "netinet/in.h" #include "string.h" #define SA struct sockaddr #define MAX 1024 int main(int argc,char** argv) { int sockfd,n; socklen_t len; struct sockaddr_in servaddr; char buff[MAX]; //create socket sockfd = socket(AF_INET,SOCK_DGRAM,0); //fill struct servaddr.sin_family = AF_INET; servaddr.sin_port = htons(atoi(argv[1])); servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); //send to server printf("enter message\n"); for(;;) { bzero(buff,sizeof(buff)); fgets(buff,MAX,stdin); len=sizeof(servaddr); sendto(sockfd,buff,MAX,0,(SA*)&servaddr,len); bzero(buff,sizeof(buff)); recvfrom(sockfd,buff,MAX,0,(SA*)&servaddr,&len); printf("%s",buff); } close(sockfd); return 0; }
Comments
Post a Comment