[toc]
前言
李柱明博客:https://i.cnblogs.com/posts/edit-done;postId=15487160
正文
在多网卡编程时,指定使用特定的网卡,通过
bind();
绑定就可以了。
- 注意:原理是在
connect();
里面会轮询网卡链表,找出 IP 对应的网卡进行连接。
如:
参考:stackoverflow
网卡 A:192.168.111.112
网卡 B:10.113.114.115
若使用网卡 A(客户端 demo):
// Error checking omitted for expository purposesint sockfd = socket(AF_INET, SOCK_STREAM, 0);// Bind to a specific network interface (and optionally a specific local port)struct sockaddr_in localaddr;localaddr.sin_family = AF_INET;localaddr.sin_addr.s_addr = inet_addr("192.168.111.112");localaddr.sin_port = 0; // Any local port will dobind(sockfd, (struct sockaddr *)&localaddr, sizeof(localaddr));// Connect to the remote serverstruct sockaddr_in remoteaddr;remoteaddr.sin_family = AF_INET;remoteaddr.sin_addr.s_addr = inet_addr(server_ip);remoteaddr.sin_port = htons(server_port);connect(sockfd, (struct sockaddr *)&remoteaddr, sizeof(remoteaddr));