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 客户端套接字
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 静态初始化顺序失败 2022-01-01
- C++ 协变模板 2021-01-01
- 从python回调到c++的选项 2022-11-16
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01