Using a C++ TCP client socket on a specific network interface Linux/Unix(在特定网络接口 Linux/Unix 上使用 C++ TCP 客户端套接字)
问题描述
我有以下代码默认连接到接口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.
这篇关于在特定网络接口 Linux/Unix 上使用 C++ TCP 客户端套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在特定网络接口 Linux/Unix 上使用 C++ TCP 客户端套接字
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
