data.h
1 #ifndef DATA_H 2 #define DATA_H 3 #include <stdio.h> 4 #include <string.h> 5 #include <sys/types.h> 6 #include <sys/stat.h> 7 #include <sys/socket.h> 8 #include <stdlib.h> 9 #include <unistd.h> 10 #include <netinet/in.h> 11 #include <arpa/inet.h> 12 #include <netdb.h> 13 #include <errno.h> 14 #define PORT 4578 15 #define maxn 100 16 17 #endif
server.c
1 #include "data.h" 2 int main() 3 { 4 int sockfd; 5 struct sockaddr_in server; 6 struct sockaddr_in client; 7 socklen_t len; 8 int num; 9 char buf[maxn]; 10 if((sockfd = socket(AF_INET,SOCK_DGRAM,0)) == -1) 11 { 12 fprintf(stderr,"socket fail,error:%s ",strerror(errno)); 13 return -1; 14 } 15 bzero(&server,sizeof(server)); 16 server.sin_family = AF_INET; 17 server.sin_port = htons(PORT); 18 server.sin_addr.s_addr = htonl(INADDR_ANY); 19 if(bind(sockfd,(struct sockaddr*)&server,sizeof(server)) == -1) 20 { 21 fprintf(stderr,"bind fail,error:%s ",strerror(errno)); 22 return -1; 23 } 24 len = sizeof(client); 25 bzero(&buf,sizeof(buf)); 26 while(1) 27 { 28 num = recvfrom(sockfd,buf,maxn,0,(struct sockaddr*)&client,&len); 29 if(num < 0) 30 { 31 perror("recvfrom() error! "); 32 exit(1); 33 } 34 num--; 35 buf[num] = '