代码示例_网络编程_UDP

UDP


 

1. 头文件

 

 1 #pragma once
 2 
 3 #include <stdio.h>
 4 #include <stdlib.h>
 5 #include <sys/types.h>
 6 #include <sys/stat.h>
 7 #include <sys/socket.h>
 8 #include <strings.h>
 9 #include <string.h>
10 #include <unistd.h>
11 #include <fcntl.h>
12 #include <arpa/inet.h>
13 
14 #define IP "192.168.2.150"
15 #define PORT 9999
16 #define SIZE 128

 


 

2. client_udp 

 1 #include "net.h"
 2 
 3 int main(void)
 4 {
 5     //1.创建套接字
 6     int fd = socket( AF_INET, SOCK_DGRAM, 0);
 7     if(fd<0){
 8         perror("socket failed");
 9         exit(1);
10     }
11 
12 
13     //2.初始服务器地址
14     struct sockaddr_in cli;
15     cli.sin_family = AF_INET;
16     cli.sin_port = htons(PORT);
17     cli.sin_addr.s_addr = inet_addr(IP);
18 
19 
20     //3.发送
21     char buf[SIZE];
22     while(1){
23     bzero(buf,SIZE);
24     printf("please input :\t");
25     fgets(buf,SIZE,stdin);
26     int ret = sendto( fd,buf,SIZE,0,(struct sockaddr*)&cli,sizeof(cli) );
27         if(ret<0){
28             perror("send failed");
29             exit(1);
30         }
31     if(!strncmp(buf,"quit",4))
32         break;
33     }
34 
35     //4.关闭
36     close(fd);
37 
38 
39     return 0 ;
40 }

 


 

3. server_udp 

 1 #include "net.h"
 2 
 3 int main(void)
 4 {
 5     //1.创建套接字
 6     int fd = socket(AF_INET,SOCK_DGRAM,0);
 7     if(fd<0){
 8         perror("socket failed");
 9         exit(1);
10     }
11 
12 
13     //2.初始本地地址
14     struct sockaddr_in ser;
15     ser.sin_family = AF_INET;
16     ser.sin_port = htons(PORT);
17     ser.sin_addr.s_addr=inet_addr(IP);
18 
19 
20     //绑定
21     if(  bind(fd,(struct sockaddr*)&ser,sizeof(ser)) <0){
22         perror("bind failed");
23         exit(1);
24     }
25 
26 
27     //接收
28     char buf[SIZE];
29     socklen_t len = sizeof(ser);
30     while(1){
31     bzero(buf,SIZE);
32     int ret = recvfrom(fd,buf,SIZE,0,(struct sockaddr*)&ser,&len);
33         if(ret<0){
34             perror("recvfrom failed");
35             exit(1);
36         }
37         else if(ret==0){
38             printf("客户端下线...");
39             break;
40         }
41         else if(ret>0){
42             printf("server : %s",buf);
43             if(!strncmp(buf,"quit",4))
44             break;
45         }
46     }
47 
48     return 0 ;
49 }

 

测试:


 

 

 

success !

 

posted @ 2019-06-21 18:26  panda_w  阅读(377)  评论(0编辑  收藏  举报