Linux C代码 获取IP地址
Ubuntu 16.04下,可编译通过:
1 #include <stdio.h>
2 #include <ifaddrs.h>
3 #include <arpa/inet.h>
4 #include <cstring>
5
6 #define MAX_LENGTH 254
7
8 int main(void)
9 {
10 char ipAddr[MAX_LENGTH];
11
12 ipAddr[0] = '\0';
13
14 struct ifaddrs * ifAddrStruct = NULL;
15 void * tmpAddrPtr = NULL;
16
17 if (getifaddrs(&ifAddrStruct) != 0)
18 {
19 //if wrong, go out!
20 printf("Somting is Wrong!\n");
21 return -1;
22 }
23
24 struct ifaddrs * iter = ifAddrStruct;
25
26 while (iter != NULL) {
27 if (iter->ifa_addr->sa_family == AF_INET) { //if ip4
28 // is a valid IP4 Address
29 tmpAddrPtr = &((struct sockaddr_in *)iter->ifa_addr)->sin_addr;
30 char addressBuffer[INET_ADDRSTRLEN];
31 inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
32 if (strlen(ipAddr) + strlen(addressBuffer) < MAX_LENGTH - 1)
33 {
34 if (strlen(ipAddr) > 0)
35 {
36 strcat(ipAddr, ";");
37 }
38 strcat(ipAddr, addressBuffer);
39 }
40 else
41 {
42 printf("Too many ips!\n");
43 break;
44 }
45 }
46 //else if (ifaddrstruct->ifa_addr->sa_family == af_inet6) { // check it is ip6
47
48 /* deal ip6 addr */
49 // tmpaddrptr = &((struct sockaddr_in *)ifaddrstruct->ifa_addr)->sin_addr;
50 // char addressbuffer[inet6_addrstrlen];
51 // inet_ntop(af_inet6, tmpaddrptr, addressbuffer, inet6_addrstrlen);
52
53 //}
54 iter = iter->ifa_next;
55 }
56 //releas the struct
57 freeifaddrs(ifAddrStruct);
58
59 printf("The ips: %s\n", ipAddr);
60
61 return 0;
62 }
效果: