特定接口上的TCP / IP连接 [英] TCP/IP connection on a specific interface
问题描述
我想使用两种网络路由之一连接到服务器。如何做到这一点?我已经google了很多,常见的答案是干扰路由表,但是这不会有帮助,因为目的地有一个单一的IP地址。大多数示例的特点是具有单个网卡的客户端和具有多个网卡的服务器,但在这种情况下是相反的。
I'd like to connect to a server using one of two network routes. How would one do this? I've Googled quite a bit, and the common answer is to fiddle with the routing table, however this won't help as the destination has a single IP address. Most of the examples feature a client with a single net card and a server with multiple NICs, but it's the opposite in this case.
ForceBindIP应用程序似乎能够提供这种类型的功能,所以我想这一定是可能的。
The ForceBindIP app seems to be able to offer this type of functionality, so I guess it must be possible.
+----->-------+
192.168.1.3 | B | 192.168.1.4
+--------+ +--------+ +--------+
| Client | | Switch |-->---| Server |
+--------+ +--------+ +--------+
192.168.1.2 | A |
+----->-------+
最有可能是使用C ++和winsock来做到这一点。我需要能够随意打开给定路由上的连接(即不能静态绑定到特定路由)。我将使用纯粹的TCP / IP。
I'll most likely be using C++ and winsock to do this. I'll need to be able to open a connection on a given route at will (i.e. must not be statically bound to a particular route). I'll be using plain ol' TCP/IP.
编辑:Windows 7客户端
Windows 7 client
推荐答案
使用 bind()
函数将套接字绑定到 192.168.1.3
或 192.168.1.2 $在调用
connect()
, ConnectEx()
或
。这告诉套接字哪个特定接口用于传出连接。例如:
Use the bind()
function to bind the socket to either 192.168.1.3
or 192.168.1.2
before calling connect()
, ConnectEx()
, or WSAConnect()
. That tells the socket which specific interface to use for the outgoing connection. For example:
SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
sockaddr_in localaddr = {0};
localaddr.sin_family = AF_INET;
localaddr.sin_addr.s_addr = inet_addr("192.168.1.3");
bind(s, (sockaddr*)&localaddr, sizeof(localaddr));
sockaddr_in remoteaddr = {0};
remoteaddr.sin_family = AF_INET;
remoteaddr.sin_addr.s_addr = inet_addr("192.168.1.4");
remoteaddr.sin_port = 12345; // whatever the server is listening on
connect(s, (sockaddr*)&remoteaddr, sizeof(remoteaddr));
或者:
addrinfo localhints = {0};
localhints.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV;
localhints.ai_family = AF_INET;
localhints.ai_socktype = SOCK_STREAM;
localhints.ai_protocol = IPPROTO_TCP;
addrinfo *localaddr = NULL;
getaddrinfo("192.168.1.3", "0", &localhints, &localaddr);
bind(s, localaddr->ai_addr, localaddr->ai_addrlen);
freeaddrinfo(localaddr);
addrinfo remotehints = {0};
remotehints.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV;
remotehints.ai_family = AF_INET;
remotehints.ai_socktype = SOCK_STREAM;
remotehints.ai_protocol = IPPROTO_TCP;
addrinfo *remoteaddr = NULL;
getaddrinfo("192.168.1.4", "12345", &remotehints, &remoteaddr);
connect(s, remoteaddr->ai_addr, remoteaddr->ai_addrlen);
freeaddrinfo(remoteaddr);
这篇关于特定接口上的TCP / IP连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!