C语言使用UDP协议通过192.168.88.254:8888和192.168.88.100:6666通讯
时间: 2024-04-15 07:32:01 浏览: 146
基于c语言实现的UDP通信系统
以下是一个使用UDP协议在192.168.88.254:8888和192.168.88.100:6666之间进行通信的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define SERVER_IP "192.168.88.254"
#define SERVER_PORT 8888
#define CLIENT_IP "192.168.88.100"
#define CLIENT_PORT 6666
#define MAX_BUFFER_SIZE 1024
int main() {
int sockfd;
struct sockaddr_in server_addr, client_addr;
char buffer[MAX_BUFFER_SIZE];
// 创建套接字
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
perror("Error in socket");
exit(1);
}
// 设置服务器地址
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVER_PORT);
if (inet_pton(AF_INET, SERVER_IP, &(server_addr.sin_addr)) <= 0) {
perror("Error in inet_pton");
exit(1);
}
// 设置客户端地址
memset(&client_addr, 0, sizeof(client_addr));
client_addr.sin_family = AF_INET;
client_addr.sin_port = htons(CLIENT_PORT);
if (inet_pton(AF_INET, CLIENT_IP, &(client_addr.sin_addr)) <= 0) {
perror("Error in inet_pton");
exit(1);
}
// 将套接字绑定到客户端地址
if (bind(sockfd, (struct sockaddr*)&client_addr, sizeof(client_addr)) < 0) {
perror("Error in bind");
exit(1);
}
// 发送数据到服务器
strcpy(buffer, "Hello, server!");
if (sendto(sockfd, buffer, strlen(buffer), 0, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
perror("Error in sendto");
exit(1);
}
// 接收服务器回复
memset(buffer, 0, sizeof(buffer));
socklen_t server_addr_len = sizeof(server_addr);
if (recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*)&server_addr, &server_addr_len) < 0) {
perror("Error in recvfrom");
exit(1);
}
printf("Received from server: %s\n", buffer);
// 关闭套接字
close(sockfd);
return 0;
}
```
在上述示例中,我们创建了一个UDP套接字,并设置了服务器和客户端的地址信息。然后,我们将套接字绑定到客户端地址,并发送一条消息给服务器。最后,我们等待服务器的回复并将其打印出来。请注意,IP地址和端口号是示例值,你需要根据实际情况修改。
阅读全文