获取主机与IP地址的C语言代码
我们将使用以下函数:
gethostname()
:gethostname函数检索本地计算机的标准主机名。
gethostbyname()
:gethostbyname函数从主机数据库中检索与主机名对应的主机信息。
inet_ntoa()
:inet_ntoa函数将(Ipv4)Internet网络地址转换为Internet标准点分十进制格式的ASCII字符串。
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <errno.h>
5 #include <netdb.h>
6 #include <sys/types.h>
7 #include <sys/socket.h>
8 #include <netinet/in.h>
9 #include <arpa/inet.h>
10
11 //返回本地主机名
12 void checkHostName(int hostname){
13 if(hostname == -1){
14 perror("gethostname");
15 exit(1);
16 }
17 }
18
19 //返回主机对应的信息到主机名
20 void checkHostEntry(struct hostent *hostentry){
21 if(hostentry == NULL){
22 perror("gethostbyname");
23 exit(1);
24 }
25 }
26
27 //将Ipv4地址格式转化为点分十进制
28 void checkIPbuffer(char *IPbuffer){
29 if(NULL == IPbuffer){
30 perror("inet_ntoa");
31 exit(1);
32 }
33 }
34
35 //设备代码
36 int main(){
37 char hostbuffer[256];
38 char *IPbuffer;
39 struct hostent *host_entry;
40 int hostname;
41
42 //接收主机名
43 hostname = gethostname(hostbuffer, sizeof(hostbuffer));
44 checkHostName(hostname);
45
46 //接收主机信息
47 host_entry = gethostbyname(hostbuffer);
48 checkHostEntry(host_entry);
49
50 //转换网络地址
51 IPbuffer = inet_ntoa(*((struct in_addr*)
52 host_entry->h_addr_list[0]));
53 printf("Hostname: %s\n", hostbuffer);
54 printf("Host IP: %s\n", IPbuffer);
55
56
57 return 0;
58 }