gethostname()函数的用法

来源:互联网 发布:mac口红russian red 编辑:程序博客网 时间:2024/03/29 03:24
gethostname() -- 获取进程所在机器的计算机的名字
注:  -- 用域名或主机名获取IP地址,这个域名或主机名可以是本地机器的主机名/域名;也可以是远端节点的域名


#include <stdio.h>
#include <unistd.h>

int main()
{
char name[65];
gethostname(name, sizeof(name));
printf("hostname = %s\n", name);
}

编译运行
---------------------------------
# gcc test.c
# ./a.out
hostname = zxl
# uname -n
zxl




理论分析
---------------------------------
task_struct
|-----------| struct nsproxy
| | -+-->|------------|
| | -| | count |
| | -| | nslock | struct uts_namespace
| | -| | *uts_ns |---->|---------------------|
|-----------| -| | *ipc_ns | | kref |
| *nsproxy -|--+ | *namespace | |---------------------|
|-----------| |------------| | char sysname[65] |
| | | char nodename[65] |
| | | char release[65] |
| | struct new_utsname name | char version[65] |
| | | char machine[65] |
|-----------| | char domainname[65] |
|---------------------|




/usr/src/linux-2.6.19/kernel/sys.c

asmlinkage long sys_gethostname(char __user *name, int len)
{
int i, errno;

if (len < 0)
return -EINVAL;
down_read(&uts_sem);
i = 1 + strlen(utsname()->nodename);
if (i > len)
i = len;
errno = 0;
if (copy_to_user(name, utsname()->nodename, i))
errno = -EFAULT;
up_read(&uts_sem);
return errno;
}




utsname() -- 返回当前进程的new_utsname结构

/usr/src/linux-2.6.19/include/linux/utsname.h

static inline struct new_utsname *utsname(void)
{
return &current->nsproxy->uts_ns->name;
}
原创粉丝点击