EPOLL 监听 UDP 代码示例
时间: 2023-07-09 20:46:14 浏览: 216
下面是一个简单的用 EPOLL 监听 UDP 的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define MAX_EVENTS 10
int main() {
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == -1) {
perror("socket error");
exit(1);
}
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(8888);
if (bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
perror("bind error");
exit(1);
}
int epollfd = epoll_create(1);
if (epollfd == -1) {
perror("epoll_create error");
exit(1);
}
struct epoll_event ev, events[MAX_EVENTS];
ev.events = EPOLLIN;
ev.data.fd = sockfd;
if (epoll_ctl(epollfd, EPOLL_CTL_ADD, sockfd, &ev) == -1) {
perror("epoll_ctl error");
exit(1);
}
while (1) {
int n = epoll_wait(epollfd, events, MAX_EVENTS, -1);
if (n == -1) {
perror("epoll_wait error");
exit(1);
}
for (int i = 0; i < n; i++) {
if (events[i].data.fd == sockfd) {
struct sockaddr_in cli_addr;
socklen_t len = sizeof(cli_addr);
char buf[1024];
int nrecv = recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&cli_addr, &len);
if (nrecv == -1) {
perror("recvfrom error");
exit(1);
}
buf[nrecv] = '\0';
printf("Received %d bytes from %s:%d: %s\n", nrecv, inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port), buf);
}
}
}
close(epollfd);
close(sockfd);
return 0;
}
```
在上面的代码中,我们先创建了一个 UDP 套接字,并绑定到本地地址和端口上。然后创建了一个 EPOLL 对象,并将监听套接字注册到其中,并设置事件类型为 EPOLLIN,表示可以读取数据。最后在 while 循环中不断调用 epoll_wait 等待事件发生,并在事件发生时进行处理(在这里只处理了来自监听套接字的数据)。
阅读全文