C语言实现udp服务器端监听根据输入的ip和端口的代码
时间: 2024-05-07 08:16:27 浏览: 178
以下是使用C语言实现UDP服务器端监听根据输入的IP和端口的代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define BUF_SIZE 1024
int main(int argc , char *argv[])
{
int udp_socket;
struct sockaddr_in server_addr, client_addr;
char buffer[BUF_SIZE];
int str_len, client_addr_size;
if(argc != 3) {
printf("Usage: %s <IP> <port>\n", argv[0]);
exit(1);
}
udp_socket = socket(PF_INET, SOCK_DGRAM, 0);
if (udp_socket == -1)
printf("Error: socket()\n");
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(atoi(argv[2]));
if (bind(udp_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1)
printf("Error: bind()\n");
while(1) {
client_addr_size = sizeof(client_addr);
str_len = recvfrom(udp_socket, buffer, BUF_SIZE-1, 0, (struct sockaddr*)&client_addr, &client_addr_size);
if (str_len < 0)
break;
buffer[str_len] = '\0';
printf("Received message from %s:%d: %s\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port), buffer);
str_len = sendto(udp_socket, buffer, str_len, 0, (struct sockaddr*)&client_addr, client_addr_size);
if (str_len < 0)
break;
}
close(udp_socket);
return 0;
}
```
希望对你有帮助。
阅读全文