[Question]
1. Bind remote IP and remote Port(do not bind local IP and local Port) on TCP client socket handle.
2. Call "connect" API.
3. On the other thread after "connect" API is called, call getsockname API with given socket handle. "connect" API is blocking function, so uses working thread to call getsockname.
In this case (3). Does getsockname return correct local binding IP address or not?
[Source Code]
#include "VDTCPClient.h"
#include "VDThread.h"
string getLocalIP(SOCKET socketHandle)
{
int size;
string res;
SOCKADDR_IN sAddr;
res = "";
if (socketHandle == INVALID_SOCKET) goto _end;
size = sizeof(sAddr);
if (getsockname(socketHandle, (SOCKADDR*)&sAddr, &size) == 0)
{
res = inet_ntoa(sAddr.sin_addr);
}
_end:
return res;
}
class MyThread : public VDThread
{
protected:
VDTCPClient* tcpClient;
public:
MyThread(VDTCPClient* tcpClient)
{
this->tcpClient = tcpClient;
}
virtual ~MyThread()
{
close();
}
virtual void run()
{
//
// Even if 500 msec elapsed after connect API is called,
// TCP connection has not finished, yet.
//
Sleep(1000);
string localIP = getLocalIP(tcpClient->tcpSession->socketHandle);
printf("T %s\n", localIP.c_str());
}
};
int main()
{
VDTCPClient tcpClient;
string localIP;
localIP = getLocalIP(tcpClient.tcpSession->socketHandle);
printf("1 %s\n", localIP.c_str());
tcpClient.host = "1.1.1.1"; // unexisting ip address on the internet
tcpClient.port = 80;
MyThread* myThread = new MyThread(&tcpClient);
myThread->open();
tcpClient.open();
Sleep(2000);
localIP = getLocalIP(tcpClient.tcpSession->socketHandle);
printf("2 %s\n", localIP.c_str());
delete myThread;
tcpClient.close();
localIP = getLocalIP(tcpClient.tcpSession->socketHandle);
printf("3 %s\n", localIP.c_str());
}
[Result]
1
T 0.0.0.0
2
3