#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
int main()
{
// 1.创建UDP通信对象
int udp_socket = socket(AF_INET, SOCK_DGRAM, 0);
// 2.绑定UDP通信socket
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(8888);
addr.sin_addr.s_addr = INADDR_ANY;
int ret = bind(udp_socket, (struct sockaddr *)&addr, sizeof(addr));
if (ret < 0)
{
perror("绑定失败\n");
return -1;
}
else
{
printf("绑定成功\n");
}
// 3.接收数据
char buf[1024] = {0};
printf("等待对方发送数据\n");
recvfrom(udp_socket, buf, 1024, 0, NULL, NULL);
printf("接收到数据:%s\n", buf);
// 4.关闭套接字
close(udp_socket);
}