简体   繁体   English

如何在函数中获取主机名?

[英]How can I get my hostname within a function?

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 ). unix hostname程序为我提供了一种非常简单的方式来获取“真实的”主机名(而不是localhost。例如,对于我来说,当前unknown74e5[...]df7.att.net )是unknown74e5[...]df7.att.net )。 But how can I do this inside of my own code with C system calls? 但是,如何使用C系统调用在自己的代码中执行此操作? I'd like to get a char * that has this string in it so that I can pass it into gethostbyname and similar. 我想获取一个char * ,其中包含此字符串,以便可以将其传递给gethostbyname和类似名称。

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)... 在讨论的同时,我还想知道如何通过UNIX系统调用来获取IP地址,而不是依赖程序(或更糟糕的是,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. 您可以使用uname(2)来获得一个充满信息的struct utsname You're interested in nodename 您对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. POSIX还提到了uname函数和utsname结构,并且几乎在所有平台上都可用。 As Thomas mentions in the comments, glibc implements gethostname as a call to uname(2) . 正如Thomas在评论中提到的那样,glibc将gethostname实现为对uname(2)的调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM