Blame view

c/inet.c 2.23 KB
36845477b   김태훈   네트워크 인터페이스의 IP 주소...
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
  #include <netdb.h>
  #include <string.h>
  #include <ifaddrs.h>
  
  #include "inet.h"
  
  static struct sockaddr *find_address_of(char *name, struct ifaddrs *from)
  {
      struct ifaddrs *ifa;
      int n;
      for (ifa = from, n = 0; ifa != NULL; ifa = ifa->ifa_next, n++) {
          if (strcmp(ifa->ifa_name, name)) {
              continue;
          }
  
          if (ifa->ifa_addr == NULL) {
              continue;
          }
  
          int family = ifa->ifa_addr->sa_family;
          if (family == AF_INET || family == AF_INET6) {
              return ifa->ifa_addr;
          }
      }
  
      return NULL;
  }
  
  static struct sockaddr *find_netmask_of(char *name, struct ifaddrs *from)
  {
      struct ifaddrs *ifa;
      int n;
      for (ifa = from, n = 0; ifa != NULL; ifa = ifa->ifa_next, n++) {
          if (strcmp(ifa->ifa_name, name)) {
              continue;
          }
  
          if (ifa->ifa_netmask == NULL) {
              continue;
          }
  
          int family = ifa->ifa_netmask->sa_family;
          if (family == AF_INET || family == AF_INET6) {
              return ifa->ifa_netmask;
          }
      }
  
      return NULL;
  }
  
  static int address_to_string(struct sockaddr *addr, char *buffer, int size)
  {
      return getnameinfo(addr,
          (addr->sa_family == AF_INET)
              ? sizeof(struct sockaddr_in)
              : sizeof(struct sockaddr_in6),
          buffer, size,
          NULL, 0,
          NI_NUMERICHOST);
  }
  
  int get_ip_addr(char *p_ip, int sz_ip)
  {
      struct ifaddrs *ifaddr;
      if (getifaddrs(&ifaddr) == -1) {
          return -1;
      }
  
      struct sockaddr *address = find_address_of(IFNAME, ifaddr);
      if (address == NULL) {
          goto ERROR;
      }
  
      int ret = address_to_string(address, p_ip, sz_ip);
      if (ret != 0) {
          goto ERROR;
      }
  
      freeifaddrs(ifaddr);
      return 0;
  
  ERROR:
      freeifaddrs(ifaddr);
      return -1;
  }
  
  int get_netmask(char *p_netmask, int sz_netmask)
  {
      struct ifaddrs *ifaddr;
      if (getifaddrs(&ifaddr) == -1) {
          return -1;
      }
  
      struct sockaddr *netmask = find_netmask_of(IFNAME, ifaddr);
      if (netmask == NULL) {
          goto ERROR;
      }
  
      int ret = address_to_string(netmask, p_netmask, sz_netmask);
      if (ret != 0) {
          goto ERROR;
      }
  
      freeifaddrs(ifaddr);
      return 0;
  
  ERROR:
      freeifaddrs(ifaddr);
      return -1;
  }