Gethostname()函數使用實例:
注意: gethostname 獲取的只是一個字符串的主機名。
可以使用gethostbyname()把主機名轉換成IP地址。
源代碼:
#include<unistd.h>
#include<netinet/in.h>
#include<sys/socket.h>
#include<stdio.h>
#include<errno.h>
int main()
{
charname [50];
intgethnrvl;
gethnrvl=gethostname(name,sizeof(name));
if(gethnrvl==-1)
{
perror("gethostnameerror");
_exit(-1);
}
printf("%s \n",name);
return 0;
}
運行結果截圖: