本地domain套接字udp协议的客户端和服务器端互相发送接受消息的c语言代码
时间: 2024-03-05 16:52:25 浏览: 130
以下是一个简单的本地domain套接字udp协议的客户端和服务器端互相发送接受消息的c语言代码。
服务器端代码:
```c
#include <stdio.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#define SOCKET_NAME "/tmp/udp_socket"
int main() {
int server_fd;
struct sockaddr_un server_addr;
char buffer[1024] = {0};
if ((server_fd = socket(AF_UNIX, SOCK_DGRAM, 0)) == -1) {
perror("socket failed");
return 1;
}
memset(&server_addr, 0, sizeof(struct sockaddr_un));
server_addr.sun_family = AF_UNIX;
strncpy(server_addr.sun_path, SOCKET_NAME, sizeof(server_addr.sun_path) - 1);
if (bind(server_fd, (const struct sockaddr*) &server_addr, sizeof(struct sockaddr_un)) == -1) {
perror("bind failed");
close(server_fd);
return 1;
}
while (1) {
struct sockaddr_un client_addr;
socklen_t len = sizeof(struct sockaddr_un);
int n = recvfrom(server_fd, buffer, sizeof(buffer), 0, (struct sockaddr*) &client_addr, &len);
if (n == -1) {
perror("recvfrom failed");
continue;
}
printf("Received message from client: %s\n", buffer);
if (sendto(server_fd, "Hello from server", 18, 0, (struct sockaddr*) &client_addr, len) == -1) {
perror("sendto failed");
}
}
close(server_fd);
unlink(SOCKET_NAME);
return 0;
}
```
客户端代码:
```c
#include <stdio.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#define SOCKET_NAME "/tmp/udp_socket"
int main() {
int client_fd;
struct sockaddr_un server_addr;
char buffer[1024] = {0};
if ((client_fd = socket(AF_UNIX, SOCK_DGRAM, 0)) == -1) {
perror("socket failed");
return 1;
}
memset(&server_addr, 0, sizeof(struct sockaddr_un));
server_addr.sun_family = AF_UNIX;
strncpy(server_addr.sun_path, SOCKET_NAME, sizeof(server_addr.sun_path) - 1);
if (connect(client_fd, (const struct sockaddr*) &server_addr, sizeof(struct sockaddr_un)) == -1) {
perror("connect failed");
close(client_fd);
return 1;
}
if (send(client_fd, "Hello from client", 18, 0) == -1) {
perror("send failed");
close(client_fd);
return 1;
}
int n = read(client_fd, buffer, sizeof(buffer));
if (n == -1) {
perror("read failed");
close(client_fd);
return 1;
}
printf("Received message from server: %s\n", buffer);
close(client_fd);
return 0;
}
```
注意,这段代码使用了本地domain套接字,因此需要在服务器和客户端之间使用同一个地址。在这个例子中,我们使用了`/tmp/udp_socket`作为套接字地址。这个地址应该在客户端和服务器端代码中保持一致。
阅读全文