TCP / IP connection on a specific interface

I would like to connect to the server using one of two network routes. How to do it? I searched a little Google, and the general answer is to mess around with the routing table, however this will not help, since the recipient has one IP address. In most examples, there is a client with a single network interface card and a server with several network adapters, but in this case it is the other way around.

ForceBindIP can offer this type of functionality, so I assume it should be possible.

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

I will most likely be using C ++ and winsock for this. I will need to be able to open a connection on a given route as desired (i.e. Do not statically bind to a specific route). I will use simple TCP / IP.

EDIT: Windows 7 Client

+5
source share
1 answer

Use bind()to bind a socket to 192.168.1.3or 192.168.1.2before the call connect(), ConnectEx()or WSAConnect(). This tells the socket which specific interface to use for the outbound connection. For instance:

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

As an alternative:

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);
+5
source

All Articles