Jump to content
  • Advertisement
Sign in to follow this  
md_lasalle

Getting local IP (internet sockets)

This topic is 4219 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
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
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!