由于 BSD 套接字中没有获取 IP 地址的功能,因此我执行了客户端/服务器程序来建立连接。每个线程一个:服务器和客户端。
从带有 localhost 的“inet_ntoa”返回的 IP 地址是 127.0.0.1。
但是网络说我的电脑是这个 10.0.0.7,这个地址是有效的。
如何获得 10.0.0.7 地址?谢谢
这是我的代码:
DWORD WINAPI CIpAddressDlg::Thread_TcpServer(LPVOID iValue)
{
CIpAddressDlg *pp = (CIpAddressDlg*)iValue;
CString c;
char buffer[128];
int sinlen;
struct sockaddr_in sin;
int s, h;
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port = htons(4000); // Port
s = socket(AF_INET, SOCK_STREAM,0);
bind(s,(struct sockaddr*)&sin,sizeof(sin));
listen(s,1);
sinlen = sizeof(sin);
h=accept(s,(struct sockaddr*)&sin,&sinlen );
//get IP address
int len = sizeof sin;
if(::getsockname(h,(struct sockaddr*)&sin,&len) == -1)
pp->MessageBox("Error local host ip");
c.Format("%d\nlocal addr %s:%u\n errno: %d", sin.sin_addr, inet_ntoa(sin.sin_addr),ntohs(sin.sin_port), errno);
pp->MessageBox(c);
//verification of send
recv(h,buffer,sizeof(buffer),0);
pp->MessageBox(buffer);
send(h,buffer,strlen(buffer),0);
::closesocket(s);
return 0;
}
DWORD WINAPI CIpAddressDlg::Thread_TcpClient(LPVOID iValue)
{
CIpAddressDlg *pp = (CIpAddressDlg*)iValue;
CString c;
char buffer[128]= "Hello world";
struct sockaddr_in sin;
struct hostent *host;
int s;
host = gethostbyname("localhost");
memcpy(&(sin.sin_addr), host->h_addr,host->h_length);
sin.sin_family = host->h_addrtype;
sin.sin_port = htons(4000);
s = socket(AF_INET, SOCK_STREAM,0);
connect(s, (struct sockaddr*)&sin,sizeof(sin));
send(s,buffer,strlen(buffer)+1,0);
recv(s,buffer,sizeof(buffer),0);
::closesocket(s);
return 0;
}