Linux 提供了相关API 用于获取系统主机相关信息
获取网络名称:int gethostname(char*name,size_t len)
参数
char*name:获取到的网络名字会写入name字符串中
size_t len:该字符串至少有len 个长度
返回值:
成功时返回0,失败时返回-1
AME
gethostname, sethostname - get/set hostname
SYNOPSIS
#include <unistd.h>
int gethostname(char *name, size_t len);
int sethostname(const char *name, size_t len);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
gethostname(): _BSD_SOURCE || _XOPEN_SOURCE >= 500
sethostname(): _BSD_SOURCE || (_XOPEN_SOURCE && _XOPEN_SOURCE < 500)
DESCRIPTION
These system calls are used to access or to change the hostname of the current processor.
sethostname() sets the hostname to the value given in the character array name. The len argument specifies the number of bytes in name. (Thus,
name does not require a terminating null byte.)
gethostname() returns the null-terminated hostname in the character array name, which has a length of len bytes. If the null-terminated host-
name is too large to fit, then the name is truncated, and no error is returned (but see NOTES below). POSIX.1-2001 says that if such truncation
occurs, then it is unspecified whether the returned buffer includes a terminating null byte.
RETURN VALUE
On success, zero is returned. On error, -1 is returned, and errno is set appropriately.
获取其余详细信息:int uname(struct utsname *name)
参数
struct utsname *name:函数会将主机相关信息写入name 结构体中
返回值:
成功返回0,失败返回-1
demo
AME
uname - get name and information about current kernel
SYNOPSIS
#include <sys/utsname.h>
int uname(struct utsname *buf);
DESCRIPTION
uname() returns system information in the structure pointed to by buf. The utsname struct is defined in <sys/utsname.h>:
struct utsname {
char sysname[]; /* Operating system name (e.g., "Linux") */
char nodename[]; /* Name within "some implementation-defined
network" */
char release[]; /* OS release (e.g., "2.6.28") */
char version[]; /* OS version */
char machine[]; /* Hardware identifier */
#ifdef _GNU_SOURCE
char domainname[]; /* NIS or YP domain name */
#endif
};
The length of the arrays in a struct utsname is unspecified (see NOTES); the fields are terminated by a null byte ('\0').
RETURN VALUE
On success, zero is returned. On error, -1 is returned, and errno is set appropriately.
#include<stdio.h>
#include<stdlib.h>
#include<sys/utsname.h>
int main()
{
int result;
char name[255];
struct utsname hostname;
result=gethostname(name,255);//获取主机网络名称
printf("result=%d,name=%s\n",result,name);
uname(&hostname);//获取主机相关信息
printf("hostname_sysname=%s\n",hostname.sysname);//操作系统名
printf("hostname_version=%s\n",hostname.version);//系统版本号
printf("hostname_machine=%s\n",hostname.machine);//硬件类型
printf("hostname_release=%s\n",hostname.release);//系统发行级别
return 0;
}