Sign in to follow this  
md_lasalle

Getting local IP (internet sockets)

Recommended Posts

md_lasalle    190
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

Share this post


Link to post
Share on other sites
md_lasalle    190
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

Share this post


Link to post
Share on other sites
markr    1692
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

Share this post


Link to post
Share on other sites
BlueHabu    106
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);

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this