C语言udp服务器端实现自定义ip和端口并且统计丢包率的代码
时间: 2024-05-12 10:15:51 浏览: 156
以下是示例代码,用于实现C语言UDP服务器端自定义IP和端口并统计丢包率:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define MAXLEN 1024
int main(int argc, char **argv)
{
struct sockaddr_in serveraddr, clientaddr;
int sockfd, n, len, count = 0;
char buffer[MAXLEN];
if(argc != 3)
{
printf("Usage: %s <ip> <port>\n", argv[0]);
return 0;
}
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if(sockfd < 0)
{
perror("socket error");
return 0;
}
bzero(&serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(atoi(argv[2]));
inet_pton(AF_INET, argv[1], &serveraddr.sin_addr);
if(bind(sockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0)
{
perror("bind error");
return 0;
}
len = sizeof(clientaddr);
while(1)
{
n = recvfrom(sockfd, buffer, MAXLEN, 0, (struct sockaddr *)&clientaddr, &len);
if(n < 0)
{
perror("recvfrom error");
continue;
}
if(!strcmp(buffer, "exit"))
break;
count++;
printf("received %d bytes from %s:%d, message: %s\n", n, inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port), buffer);
}
printf("received %d messages from clients, packet loss rate: %.2f%%\n", count, (float)count/(float)(count+1)*100);
close(sockfd);
return 0;
}
```
这段代码实现了UDP服务器的基本功能,并且可以自定义IP和端口。同时,它还计算了收到的数据包数量并且统计了丢包率。在使用时,只需要在命令行中输入IP和端口号即可启动服务器。
阅读全文