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!
gethostname(2)
是POSIX强制的C库函数,为hostname
程序提供动力:
int gethostname(char *name, size_t len);
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)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.