用C语言编写一个UDP客户端程序,向服务器发送一个字符串,并接收服务器返回的响应。
时间: 2024-10-09 10:10:15 浏览: 65
在C语言中,我们可以使用`sys/socket.h`, `arpa/inet.h`, 和 `unistd.h` 等头文件来创建UDP客户端。以下是一个简单的示例,展示了如何连接到服务器、发送数据并接收响应:
```c
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 12345 // 假设服务器监听这个端口
#define BUFFER_SIZE 1024
int main() {
struct sockaddr_in server_addr;
char send_data[] = "Hello from client"; // 发送的数据
char receive_buffer[BUFFER_SIZE];
int sock, bytes_sent, bytes_received;
// 创建套接字
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) {
perror("Error creating socket");
return 1;
}
// 设置服务器地址
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
inet_pton(AF_INET, "localhost", &server_addr.sin_addr);
// 发送数据
bytes_sent = sendto(sock, send_data, strlen(send_data), 0, (struct sockaddr*)&server_addr, sizeof(server_addr));
if (bytes_sent <= 0) {
perror("Error sending data");
return 1;
}
printf("Sent %d bytes of data\n", bytes_sent);
// 接收数据
bytes_received = recvfrom(sock, receive_buffer, BUFFER_SIZE, 0, NULL, NULL);
if (bytes_received <= 0) {
perror("Error receiving response");
return 1;
}
printf("Received %d bytes of response: %s\n", bytes_received, receive_buffer);
// 关闭套接字
close(sock);
return 0;
}
```
阅读全文