写一个C语言用select实现udp自定义IP,端口的服务器端例子
时间: 2024-05-14 13:13:04 浏览: 96
可以参考以下代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/select.h>
#define BUF_SIZE 1024
#define IP_ADDR "127.0.0.1"
#define PORT 8888
int main()
{
struct sockaddr_in serv_addr, cli_addr;
int serv_sock, cli_sock;
socklen_t addr_len;
char buf[BUF_SIZE];
int i, n;
serv_sock = socket(AF_INET, SOCK_DGRAM, 0);
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr(IP_ADDR);
serv_addr.sin_port = htons(PORT);
bind(serv_sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
printf("UDP server is running on %s:%d\n", IP_ADDR, PORT);
fd_set read_fds, all_fds;
int max_fd = serv_sock;
FD_ZERO(&all_fds);
FD_SET(serv_sock, &all_fds);
while (1) {
read_fds = all_fds;
if (select(max_fd + 1, &read_fds, NULL, NULL, NULL) < 0) {
perror("select");
exit(1);
}
for (i = 0; i <= max_fd; ++i) {
if (FD_ISSET(i, &read_fds)) {
if (i == serv_sock) {
addr_len = sizeof(cli_addr);
n = recvfrom(serv_sock, buf, BUF_SIZE, 0,
(struct sockaddr *)&cli_addr, &addr_len);
printf("Received packet from %s:%d\n",
inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port));
if (n < 0) {
perror("recvfrom");
exit(1);
}
FD_SET(cli_sock, &all_fds);
if (cli_sock > max_fd) {
max_fd = cli_sock;
}
} else {
n = sendto(i, buf, n, 0, (struct sockaddr *)&cli_addr, addr_len);
if (n < 0) {
perror("sendto");
exit(1);
}
}
}
}
}
return 0;
}
```
当然,以上代码只是一个简单的例子,实际应用中可能还需要增加更多的错误处理和逻辑。
阅读全文