C语言udp服务器端实现自定义ip和端口并且间隔显示丢包率的代码
时间: 2024-05-10 20:19:48 浏览: 204
c语言udp服务器端代码
以下是C语言UDP服务器端实现自定义IP和端口并且间隔显示丢包率的代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <errno.h>
#define BUF_SIZE 1024
int main(int argc, char *argv[]) {
if (argc != 4) {
printf("Usage: %s [ip] [port] [interval]\n", argv[0]);
exit(1);
}
struct sockaddr_in serv_addr, clnt_addr;
socklen_t clnt_addr_len = sizeof(clnt_addr);
char buf[BUF_SIZE];
// Create UDP socket
int sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
if (sock_fd < 0) {
perror("socket creation failed");
exit(1);
}
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr(argv[1]);
serv_addr.sin_port = htons(atoi(argv[2]));
// Bind socket to address
if (bind(sock_fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
perror("bind failed");
exit(1);
}
unsigned long interval = strtoul(argv[3], NULL, 0);
unsigned long pkts_sent = 0;
unsigned long pkts_recv = 0;
struct timeval timeout = {
.tv_sec = (long)interval,
.tv_usec = 0
};
if (setsockopt(sock_fd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(struct timeval)) < 0) {
perror("setsockopt failed");
exit(1);
}
while (1) {
if (recvfrom(sock_fd, buf, BUF_SIZE, 0, (struct sockaddr *)&clnt_addr, &clnt_addr_len) >= 0) {
pkts_recv++;
} else if (errno != EAGAIN && errno != EWOULDBLOCK) {
perror("recvfrom failed");
exit(1);
}
pkts_sent++;
double loss_rate = (double)(pkts_sent - pkts_recv) / pkts_sent * 100.0;
printf("Sent %lu packets, Received %lu packets, Loss rate: %0.2f%%\n", pkts_sent, pkts_recv, loss_rate);
sleep(interval);
}
close(sock_fd);
return 0;
}
```
以上代码实现了一个UDP服务器端,代码中使用了`socket()`函数创建socket,`bind()`函数将socket绑定到指定的IP和端口,`recvfrom()`函数接收数据并计算丢包率。同时,也支持指定间隔时间并在指定间隔时间内显示丢包率。
阅读全文