C ipv6 兼容 ipv4 的 socket 多线程 源代码
时间: 2024-12-25 15:26:39 浏览: 4
IPv6兼容IPv4的socket多线程通常涉及到网络编程中的双栈技术,即在一个程序中同时支持IPv4和IPv6。在C语言中,你可以通过设置socket选项`IPPROTO_IPV6`来启用IPv6套接字功能,并在需要的时候选择发送或接收IPv4或IPv6的数据。
下面是一个简单的多线程示例,展示了如何创建一个服务器,每个线程处理来自不同协议族的连接:
```c
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <pthread.h>
#define PORT 8080
void* thread_func(void* arg) {
int sock = *(int*)arg;
struct sockaddr_storage addr;
socklen_t addr_len = sizeof(addr);
// 确保可以接收IPv4和IPv6
int one = 1;
setsockopt(sock, IPPROTO_IP, IP_TOS, &one, sizeof(one));
setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &one, sizeof(one));
while (1) {
// 接收连接请求
if (accept(sock, (struct sockaddr*)&addr, &addr_len) < 0) {
perror("accept failed");
break;
}
// 根据地址类型决定协议
if (AF_INET == addr.ss_family) {
// IPv4处理
char ip[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &((struct sockaddr_in*)&addr)->sin_addr, ip, sizeof(ip));
printf("Received connection from IPv4: %s\n", ip);
// 处理连接...
} else if (AF_INET6 == addr.ss_family) {
// IPv6处理
char ip[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, &((struct sockaddr_in6*)&addr)->sin6_addr, ip, sizeof(ip));
printf("Received connection from IPv6: %s\n", ip);
// 处理连接...
}
}
}
int main() {
int server_fd, new_sock;
struct sockaddr_in6 serv_addr6, cli_addr6;
struct sockaddr_in serv_addr4;
server_fd = socket(AF_UNSPEC, SOCK_STREAM, 0);
if (-1 == server_fd) {
perror("socket failed");
return 1;
}
// 设置IPv4和IPv6双栈
bind(server_fd, (struct sockaddr*)&serv_addr6, sizeof(serv_addr6));
serv_addr6.sin6_family = AF_INET6;
serv_addr6.sin6_port = htons(PORT);
sin6_addr_zero(&serv_addr6.sin6_addr);
if (bind(server_fd, (struct sockaddr*)&serv_addr4, sizeof(serv_addr4)) < 0) {
perror("binding to IPv4 failed");
}
listen(server_fd, 5);
pthread_t threads[MAX_THREADS];
// 创建线程
for (int i = 0; i < MAX_THREADS; i++) {
new_sock = accept(server_fd, NULL, NULL);
if (new_sock < 0) {
perror("accepting failed");
continue;
}
pthread_create(&threads[i], NULL, thread_func, (void*)&new_sock);
}
// 等待所有线程结束
for (int i = 0; i < MAX_THREADS; i++) {
pthread_join(threads[i], NULL);
}
close(server_fd);
return 0;
}
```
阅读全文