Get the IP address of my computer on the local network using BSD sockets?

Since BSD sockets do not have a function to obtain an IP address, I made a client / server program to establish a connection. One thread for each: server and client.

The IP address returned from "inet_ntoa" with localhost was 127.0.0.1.
But the network says that my computer is 10.0.0.7, and this address works.

How to get the address 10.0.0.7? thanks

Here is my code:

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; } 
+1
source share
2 answers

There are simpler ways to get the IP address of the "private" / "LAN" computer on which your program is running. Your solution is very inventive, though.

I think the simplest is probably GetAdaptersAddresses . The sample code on the MSDN page looks pretty detailed.

But if this requires a newer version of the compiler, consider GetAdaptersInfo . See “Method Three” here and sample code here .

Furthermore, it looks like you can also access the IP address through the WinSock API. See this example .

Finally, just as a side element, BSD sockets have a function that does just that ( getifaddrs() ), they simply don’t port it to Windows.

0
source

Despite the intuitive appeal to the concept and, for that matter, the widespread belief in the mentioned concept, computers do not have IP addresses.

Interfaces have IP addresses.

You can get a list of interfaces and select the first one. Unfortunately, getting a list of interfaces in most languages ​​is system dependent.

The usual approach is to just use 0.0.0.0 .

+2
source

All Articles