Getting local IP (internet sockets)

Started by
2 comments, last by BlueHabu 17 years, 4 months ago
Hi! I'm doing some application in C/C++ using pure berkeley sockets. I want to know, what is the best way to get the adress from the current local machine, right now what I'm doing returns 127.1.1.0, i want to have 192.168.0.100 for insntace i gethostname() -> gives me my computer name ( marcd-linuxbox ) and then i create a hostent struct with the gethostbyname() it works on Windows machine, but now I'm on Linux. Thanks for any help
Advertisement
ok i managed to find this talking about ioctl() function and i managed to get that the second interface returns 192.168.0.102 like i wanted

But this brings me to another question, how can i know if the second interface will always return the right local adress, as the first one currently returns 127.0.0.1
You should read the FAQ, about why knowing the local IP address is not necessary in most cases.

You have to realise that machines can have more than one (indeed, more than two) interfaces each of which can have a different IP address. None of them is any more "right" as the local IP than any other.

To discover which interface is being used to route to a particular destination, I think you may be able to connect a socket to that destination and then call getsockname().

But of course, in principle, routing can change during the lifetime of a socket. Interfaces may also come and go (well, at least go up and down) or change IP during the lifetime of an application.

Mark
markr is correct. Here is code sample from my network library that I am currently developing.

    // TODO check error number after calling getsockname()    int iSize = sizeof(Socket::mLocalSocketAddress);    getsockname(this->mulSocket, (sockaddr*)&this->mLocalSocketAddress, &iSize);    mulLocalIP    = ntohl(this->mLocalSocketAddress.sin_addr.s_addr);    musLocalPort  = ntohs(this->mLocalSocketAddress.sin_port);

This topic is closed to new replies.

Advertisement