Operating System - HP-UX
1753278 Members
5606 Online
108792 Solutions
New Discussion юеВ

Re: get client "hostname" in C?

 
Tim Howell
Frequent Advisor

get client "hostname" in C?

What is the most sensible way to get the hostname of a client for use inside a C program? That is, if a client that has an IP address connects to a host via telnet and executes a program containing gethostname(), it will return the name of the host, of course. Is there something similar for the client name?
{HP-UX 11i, HP C/ANSI C, aC++}
if only we knew...
3 REPLIES 3
A. Clay Stephenson
Acclaimed Contributor

Re: get client "hostname" in C?

Not really. You have to understand that you could be N levels deep in indirection (ie telnet to HostA then telnet to HostB then telnet to HostC ... --- which of those do you want?

If you can assume that you are only I level deep then

build up a command like this:
who -um | awk '{split($NF,x," "); print x[1]

and stuff that into a popen and read it.

That will probably be the most portable way to do this.
If it ain't broke, I can fix that.
A. Clay Stephenson
Acclaimed Contributor

Re: get client "hostname" in C?

Ooops,
who -um | awk '{split($NF,x," "); print x[1]
should be:
who -um | awk '{split($NF,x,":"); print x[1]

who -um normally reports just the hostname (or IP address) in the last field but if this is a CDE session you would see hostname:0.0 (or IP_Address:0.0). The split on ":" and then printing the first elemnt of the array regardless or whether the colon is found assure you that only the hostname (or IP Address id hostname is unknown) is returned.



If it ain't broke, I can fix that.
rick jones
Honored Contributor

Re: get client "hostname" in C?

If the user connects via telnet or the like, presumeably stdin will be a socket. That being the case, the application may be able to call getpeername() on stdin/stdout. If someone runs that same application from the console the getpeername() call will of course return an error - that the fd is not a socket most likely.

Armed with the IP address of the peer (remote/client) one can call getnodeinfo() to return the hostname information available for that IP address. That call should be in all the 11i releases, IIRC. Or you can use the older, non-IPV6-aware gethostbyaddr() call.
there is no rest for the wicked yet the virtuous have no pillows