与TCP连接相差不多,UDP同样需要套接字socket产生。
注意:UDP中需要知道对方的IP及port,这样才能正确的传送数据。
UDP服务器实现代码如下:
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include <sys/socket.h> 5 #include <sys/types.h> 6 #include <netinet/in.h> 7 #include <arpa/inet.h> 8 #include <unistd.h> 9 #define IP "192.168.0.124" 10 #define PORT 10000 11 int main(int argc,char *argv[]) 12 { 13 int fd; 14 if((fd = socket(AF_INET,SOCK_DGRAM,0))==-1) 15 { 16 perror("socket"); 17 exit(1); 18 } 19 struct sockaddr_in addr,addr_client; 20 memset(&addr,0,sizeof(addr)); 21 memset(&addr_client,0,sizeof(addr_client)); 22 int len = sizeof(addr_client); 23 addr.sin_family=AF_INET; 24 addr.sin_port=htons(PORT); 25 addr.sin_addr.s_addr=inet_addr(IP); 26 if(-1 == bind(fd,(struct sockaddr*)&addr,sizeof(addr))) 27 { 28 perror("bind"); 29 exit(1); 30 } 31 char buf[128]; 32 memset(buf,0,128); 33 recvfrom(fd,buf,128,0,(struct sockaddr*)&addr_client,&len); 34 printf("recv : %s from %s : %d ",buf,inet_ntoa(addr_client.sin_addr),ntohs(addr_client.sin_port)); 35 if(fork()>0) 36 { 37 while(memset(buf,0,128),recvfrom(fd,buf,128,0,(struct sockaddr*)&addr_client,&len)>0) 38 printf("recv : %s from %s : %d ",buf,inet_ntoa(addr_client.sin_addr),ntohs(addr_client.sin_port)); 39 exit(0); 40 } 41 while(memset(buf,0,128),fgets(buf,128,stdin)!=NULL) 42 sendto(fd,buf,strlen(buf),0,(struct sockaddr*)&addr_client,sizeof(addr)); 43 wait(NULL); 44 close(fd); 45 return 0; 46 }
客户端实现代码如下:
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include <unistd.h> 5 #include <netinet/in.h> 6 #include <sys/types.h> 7 #include <sys/socket.h> 8 #include <arpa/inet.h> 9 #define IP "192.168.0.173" 10 #define PORT 9999 11 int main(int argc,char *argv[]) 12 { 13 int fd; 14 if((fd = socket(AF_INET,SOCK_DGRAM,0))==-1 ) 15 { 16 perror("socket"); 17 exit(1); 18 } 19 struct sockaddr_in addr; 20 memset(&addr,0,sizeof(addr)); 21 int len = sizeof(addr); 22 addr.sin_family = AF_INET; 23 addr.sin_port = htons(PORT); 24 addr.sin_addr.s_addr = inet_addr(IP); 25 char buf[128]; 26 int sendn; 27 if(fork()==0) 28 { 29 while(memset(buf,0,128),fgets(buf,128,stdin)!=NULL) 30 sendto(fd,buf,strlen(buf),0,(struct sockaddr*)&addr,len); 31 exit(0); 32 } 33 while(memset(buf ,0 ,128),recvfrom(fd,buf,128,0,(struct sockaddr*)&addr,&len)>0) 34 printf("recv : %s form : %s:%d ",buf,inet_ntoa(addr.sin_addr),ntohs(addr.sin_port)); 35 wait(NULL); 36 close(fd); 37 return 0; 38 }