-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathgethostbyname_test.cpp
More file actions
64 lines (57 loc) · 1.2 KB
/
gethostbyname_test.cpp
File metadata and controls
64 lines (57 loc) · 1.2 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//
// Created by jxq on 19-8-6.
//
#include <iostream>
#include <stdio.h>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
} while (0);
int getlocalip(char *ip)
{
char host[100] = {0};
if (gethostname(host, sizeof host) < 0)
{
ERR_EXIT("gethostname");
}
struct hostent *hp;
if ((hp = gethostbyname(host)) == NULL)
{
ERR_EXIT("gethostbyname");
}
strcpy(ip, inet_ntoa(*(struct in_addr*)hp->h_addr_list[0]));
return 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("%s\n", inet_ntoa(*(struct in_addr*)hp->h_addr_list[i]));
// ++i;
// }
char ip[16] = {0};
getlocalip(ip);
printf("localip = %s\n", ip);
return 0;
}