TCP/IP connection on a specific interface

后端 未结 1 1800
予麋鹿
予麋鹿 2020-11-30 10:55

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

相关标签:
1条回答
  • 2020-11-30 10:59

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

    Alternatively:

    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);
    
    0 讨论(0)
提交回复
热议问题