在特定网络接口 Linux/Unix 上使用 C++ TCP 客户端套接字

2022-01-19 00:00:00 sockets tcp network-programming c++

我有以下代码默认连接到接口eth0",它是一个 1G 网卡,但我想使用eth5"连接,它是一个 10G 网卡.

I have the following code which by default connects to interface "eth0" which is a 1G NIC, but I would like to connect using "eth5", which is a 10G NIC.

 class TCPClientSocket {
  protected:
    int socket_file_descriptor_;

  public:

    TCPClientSocket ( ) 
      : socket_file_descriptor_ ( -1 )
    {
      /* socket creation */
      socket_file_descriptor_ = socket ( AF_INET, SOCK_STREAM, 0 );
      if ( socket_file_descriptor_ < 0 ) { exit(1); }
    }

    void Connect ( const std::string & _ors_ip_, const int _ors_port_ ) {
      struct sockaddr_in ors_Addr_ ;
      bzero ( &ors_Addr_, sizeof ( ors_Addr_ ) ) ;
      ors_Addr_.sin_family = AF_INET;
      ors_Addr_.sin_port = htons ( _ors_port_ );
      inet_pton ( AF_INET, _ors_ip_.c_str(), &(ors_Addr_.sin_addr) );

      if ( connect ( socket_file_descriptor_, (struct sockaddr *) &ors_Addr_, sizeof(struct sockaddr_in) ) < 0 ) {
        fprintf ( stderr, "connect() failed on %s:%d
", _ors_ip_.c_str( ), _ors_port_ );
        close ( socket_file_descriptor_ );
        socket_file_descriptor_ = -1;
      }
    }

    inline int WriteN ( const unsigned int _len_, const void * _src_ ) const {
      if ( socket_file_descriptor_ != -1 ) {
        return write ( socket_file_descriptor_, _src_, _len_ );
      }
      return -1;
    }

    inline int ReadN ( const unsigned int _len_, void * _dest_ ) const {
      if ( socket_file_descriptor_ != -1 ) {
        return read ( socket_file_descriptor_, _dest_, _len_ );
      }
      return -1;
    }

    inline bool IsOpen ( ) const { return ( socket_file_descriptor_ != -1 ) ; }
    inline int socket_file_descriptor() const { return socket_file_descriptor_; }    
    void Close ( ) {
      if ( socket_file_descriptor_ != -1 ) {
        shutdown ( socket_file_descriptor_, SHUT_RDWR );
        close ( socket_file_descriptor_ );
        socket_file_descriptor_ = -1;
      }
    }
  };

推荐答案

根据资料here 你可以使用 setsockopt() 来实现这一点,如下所示:

According to the information here you can use setsockopt() to achieve this as follows:

char* interface = "eth5";
setsockopt( socket_file_descriptor_, SOL_SOCKET, SO_BINDTODEVICE, interface, 4 );

最后一个参数,4,代表接口变量的字节数.

The final parameter, 4, represents the number of bytes in the interface variable.

相关文章