views:

497

answers:

5

I'm writing c++ code that I need to run on both windows and linux and I'm looking for a function call that will return the ip address of the box the app is running on. Is there such one?

+1  A: 

Call socket(), then getsockname().

sharptooth
is it a cross platform solution?
Mykola Golubyev
socket() is surely part of BSD sockets and is therefore crossplatform - used it myself on Free BSD. Google says that getsockname() exists on Linux and is mentioned in man, so it's likely to be crossplatform too. I only used this approach in general on Win32.
sharptooth
+1  A: 

You can do it but it's generally a bad idea.

ioctl SIOCGIFCONF as described in "man netdevice" explains this.

The reason it's a bad idea is that you probably won't get what you want out of it.

The machine could have several or many IP addresses, you won't know which one(s) are public. It could be behind a NAT gateway (or several) in which case none of them may be public.

You just can't use that info particularly usefully. Whatever you want it for, it's probably not a good idea to do it.

MarkR
A: 

Best idea is to use a webservice. Connect to a known server, have it send back the IP that you used to contact it. That will tell you the IP address (OK, an IP address) that your PC uses when talking to the outside world.

Possible exceptions and why they do not matter:

  • You get the address of a NAT device - well, in that case your PC doesn't have an Internet address, what were you planning to do with the 10.x.y.z address you probably do have?
  • You don't get an address at all, as you're not connected to the Internet - if you can't connect, it's unlikely another computer could do anythin useful with your IP address.
  • You do get back an IP, but nobody can connect to it - you're likely behind a filtering firewall that refuses any incoming connection. It's quite unlikely that the firewall would accept traffic on another IP address that connects to the same computer. Even if that is the case, it might be impossible to discover. And it would be hell for FTP.
MSalters
A: 

If you know the name of the machine your application run, just use gethostbyname().

bonny