linux udp多线程两个socket绑254.254.254.253端口28005和192.168.131.1端口15003接受消息
时间: 2023-12-20 22:03:27 浏览: 112
以下是一个简单的示例代码,可以让您在Linux上使用多线程同时监听两个UDP套接字:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#define BUF_SIZE 1024
void *recv_thread(void *arg);
int main()
{
// 创建套接字1,绑定254.254.254.253:28005
int sock1 = socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in addr1;
memset(&addr1, 0, sizeof(addr1));
addr1.sin_family = AF_INET;
addr1.sin_port = htons(28005);
inet_pton(AF_INET, "254.254.254.253", &addr1.sin_addr);
bind(sock1, (struct sockaddr *)&addr1, sizeof(addr1));
// 创建套接字2,绑定192.168.131.1:15003
int sock2 = socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in addr2;
memset(&addr2, 0, sizeof(addr2));
addr2.sin_family = AF_INET;
addr2.sin_port = htons(15003);
inet_pton(AF_INET, "192.168.131.1", &addr2.sin_addr);
bind(sock2, (struct sockaddr *)&addr2, sizeof(addr2));
// 创建两个接收线程,分别监听两个套接字
pthread_t tid1, tid2;
pthread_create(&tid1, NULL, recv_thread, (void *)&sock1);
pthread_create(&tid2, NULL, recv_thread, (void *)&sock2);
// 等待两个线程结束
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
return 0;
}
void *recv_thread(void *arg)
{
int sock = *(int *)arg;
struct sockaddr_in peer_addr;
socklen_t peer_addr_len = sizeof(peer_addr);
char buf[BUF_SIZE];
while (1) {
ssize_t n = recvfrom(sock, buf, BUF_SIZE, 0,
(struct sockaddr *)&peer_addr, &peer_addr_len);
if (n <= 0) {
perror("recvfrom");
continue;
}
// 处理接收到的数据
printf("Received %zd bytes from %s:%d\n", n,
inet_ntoa(peer_addr.sin_addr), ntohs(peer_addr.sin_port));
fwrite(buf, 1, n, stdout);
putchar('\n');
}
return NULL;
}
```
在这个示例代码中,我们使用了两个线程来分别监听两个UDP套接字。`recv_thread` 函数是每个线程的入口函数,它通过参数传递套接字描述符。在函数内部,我们使用 `recvfrom` 函数从套接字接收数据,并将接收到的数据输出到控制台上。注意,在多线程程序中,我们需要使用互斥锁等机制来保证对共享资源的访问是安全的,但在此示例中我们省略了这些细节。
阅读全文