特定接口上的TCP / IP连接

时间:2013-02-05 00:00:02

标签: c++ winsock

我想使用两种网络路由之一连接到服务器。怎么会这样做?我用谷歌搜索了很多,常见的答案是摆弄路由表,但是由于目的地只有一个IP地址,这无济于事。大多数示例都包含一个带有单个网卡的客户端和一个带有多个NIC的服务器,但在这种情况下则相反。

ForceBindIP应用程序似乎能够提供此类功能,所以我想它一定是可能的。

             +----->-------+
192.168.1.3  |      B      |          192.168.1.4
      +--------+      +--------+      +--------+
      | Client |      | Switch |-->---| Server |
      +--------+      +--------+      +--------+
192.168.1.2  |      A      |
             +----->-------+

我很可能会使用C ++和winsock来做到这一点。我需要能够随意打开给定路由上的连接(即不得静态绑定到特定路由)。我将使用普通的'TCP / IP。

编辑:Windows 7客户端

1 个答案:

答案 0 :(得分:6)

在致电192.168.1.3192.168.1.2connect()之前,使用bind()功能将套接字绑定到ConnectEx()WSAConnect()。这告诉套接字使用哪个特定接口进行传出连接。例如:

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);