from http://ty1992.blog.51cto.com/7098269/1685880
gethostname() : 返回本地主機的標准主機名。
原型如下:
#include <unistd.h>
int gethostname(char *name, size_t len);
參數說明:
這個函數需要兩個參數:
接收緩沖區name,其長度必須為len字節或是更長,存獲得的主機名。
接收緩沖區name的最大長度
返回值:
如果函數成功,則返回0。如果發生錯誤則返回-1。錯誤號存放在外部變量errno中。
gethostbyname()函數說明——用域名或主機名獲取IP地址
包含頭文件
#include <netdb.h>
#include <sys/socket.h>
函數原型
struct hostent *gethostbyname(const char *name);
這個函數的傳入值是域名或者主機名,例如"www.google.cn"等等。傳出值,是一個hostent的結構。如果函數調用失敗,將返回NULL。
返回hostent結構體類型指針
1
2
3
4
5
6
7
8
|
struct hostent {
char *h_name; /* official name of host */
char **h_aliases; /* alias list */
int h_addrtype; /* host address type */
int h_length; /* length of address */
char **h_addr_list; /* list of addresses */
}
#define h_addr h_addr_list[0] /* for backward compatibility */
|
hostent->h_name
表示的是主機的規范名。例如www.google.com的規范名其實是www.l.google.com。
hostent->h_aliases
表示的是主機的別名.www.google.com就是google他自己的別名。有的時候,有的主機可能有好幾個別名,這些,其實都是為了易於用戶記憶而為自己的網站多取的名字。
hostent->h_addrtype
表示的是主機ip地址的類型,到底是ipv4(AF_INET),還是pv6(AF_INET6)
hostent->h_length
表示的是主機ip地址的長度
hostent->h_addr_lisst
表示的是主機的ip地址,注意,這個是以網絡字節序存儲的。千萬不要直接用printf帶%s參數來打這個東西,會有問題的哇。所以到真正需要打印出這個IP的話,需要調用inet_ntop()。
const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt) :
這個函數,是將類型為af的網絡地址結構src,轉換成主機序的字符串形式,存放在長度為cnt的字符串中。返回指向dst的一個指針。如果函數調用錯誤,返回值是NULL。
實例如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
#include <stdio.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
void handler( int sig){
printf ( "recv a sig=%d\n" ,sig);
exit (EXIT_SUCCESS);
}
#define ERR_EXIT(m) \
do { \
perror (m); \
exit (EXIT_FAILURE);\
} while (0);
int main( void )
{
char host[100] = {0};
if (gethostname(host, sizeof (host)) < 0){
ERR_EXIT( "gethostname" );
}
struct hostent *hp;
if ((hp=gethostbyname(host)) == NULL){
ERR_EXIT( "gethostbyname" );
}
int i = 0;
while (hp->h_addr_list[i] != NULL)
{
printf ( "hostname: %s\n" ,hp->h_name);
printf ( " ip: %s\n" ,inet_ntoa(*( struct in_addr*)hp->h_addr_list[i]));
i++;
}
return 0;
}
|
編譯運行
-----------------------------
# gcc -o getinfo getinfo.c
# ./getinfo
hostname: www.server1.com
ip: 69.172.201.208
注意:試驗時主機名要是域名格式(如www.server1.com,若函數為server1時gethostbuname函數返回為NULL),gethostbyname()函數才能獲取到信息,否則返回NULL
本文出自 “划舞魚” 博客,請務必保留此出處http://ty1992.blog.51cto.com/7098269/1685880