设计Linux环境下的UDP socket通信程序,实现服务器端和客户端的通信
时间: 2023-05-30 20:03:50 浏览: 119
Linux下基于UDP的socket编程,适用多客户端之间,服务器与客户端之间的通信
以下是一个简单的UDP socket通信程序示例,包括服务器端和客户端的代码:
服务器端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 12345
#define BUFFER_SIZE 1024
int main(int argc, char *argv[])
{
int server_fd, ret;
struct sockaddr_in server_addr, client_addr;
socklen_t client_addr_len = sizeof(client_addr);
char buffer[BUFFER_SIZE];
// 创建socket
server_fd = socket(AF_INET, SOCK_DGRAM, 0);
if (server_fd < 0) {
perror("socket");
exit(EXIT_FAILURE);
}
// 绑定地址
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(PORT);
ret = bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr));
if (ret < 0) {
perror("bind");
exit(EXIT_FAILURE);
}
// 接收数据
while (1) {
memset(buffer, 0, BUFFER_SIZE);
ret = recvfrom(server_fd, buffer, BUFFER_SIZE, 0, (struct sockaddr *)&client_addr, &client_addr_len);
if (ret < 0) {
perror("recvfrom");
exit(EXIT_FAILURE);
}
printf("Receive message from %s:%d: %s\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port), buffer);
// 回复数据
ret = sendto(server_fd, buffer, strlen(buffer), 0, (struct sockaddr *)&client_addr, client_addr_len);
if (ret < 0) {
perror("sendto");
exit(EXIT_FAILURE);
}
}
close(server_fd);
return 0;
}
```
客户端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define SERVER_IP "127.0.0.1"
#define PORT 12345
#define BUFFER_SIZE 1024
int main(int argc, char *argv[])
{
int client_fd, ret;
struct sockaddr_in server_addr;
socklen_t server_addr_len = sizeof(server_addr);
char buffer[BUFFER_SIZE];
// 创建socket
client_fd = socket(AF_INET, SOCK_DGRAM, 0);
if (client_fd < 0) {
perror("socket");
exit(EXIT_FAILURE);
}
// 设置服务器地址
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
server_addr.sin_port = htons(PORT);
// 发送数据
while (1) {
printf("Input message: ");
fgets(buffer, BUFFER_SIZE, stdin);
ret = sendto(client_fd, buffer, strlen(buffer), 0, (struct sockaddr *)&server_addr, server_addr_len);
if (ret < 0) {
perror("sendto");
exit(EXIT_FAILURE);
}
// 接收数据
memset(buffer, 0, BUFFER_SIZE);
ret = recvfrom(client_fd, buffer, BUFFER_SIZE, 0, (struct sockaddr *)&server_addr, &server_addr_len);
if (ret < 0) {
perror("recvfrom");
exit(EXIT_FAILURE);
}
printf("Receive message from %s:%d: %s\n", inet_ntoa(server_addr.sin_addr), ntohs(server_addr.sin_port), buffer);
}
close(client_fd);
return 0;
}
```
运行以上代码,可以在服务器端和客户端之间进行简单的UDP通信。
阅读全文