开发者

Using a C++ TCP client socket on a specific network interface Linux/Unix

开发者 https://www.devze.com 2023-03-28 04:59 出处:网络
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.

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\n", _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;
      }
    }
  };


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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消