linux udp socket 进程间通讯 C语言代码
时间: 2023-03-13 13:12:10 浏览: 115
我了解到 UDP Socket 是一种网络协议,它可以让进程之间进行通讯。使用 C 语言实现 UDP Socket 的进程间通讯,可以参考下面的代码:#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#define PORT 8080int main(int argc, char const *argv[])
{
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {0};
char *hello = "Hello from server";
// Creating socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_DGRAM, 0)) == 0)
{
perror("socket failed");
exit(EXIT_FAILURE);
}
// Forcefully attaching socket to the port 8080
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,
&opt, sizeof(opt)))
{
perror("setsockopt");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( PORT );
// Forcefully attaching socket to the port 8080
if (bind(server_fd, (struct sockaddr *)&address,
sizeof(address))<0)
{
perror("bind failed");
exit(EXIT_FAILURE);
}
while(1)
{
int len, n;
n = recvfrom(server_fd, (char *)buffer, 1024,
MSG_WAITALL, ( struct sockaddr *) &address,
&addrlen);
buffer[n] = '\0';
printf("Client : %s\n", buffer);
sendto(server_fd, (const char *)hello, strlen(hello),
0, (const struct sockaddr *) &address,
addrlen);
printf("Hello message sent.\n");
}
return 0;
}
阅读全文