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

bob 295 icanprogram-sKcZck+fQKg at public.gmane.org
Wed Jul 13 19:33:23 UTC 2011


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.

bob

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