先看效果
程序会将收到的信息又发送给对端
流程
程序源码
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define HOST "192.168.1.164" // 本机地址
#define PORT 8888 // 端口
int main ()
{
int sockfd;
int ret;
uint8_t buf[100];
struct sockaddr_in server, peer_addr;
socklen_t peerlen;
peerlen = (socklen_t)sizeof(struct sockaddr);
// 创建UDP Socket
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == -1)
{
printf("fail to creat socket.\r\n");
exit(EXIT_FAILURE);
}
// 设置地址与端口到结构体
memset(&server, 0,sizeof(server));
server.sin_family = AF_INET; // IPV4
server.sin_port = htons(PORT);
server.sin_addr.s_addr = inet_addr(HOST);
// 绑定地址与端口信息
ret = bind(sockfd, (struct sockaddr *)&server, sizeof(struct sockaddr));
if (ret == -1)
{
close(sockfd);
printf("Fail to bind information.\r\n");
exit(EXIT_FAILURE);
}
while (1)
{
// 非阻塞接收消息 并存储对端地址
ret = recvfrom(sockfd, buf, 100, MSG_DONTWAIT, (struct sockaddr *)&peer_addr, &peerlen);
if (ret > 0)
{
// 将消息发回对端
sendto(sockfd, buf, ret, MSG_DONTWAIT, (struct sockaddr *)&peer_addr, peerlen);
printf("recv[%d]: from %s:%d\r\n", ret, inet_ntoa(peer_addr.sin_addr), htons(peer_addr.sin_port));
}
else if (ret == 0)
{
close(sockfd);
break;
}
else
{
if(errno != EINTR && errno != EWOULDBLOCK && errno != EAGAIN)
{
close(sockfd);
break;
}
}
}
return 0;
}