2.1 基于UDP的网络编程
![](https://img-blog.csdnimg.cn/20210415181741960.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDY4NjEwMQ==,size_16,color_FFFFFF,t_70#pic_center)
2.2.1 服务端实现
- 使用socket函数,创建一个socket
- 使用bind()函数,绑定ip地址、端口等信息到socket上
- 使用recvfrom()函数,循环接收数据
- 关闭网络
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define PORT 3212
#define MAX_SIZE 512
int main(int argc, char *argv[])
{
int sockfd;
int len = sizeof(struct sockaddr);
char buf[MAX_SIZE];
char buffer[MAX_SIZE];
struct sockaddr_in serv_addr;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0)
{
printf("创建socket失败!");
exit(1);
}