用c语言写一个两个client通过udp互相收发消息的代码
时间: 2024-12-18 08:26:29 浏览: 19
在C语言中,使用UDP协议编写两个客户端通过网络相互发送和接收数据,首先需要包含必要的头文件,如`sys/socket.h`、`netinet/in.h` 和 `arpa/inet.h`。下面是一个简单的示例,展示了如何创建套接字、设置地址信息、绑定端口以及发送和接收数据:
```c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8080
#define BUFFER_SIZE 1024
void create_socket(int *sock) {
*sock = socket(AF_INET, SOCK_DGRAM, 0);
if (*sock == -1) {
perror("Error creating socket");
exit(EXIT_FAILURE);
}
}
void bind_to_address(int sock, char *ip) {
struct sockaddr_in server_address;
memset(&server_address, 0, sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_port = htons(PORT);
inet_pton(AF_INET, ip, &server_address.sin_addr);
if (bind(sock, (struct sockaddr *)&server_address, sizeof(server_address)) == -1) {
perror("Error binding to address");
exit(EXIT_FAILURE);
}
printf("Server bound to %s:%d\n", ip, PORT);
}
int main() {
int client_sock1, client_sock2;
char message[BUFFER_SIZE], received_message[BUFFER_SIZE];
// 创建并初始化第一个客户端socket
create_socket(&client_sock1);
// 地址替换为你的IP或其他服务器地址
char server_ip[] = "192.168.1.1"; // 请替换为你想连接的服务器IP
bind_to_address(client_sock1, server_ip);
while (1) {
printf("Client 1, enter a message to send (or 'exit' to quit): ");
fgets(message, sizeof(message), stdin);
message[strcspn(message, "\n")] = '\0'; // remove newline character
if (strcmp(message, "exit") == 0) break; // check for quitting command
// 发送消息到服务器
sendto(client_sock1, message, strlen(message), 0, (struct sockaddr *)&server_address, sizeof(server_address));
// 接收来自服务器的消息
ssize_t bytes_received = recvfrom(client_sock1, received_message, sizeof(received_message), 0, NULL, NULL);
if (bytes_received > 0) {
printf("Received from Client 2: %s\n", received_message);
} else {
perror("Error receiving message");
}
}
close(client_sock1); //关闭套接字
return 0;
}
```
同样的,你需要为第二个客户端做类似的操作,但是使用不同的端口号,并将它们作为接收方来发送消息给第一个客户端。
阅读全文