TCP 连接有 2 个相同的端点,一旦建立就无法区分。两端都有一个IP地址和一个端口号,另一台计算机必须向它们发送数据。
该connect
函数告诉客户端服务器正在侦听的 IP 地址和端口
该bind
函数告诉客户端它应该在哪个 IP 地址和端口上侦听来自服务器的回复。如果不调用bind()
操作系统会自动选择合适的值。
您遇到的问题(根据您所说)是操作系统选择了错误的默认 IP 地址。这就是绑定函数的用武之地。
下面是您的代码的(未经测试的)固定副本,它绑定到192.168.100.2
. 您需要将其更改为属于您要使用的接口的地址。
如果您打开终端并输入ifconfig -a
,它将打印所有接口的列表以及属于每个接口的 IP 地址。您应该将192.168.100.2
以下代码中的值替换为属于您希望使用的接口的 IP 地址。
int sock, bytes_recieved;
char send_data[1024],recv_data[1024];
struct hostent *host;
struct sockaddr_in server_addr, local_addr; //Added a new variable in here for our local address
host = gethostbyname("192.168.100.4"); //This is the address of the server we are connecting to
cout << "Start" << endl;
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
// perror("Socket");
cout << "Socket error" << endl;
exit(1);
}
//Now we want to bind an IP address
//This is an IP address that belongs to your computer, that will be used as the reply IP address
local_addr.sin_family = AF_INET;
local_addr.sin_addr.s_addr = inet_addr("192.168.100.2"); //CHANGE THIS: this is an address on your computer
local_addr.sin_port = htons(0); //Leave this as 0 and the operating system will choose a unused one for you
if bind(sock, (struct sockaddr *)&local_addr, sizeof(local_addr)) == -1)
{
// perror("Bind");
cout << "Bind error" << endl;
exit(1);
}
//Set up the structure that tells us what server to connect to
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(30002);
server_addr.sin_addr = *((struct in_addr *)host->h_addr);
bzero(&(server_addr.sin_zero),8);
//And connect to the server
if (connect(sock, (struct sockaddr *)&server_addr,
sizeof(struct sockaddr)) == -1)
{
// perror("Connect");
cout << "Connect error" << endl;
exit(1);
}