socket client 使用特定网卡

在多网卡的机器上,假设两张网卡,分别连接到不同的局域网内,他们有不同的IP
网卡1:192.168.1.100
网卡2:10.101.151.100
假设使用192.168.1.100执行connect(2)调用,则需要先进行bind(2)操作:

// Error checking omitted for expository purposes
int 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.1.100");
localaddr.sin_port = 0;  // Any local port will do
bind(sockfd, (struct sockaddr *)&localaddr, sizeof(localaddr));

// Connect to the remote server
struct 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));

参考:
https://stackoverflow.com/questions/15673846/how-to-give-to-a-client-specific-ip-address-in-c

你可能感兴趣的:(UNIX网络编程(卷1))