UDP通信

头文件:

 1 #pragma once
 2 
 3 #include<stdio.h>
 4 #include<unistd.h>
 5 #include<string.h>
 6 #include<stdlib.h>
 7 #include<netinet/in.h>
 8 
 9 #define SERVER_IP   "192.168.0.22"
10 #define SERVER_PORT 10000
11 
12 #define MAX_BUFFER_SIZE 255
13 #define LISTEN_QUEUE_SIZE 5
14 void Perror(char *str)
15 {
16     perror(str);
17     exit(1);
18 }

 

客户端代码:

 1 #include"utili.h"
 2 
 3 int main()
 4 {
 5     int sockCli = socket(AF_INET, SOCK_DGRAM, 0);
 6     if(sockCli == -1)
 7         Perror("socket");
 8 
 9     struct sockaddr_in addrSer,addrCli;
10     addrSer.sin_family = AF_INET;
11     addrSer.sin_port = htons(SERVER_PORT);
12     addrSer.sin_addr.s_addr = inet_addr(SERVER_IP);
13 
14     socklen_t len = sizeof(struct sockaddr);
15     char sendbuf[MAX_BUFFER_SIZE];
16     char recvbuf[MAX_BUFFER_SIZE];
17 
18     while(1)
19     {
20         printf("Cli:>");
21         scanf("%s",sendbuf);
22         sendto(sockCli, sendbuf, strlen(sendbuf)+1, 0, (struct sockaddr*)&addrSer, len);
23 
24         recvfrom(sockCli, recvbuf, MAX_BUFFER_SIZE, 0, (struct sockaddr*)&addrSer, &len);
25         printf("Ser:>%s\n",recvbuf);
26 
27     }
28 
29     close(sockCli);
30     return 0;
31 }

 

服务端代码:

 1 #include"utili.h"
 2 
 3 int main()
 4 {
 5     int sockSer = socket(AF_INET, SOCK_DGRAM, 0);
 6     if(sockSer == -1)
 7         Perror("socket");
 8 
 9     struct sockaddr_in addrSer,addrCli;
10     addrSer.sin_family = AF_INET;
11     addrSer.sin_port = htons(SERVER_PORT);
12     addrSer.sin_addr.s_addr = inet_addr(SERVER_IP);
13 
14     socklen_t len = sizeof(struct sockaddr);
15     int res = bind(sockSer, (struct sockaddr*)&addrSer, len);
16     if(res == -1)
17         Perror("bind");
18 
19     char sendbuf[MAX_BUFFER_SIZE];
20     char recvbuf[MAX_BUFFER_SIZE];
21 
22     while(1)
23     {
24         recvfrom(sockSer, recvbuf, MAX_BUFFER_SIZE, 0, (struct sockaddr*)&addrCli, &len);
25         printf("Cli:>%s\n",recvbuf);
26 
27         printf("Ser:>");
28         scanf("%s",sendbuf);
29         sendto(sockSer, sendbuf, strlen(sendbuf)+1, 0, (struct sockaddr*)&addrCli, len);
30     }
31 
32     close(sockSer);
33     return 0;
34 }

 

转载于:https://www.cnblogs.com/xumiao1314/p/7365083.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值