0

the unix hostname program gives me an exceedingly simple way to get my "real" hostname (not localhost. For example, for me it's currently unknown74e5[...]df7.att.net). But how can I do this inside of my own code with C system calls? I'd like to get a char * that has this string in it so that I can pass it into gethostbyname and similar.

While I'm at it, I'd like also to know how I can get my IP address with UNIX system calls rather than relying on programs (or worse, whatismyip.com)...

Thanks!

limp_chimp
  • 13,475
  • 17
  • 66
  • 105
  • Be aware that a system may have multiple IP addresses. Also, due to NAT, the external IP as seen by whatismyip.com might be different from what the host itself sees. – Thomas Apr 08 '13 at 11:24
  • Also, why do you need to know your own IP? This is rarely needed. If you just want to listen on a socket, use `0.0.0.0` or allow the user to specify it. This is how most Unix servers work. – Thomas Apr 08 '13 at 11:28

2 Answers2

3

gethostname(2) is the POSIX-mandated C library function that powers the hostname program:

   int gethostname(char *name, size_t len);
Thomas
  • 174,939
  • 50
  • 355
  • 478
  • 1
    Really? I thought it was just retrieving a value from the kernel. – Thomas Apr 08 '13 at 11:29
  • 2
    @Joe Maybe you're somehow thinking of `gethost**by**name` ? – cnicutar Apr 08 '13 at 11:33
  • Yeah, that'll be it. Sorry. Ignore all my previous comments! :-) – Joe Apr 08 '13 at 11:34
  • The hostname has nothing to do with DNS. It's just he name of the host as defined by `hostname` and `/etc/hostname/`. `gethostname()` shall not be mixed up with `gethostbyname()`. However it is common practice for network hosts to set the hostname to the name one of the host's nic-ips resolves to. – alk Apr 08 '13 at 14:42
1

You can use uname(2) which gets you a struct utsname filled with information. You're interested in nodename

struct utsname {
    char sysname[];    /* Operating system name (e.g., "Linux") */
    char nodename[];   /* Name within "some implementation-defined network". */

The uname function and utsname struct are also mentioned by POSIX and available on virtually all platforms. As Thomas mentions in the comments, glibc implements gethostname as a call to uname(2).

cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • They're equivalent on systems with GNU libc: "The GNU C library does not employ the gethostname() system call; instead, it implements gethostname() as a library function that calls uname(2) and copies [...] from the returned nodename field [...]" – Thomas Apr 08 '13 at 11:31