C语言实现client端可以向指定IP和端口udp端口发送测试流
时间: 2024-05-07 19:16:34 浏览: 126
量的程序,你能帮我实现吗?
当然可以,您可以使用socket编程实现该程序。先创建一个UDP socket,然后发送UDP数据报到指定的IP地址和端口号。以下是C语言实现的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define BUF_SIZE 512
int main(int argc, char *argv[])
{
if (argc != 3) {
fprintf(stderr, "Usage: %s <IP> <port>\n", argv[0]);
exit(EXIT_FAILURE);
}
const char *ip = argv[1];
int port = atoi(argv[2]);
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
perror("socket");
exit(EXIT_FAILURE);
}
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
if (inet_pton(AF_INET, ip, &addr.sin_addr) <= 0) {
perror("inet_pton");
exit(EXIT_FAILURE);
}
char buf[BUF_SIZE];
strncpy(buf, "This is a test message.", BUF_SIZE);
if (sendto(sockfd, buf, strlen(buf), 0, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
perror("sendto");
exit(EXIT_FAILURE);
}
printf("Sent message to %s:%d\n", ip, port);
close(sockfd);
return 0;
}
```
您只需要将IP和端口号作为命令行参数传递给程序即可。
阅读全文