Advertisement

[Unix/C] How to find out local host?

Started by April 28, 2004 11:23 AM
3 comments, last by Frankie68 20 years, 9 months ago
What is the fastest way of finding out what MY ip-address is? My best guess is that there will be a function called something like getlocalhost(...), but I cannot find it
gethostname() to get the name of the local machine.
gethostbyname() to get the address of a name machine.

Combine the two ....
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Advertisement
thnx
Or if you just want to know the IP without using a funtion, you can simply enter the command ifconfig on the bash in Unix.

It will show you the various IP''s of the various interfaces your machine has.

VFX
quote:
Original post by Fruny
gethostname() to get the name of the local machine.
gethostbyname() to get the address of a name machine.

Combine the two ....


[pedantic]

That works on most configurations, but not necessarily all. Some hosts don't set their name to the DNS entry for their IP, some have multiple active network interfaces, and others are behind NAT so the "local" IP address doesn't tell you anything about your "apparent" IP address.

With BSD Sockets, call ioctl(OSIOCGIFCONF) on an unconnected UDP endpoint to query all the available network interfaces, then call ioctl(SIOCGIFFLAGS) and filter out them based on AF_INET, IFF_UP, and IFF_LOOPBACK flags.

If those calls don't work, a possible fallback is to connect() the UDP socket to an arbitrary internet host (I like 128.0.0.1). This doesn't generate any network traffic, but let's you call getsockname() to get the IP address you've bound to.

On Windows, use GetIpAddrTable if its available. Otherwise, just fall back to gethostname(gethostbyname()) as suggested above.

As for NAT, you'll almost need a remote server to tell you what your IP address appears to be.

[/pedantic]

edit: ubbcode

[edited by - fprefect on April 29, 2004 4:22:53 AM]
Matt Slot / Bitwise Operator / Ambrosia Software, Inc.

This topic is closed to new replies.

Advertisement