what is the best way to find local IP address/hostname from inside C program?

Lennart Sorensen lsorense-1wCw9BSqJbv44Nm34jS7GywD8/FfD2ys at public.gmane.org
Thu Jul 14 15:11:00 UTC 2011


On Wed, Jul 13, 2011 at 03:33:23PM -0400, bob 295 wrote:
> I was revisiting some really old code in my SIMPL project recently.  This 
> logic helps determine whether or not a requested communication channel is 
> opened locally via shared memory or remotely via TCP/IP surrogates.
> 
> Although the code isn't written this cleanly, essentially the functionality 
> required can be captured in a function something like:
> 
> int isThisMe(char *mynode)
> 
> where the mynode string can either be a dotted text respresentation of an IP 
> address or a straight node name.   ie. we return a 1 when the mynode matches 
> the node info for the node on which the call is being made,  or a 0 if there 
> is no match.   . 
> 
> Does anyone know the best practice for making this kind of determination these 
> days?
> 
> I can't recall the issues when this code was created in the 1999-2000 time 
> frame.   For example I don't recall why the gethostname() function was not 
> used for part of the algorithm but instead the algorithm relies on a 
> getenv("HOSTNAME") or parsing of /etc/hostname to get the local host name and 
> the a gethostbyname() to generate an IPaddress representing this node.
> 
> On another interesting sidebar,  during my recent testing on several of the 
> Linux systems I have access to the call:
> 
> getenv("HOSTNAME")
> 
> will return NULL even though 
> 
> echo $HOSTNAME
> 
> from a shell returns a valid name.    Any ideas why this no longer works in 
> modern Linux distributions?   Is there a special check inside the getenv code 
> to bypass HOSTNAME?
> 
> Thanks in advance for your help.

There is no requirement for a system to have it's hostname map to an IP.
It's not and usually done, but not required.

I suspect if you check the source and destination of the socket, if they
are the same, then it is you, otherwise it is someone else in most cases.

-- 
Len Sorensen
--
The Toronto Linux Users Group.      Meetings: http://gtalug.org/
TLUG requests: Linux topics, No HTML, wrap text below 80 columns
How to UNSUBSCRIBE: http://gtalug.org/wiki/Mailing_lists





More information about the Legacy mailing list