linux udp多线程两个socket绑254.254.254.253端口28005和192.168.131.1端口15003分别发送和接受消息
时间: 2024-01-21 07:19:17 浏览: 134
下面是一个简单的示例代码,可以实现在Linux平台下使用UDP多线程方式同时绑定两个socket,分别发送和接收消息。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define MAX_BUF_SIZE 1024
void *recv_thread_func(void *arg);
void *send_thread_func(void *arg);
int main() {
// 创建接收socket
int recv_sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
if (recv_sock_fd < 0) {
perror("create recv socket error");
exit(1);
}
// 创建发送socket
int send_sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
if (send_sock_fd < 0) {
perror("create send socket error");
exit(1);
}
// 配置接收socket
struct sockaddr_in recv_addr;
memset(&recv_addr, 0, sizeof(recv_addr));
recv_addr.sin_family = AF_INET;
recv_addr.sin_port = htons(15003); // 绑定15003端口
recv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(recv_sock_fd, (struct sockaddr *)&recv_addr, sizeof(recv_addr)) < 0) {
perror("bind recv socket error");
exit(1);
}
// 配置发送socket
struct sockaddr_in send_addr;
memset(&send_addr, 0, sizeof(send_addr));
send_addr.sin_family = AF_INET;
send_addr.sin_port = htons(28005); // 绑定28005端口
if (inet_pton(AF_INET, "254.254.254.253", &send_addr.sin_addr) <= 0) {
perror("inet_pton error");
exit(1);
}
// 创建接收线程
pthread_t recv_thread;
if (pthread_create(&recv_thread, NULL, recv_thread_func, (void *)&recv_sock_fd) != 0) {
perror("create recv thread error");
exit(1);
}
// 创建发送线程
pthread_t send_thread;
if (pthread_create(&send_thread, NULL, send_thread_func, (void *)&send_sock_fd) != 0) {
perror("create send thread error");
exit(1);
}
// 等待线程结束
pthread_join(recv_thread, NULL);
pthread_join(send_thread, NULL);
// 关闭接收socket
close(recv_sock_fd);
// 关闭发送socket
close(send_sock_fd);
return 0;
}
void *recv_thread_func(void *arg) {
int sock_fd = *(int *)arg;
char buf[MAX_BUF_SIZE];
struct sockaddr_in client_addr;
socklen_t client_addr_len;
while (1) {
memset(&buf, 0, sizeof(buf));
client_addr_len = sizeof(client_addr);
int len = recvfrom(sock_fd, buf, MAX_BUF_SIZE, 0, (struct sockaddr *)&client_addr, &client_addr_len);
if (len < 0) {
perror("recvfrom error");
continue;
}
printf("recv message: %s\n", buf);
}
return NULL;
}
void *send_thread_func(void *arg) {
int sock_fd = *(int *)arg;
char buf[MAX_BUF_SIZE];
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(15003);
if (inet_pton(AF_INET, "192.168.131.1", &server_addr.sin_addr) <= 0) {
perror("inet_pton error");
exit(1);
}
while (1) {
memset(&buf, 0, sizeof(buf));
printf("input message: ");
fgets(buf, MAX_BUF_SIZE, stdin);
int len = sendto(sock_fd, buf, strlen(buf), 0, (struct sockaddr *)&server_addr, sizeof(server_addr));
if (len < 0) {
perror("sendto error");
continue;
}
}
return NULL;
}
```
需要注意的是,在Linux平台下,多线程访问同一个socket可能会导致数据混乱或者奔溃,因此上述代码中,我们分别创建了两个socket,并且分别在两个线程中进行读写操作,从而避免了多线程访问同一个socket的问题。
阅读全文