interfaces.c 13.6 KB
Newer Older
Youness Alaoui's avatar
Youness Alaoui committed
1 2 3 4 5
/*
 * interfaces.c - Source for interface discovery code
 *
 * Copyright (C) 2006 Youness Alaoui <kakaroto@kakaroto.homelinux.net>
 * Copyright (C) 2007 Collabora, Nokia
6
 *  Contact: Youness Alaoui
Youness Alaoui's avatar
Youness Alaoui committed
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
 * Copyright (C) 2008 Haakon Sporsheim <haakon.sporsheim@tandberg.com>
 * @author: Youness Alaoui <kakaroto@kakaroto.homelinux.net>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA
 */

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "interfaces.h"
#include "debug.h"

#ifdef G_OS_UNIX

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/types.h>

42
#include <sys/socket.h>
Alexis Ballier's avatar
Alexis Ballier committed
43
#include <netinet/in.h>
44

Youness Alaoui's avatar
Youness Alaoui committed
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
#ifdef HAVE_GETIFADDRS
 #include <ifaddrs.h>
#endif

#include <net/if.h>
#include <net/if_arp.h>
#include <arpa/inet.h>

#ifdef HAVE_GETIFADDRS

GList *
nice_interfaces_get_local_interfaces (void)
{
  GList *interfaces = NULL;
  struct ifaddrs *ifa, *results;

  if (getifaddrs (&results) < 0) {
    return NULL;
  }

  /* Loop and get each interface the system has, one by one... */
  for (ifa = results; ifa; ifa = ifa->ifa_next) {
    /* no ip address from interface that is down */
    if ((ifa->ifa_flags & IFF_UP) == 0)
      continue;

71
    if (ifa->ifa_addr == NULL)
Youness Alaoui's avatar
Youness Alaoui committed
72 73
      continue;

74 75 76 77
    if (ifa->ifa_addr->sa_family == AF_INET || ifa->ifa_addr->sa_family == AF_INET6) {
      nice_debug ("Found interface : %s", ifa->ifa_name);
      interfaces = g_list_prepend (interfaces, g_strdup (ifa->ifa_name));
    }
Youness Alaoui's avatar
Youness Alaoui committed
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 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
  }

  freeifaddrs (results);

  return interfaces;
}

#else /* ! HAVE_GETIFADDRS */

GList *
nice_interfaces_get_local_interfaces (void)
{
  GList *interfaces = NULL;
  gint sockfd;
  gint size = 0;
  struct ifreq *ifr;
  struct ifconf ifc;

  if ((sockfd = socket (AF_INET, SOCK_DGRAM, IPPROTO_IP)) < 0) {
    nice_debug ("error : Cannot open socket to retreive interface list");
    return NULL;
  }

  ifc.ifc_len = 0;
  ifc.ifc_req = NULL;

  /* Loop and get each interface the system has, one by one... */
  do {
    size += sizeof (struct ifreq);
    /* realloc buffer size until no overflow occurs  */
    if (NULL == (ifc.ifc_req = realloc (ifc.ifc_req, size))) {
      nice_debug ("Error : Out of memory while allocation interface"
          "configuration structure");
      close (sockfd);
      return NULL;
    }
    ifc.ifc_len = size;

    if (ioctl (sockfd, SIOCGIFCONF, &ifc)) {
      perror ("ioctl SIOCFIFCONF");
      close (sockfd);
      free (ifc.ifc_req);
      return NULL;
    }
  } while (size <= ifc.ifc_len);


  /* Loop throught the interface list and get the IP address of each IF */
  for (ifr = ifc.ifc_req;
       (gchar *) ifr < (gchar *) ifc.ifc_req + ifc.ifc_len;
       ++ifr) {
    nice_debug ("Found interface : %s", ifr->ifr_name);
    interfaces = g_list_prepend (interfaces, g_strdup (ifr->ifr_name));
  }

  free (ifc.ifc_req);
  close (sockfd);

  return interfaces;
}
#endif /* HAVE_GETIFADDRS */


static gboolean
142
nice_interfaces_is_private_ip (const struct sockaddr *sa)
Youness Alaoui's avatar
Youness Alaoui committed
143
{
144 145
  if (sa->sa_family == AF_INET) {
    struct sockaddr_in *sa4 = (struct sockaddr_in *) sa;
Youness Alaoui's avatar
Youness Alaoui committed
146

147 148 149
    /* 10.x.x.x/8 */
    if (sa4->sin_addr.s_addr >> 24 == 0x0A)
      return TRUE;
Youness Alaoui's avatar
Youness Alaoui committed
150

151 152 153
    /* 172.16.0.0 - 172.31.255.255 = 172.16.0.0/10 */
    if (sa4->sin_addr.s_addr >> 20 == 0xAC1)
      return TRUE;
Youness Alaoui's avatar
Youness Alaoui committed
154

155 156 157
    /* 192.168.x.x/16 */
    if (sa4->sin_addr.s_addr >> 16 == 0xC0A8)
      return TRUE;
Youness Alaoui's avatar
Youness Alaoui committed
158

159 160 161 162 163
    /* 169.254.x.x/16  (for APIPA) */
    if (sa4->sin_addr.s_addr >> 16 == 0xA9FE)
      return TRUE;
  }
  
Youness Alaoui's avatar
Youness Alaoui committed
164 165 166 167 168 169 170 171 172 173
  return FALSE;
}

#ifdef HAVE_GETIFADDRS

GList *
nice_interfaces_get_local_ips (gboolean include_loopback)
{
  GList *ips = NULL;
  struct ifaddrs *ifa, *results;
174
  GList *loopbacks = NULL;
Youness Alaoui's avatar
Youness Alaoui committed
175 176 177 178 179 180

  if (getifaddrs (&results) < 0)
      return NULL;

  /* Loop through the interface list and get the IP address of each IF */
  for (ifa = results; ifa; ifa = ifa->ifa_next) {
181 182
    char addr_as_string[INET6_ADDRSTRLEN+1];

Youness Alaoui's avatar
Youness Alaoui committed
183 184 185 186
    /* no ip address from interface that is down */
    if ((ifa->ifa_flags & IFF_UP) == 0)
      continue;

187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
    if (ifa->ifa_addr == NULL) {
      continue;
    } else if (ifa->ifa_addr->sa_family == AF_INET) {
      struct sockaddr_in *sa4 = (struct sockaddr_in *) ifa->ifa_addr;

      if (inet_ntop (AF_INET, &sa4->sin_addr, addr_as_string,
              INET6_ADDRSTRLEN) == NULL)
        continue;
    } else if (ifa->ifa_addr->sa_family == AF_INET6) {
      struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)ifa->ifa_addr;

      /* Skip link-local addresses, they require a scope */
      if (IN6_IS_ADDR_LINKLOCAL (sa6->sin6_addr.s6_addr))
        continue;

      if (inet_ntop (AF_INET6, &sa6->sin6_addr, addr_as_string,
              INET6_ADDRSTRLEN) == NULL)
        continue;
    } else
Youness Alaoui's avatar
Youness Alaoui committed
206 207 208 209
      continue;


    nice_debug ("Interface:  %s", ifa->ifa_name);
210
    nice_debug ("IP Address: %s", addr_as_string);
Youness Alaoui's avatar
Youness Alaoui committed
211 212
    if ((ifa->ifa_flags & IFF_LOOPBACK) == IFF_LOOPBACK) {
      if (include_loopback)
213
        loopbacks = g_list_append (loopbacks, g_strdup (addr_as_string));
Youness Alaoui's avatar
Youness Alaoui committed
214 215 216
      else
        nice_debug ("Ignoring loopback interface");
    } else {
217 218
      if (nice_interfaces_is_private_ip (ifa->ifa_addr))
        ips = g_list_append (ips, g_strdup (addr_as_string));
Youness Alaoui's avatar
Youness Alaoui committed
219
      else
220
        ips = g_list_prepend (ips, g_strdup (addr_as_string));
Youness Alaoui's avatar
Youness Alaoui committed
221 222 223 224 225
    }
  }

  freeifaddrs (results);

226 227
  if (loopbacks)
    ips = g_list_concat (ips, loopbacks);
Youness Alaoui's avatar
Youness Alaoui committed
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292

  return ips;
}

#else /* ! HAVE_GETIFADDRS */

GList *
nice_interfaces_get_local_ips (gboolean include_loopback)
{
  GList *ips = NULL;
  gint sockfd;
  gint size = 0;
  struct ifreq *ifr;
  struct ifconf ifc;
  struct sockaddr_in *sa;
  gchar *loopback = NULL;

  if ((sockfd = socket (AF_INET, SOCK_DGRAM, IPPROTO_IP)) < 0) {
    nice_debug ("Error : Cannot open socket to retreive interface list");
    return NULL;
  }

  ifc.ifc_len = 0;
  ifc.ifc_req = NULL;

  /* Loop and get each interface the system has, one by one... */
  do {
    size += sizeof (struct ifreq);
    /* realloc buffer size until no overflow occurs  */
    if (NULL == (ifc.ifc_req = realloc (ifc.ifc_req, size))) {
      nice_debug ("Error : Out of memory while allocation interface"
          " configuration structure");
      close (sockfd);
      return NULL;
    }
    ifc.ifc_len = size;

    if (ioctl (sockfd, SIOCGIFCONF, &ifc)) {
      perror ("ioctl SIOCFIFCONF");
      close (sockfd);
      free (ifc.ifc_req);
      return NULL;
    }
  } while  (size <= ifc.ifc_len);


  /* Loop throught the interface list and get the IP address of each IF */
  for (ifr = ifc.ifc_req;
       (gchar *) ifr < (gchar *) ifc.ifc_req + ifc.ifc_len;
       ++ifr) {

    if (ioctl (sockfd, SIOCGIFFLAGS, ifr)) {
      nice_debug ("Error : Unable to get IP information for interface %s."
          " Skipping...", ifr->ifr_name);
      continue;  /* failed to get flags, skip it */
    }
    sa = (struct sockaddr_in *) &ifr->ifr_addr;
    nice_debug ("Interface:  %s", ifr->ifr_name);
    nice_debug ("IP Address: %s", inet_ntoa (sa->sin_addr));
    if ((ifr->ifr_flags & IFF_LOOPBACK) == IFF_LOOPBACK){
      if (include_loopback)
        loopback = g_strdup (inet_ntoa (sa->sin_addr));
      else
        nice_debug ("Ignoring loopback interface");
    } else {
293
      if (nice_interfaces_is_private_ip (sa)) {
Youness Alaoui's avatar
Youness Alaoui committed
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
        ips = g_list_append (ips, g_strdup (inet_ntoa (sa->sin_addr)));
      } else {
        ips = g_list_prepend (ips, g_strdup (inet_ntoa (sa->sin_addr)));
      }
    }
  }

  close (sockfd);
  free (ifc.ifc_req);

  if (loopback)
    ips = g_list_append (ips, loopback);

  return ips;
}

#endif /* HAVE_GETIFADDRS */

gchar *
nice_interfaces_get_ip_for_interface (gchar *interface_name)
{
  struct ifreq ifr;
  struct sockaddr_in *sa;
  gint sockfd;


  ifr.ifr_addr.sa_family = AF_INET;
  memset (ifr.ifr_name, 0, sizeof (ifr.ifr_name));
322
  g_strlcpy (ifr.ifr_name, interface_name, sizeof (ifr.ifr_name));
Youness Alaoui's avatar
Youness Alaoui committed
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523

  if ((sockfd = socket (AF_INET, SOCK_DGRAM, IPPROTO_IP)) < 0) {
    nice_debug ("Error : Cannot open socket to retreive interface list");
    return NULL;
  }

  if (ioctl (sockfd, SIOCGIFADDR, &ifr) < 0) {
    nice_debug ("Error : Unable to get IP information for interface %s",
      interface_name);
    close (sockfd);
    return NULL;
  }

  close (sockfd);
  sa = (struct sockaddr_in *) &ifr.ifr_addr;
  nice_debug ("Address for %s: %s", interface_name, inet_ntoa (sa->sin_addr));
  return g_strdup (inet_ntoa (sa->sin_addr));
}

#else /* G_OS_UNIX */
#ifdef G_OS_WIN32

#include <winsock2.h>
#include <Iphlpapi.h>

static gboolean started_wsa_engine = FALSE;

/*
 * private function that initializes the WinSock engine and
 *  returns a prebuilt socket
 */
SOCKET nice_interfaces_get_WSA_socket ()
{
  WORD wVersionRequested;
  WSADATA wsaData;
  int err;
  SOCKET sock;

  if (started_wsa_engine == FALSE) {
    wVersionRequested = MAKEWORD ( 2, 0 );

    err = WSAStartup ( wVersionRequested, &wsaData );
    if ( err != 0 ) {
      nice_debug ("Error : Could not start the winsocket engine");
      return INVALID_SOCKET;
    }
    started_wsa_engine = TRUE;
  }


  if ((sock = socket (AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET) {
    nice_debug ("Error : Could not open socket to retreive interface list,"
        " error no : %d", WSAGetLastError ());
    return INVALID_SOCKET;
  }

  return sock;
}

GList * nice_interfaces_get_local_interfaces ()
{
  ULONG size = 0;
  PMIB_IFTABLE if_table;
  GList * ret = NULL;

  GetIfTable(NULL, &size, TRUE);

  if (!size)
    return NULL;

  if_table = (PMIB_IFTABLE)g_malloc0(size);

  if (GetIfTable(if_table, &size, TRUE) == ERROR_SUCCESS) {
    DWORD i;
    for (i = 0; i < if_table->dwNumEntries; i++) {
      ret = g_list_prepend (ret, g_strdup ((gchar*)if_table->table[i].bDescr));
    }
  }

  g_free(if_table);

  return ret;
}

GList * nice_interfaces_get_local_ips (gboolean include_loopback)
{
  ULONG size = 0;
  DWORD pref = 0;
  PMIB_IPADDRTABLE ip_table;
  GList * ret = NULL;

  GetIpAddrTable (NULL, &size, TRUE);

  if (!size)
    return NULL;

  /*
   * Get the best interface for transport to 0.0.0.0.
   * This interface should be first in list!
   */
  if (GetBestInterface (0, &pref) != NO_ERROR)
    pref = 0;

  ip_table = (PMIB_IPADDRTABLE)g_malloc0 (size);

  if (GetIpAddrTable (ip_table, &size, TRUE) == ERROR_SUCCESS) {
    DWORD i;
    for (i = 0; i < ip_table->dwNumEntries; i++) {
      gchar * ipstr;
      PMIB_IPADDRROW ipaddr = &ip_table->table[i];

      if (!(ipaddr->wType & (MIB_IPADDR_DISCONNECTED | MIB_IPADDR_DELETED)) &&
          ipaddr->dwAddr) {
        if (!include_loopback) {
          DWORD type = 0;
          PMIB_IFROW ifr = (PMIB_IFROW)g_malloc0 (sizeof (MIB_IFROW));
          ifr->dwIndex = ipaddr->dwIndex;
          if (GetIfEntry (ifr) == NO_ERROR)
            type = ifr->dwType;
          g_free (ifr);

          if (type == IF_TYPE_SOFTWARE_LOOPBACK)
            continue;
        }

        ipstr = g_strdup_printf ("%d.%d.%d.%d",
            (ipaddr->dwAddr      ) & 0xFF,
            (ipaddr->dwAddr >>  8) & 0xFF,
            (ipaddr->dwAddr >> 16) & 0xFF,
            (ipaddr->dwAddr >> 24) & 0xFF);
        if (ipaddr->dwIndex == pref)
          ret = g_list_prepend (ret, ipstr);
        else
          ret = g_list_append (ret, ipstr);
      }
    }
  }

  g_free(ip_table);

  return ret;
}

/*
 * returns ip address as an utf8 string
 */
static gchar *
win32_get_ip_for_interface (IF_INDEX idx)
{
  ULONG size = 0;
  PMIB_IPADDRTABLE ip_table;
  gchar * ret = NULL;

  GetIpAddrTable (NULL, &size, TRUE);

  if (!size)
    return NULL;

  ip_table = (PMIB_IPADDRTABLE)g_malloc0 (size);

  if (GetIpAddrTable (ip_table, &size, TRUE) == ERROR_SUCCESS) {
    DWORD i;
    for (i = 0; i < ip_table->dwNumEntries; i++) {
      PMIB_IPADDRROW ipaddr = &ip_table->table[i];
      if (ipaddr->dwIndex == idx &&
          !(ipaddr->wType & (MIB_IPADDR_DISCONNECTED | MIB_IPADDR_DELETED))) {
        ret = g_strdup_printf ("%d.%d.%d.%d",
            (ipaddr->dwAddr      ) & 0xFF,
            (ipaddr->dwAddr >>  8) & 0xFF,
            (ipaddr->dwAddr >> 16) & 0xFF,
            (ipaddr->dwAddr >> 24) & 0xFF);
        break;
      }
    }
  }

  g_free (ip_table);
  return ret;
}

gchar * nice_interfaces_get_ip_for_interface (gchar *interface_name)
{
  ULONG size = 0;
  PMIB_IFTABLE if_table;
  gchar * ret = NULL;

  GetIfTable (NULL, &size, TRUE);

  if (!size)
    return NULL;

  if_table = (PMIB_IFTABLE)g_malloc0 (size);

  if (GetIfTable (if_table, &size, TRUE) == ERROR_SUCCESS) {
    DWORD i;
    gchar * tmp_str;
    for (i = 0; i < if_table->dwNumEntries; i++) {
      tmp_str = g_utf16_to_utf8 (
          if_table->table[i].wszName, MAX_INTERFACE_NAME_LEN,
          NULL, NULL, NULL);

524 525
      if (strlen (interface_name) == strlen (tmp_str) &&
          g_ascii_strncasecmp (interface_name, tmp_str, strlen (interface_name)) == 0) {
Youness Alaoui's avatar
Youness Alaoui committed
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
        ret = win32_get_ip_for_interface (if_table->table[i].dwIndex);
        g_free (tmp_str);
        break;
      }

      g_free (tmp_str);
    }
  }

  g_free (if_table);

  return ret;
}


#else /* G_OS_WIN32 */
#error Can not use this method for retreiving ip list from OS other than unix or windows
#endif /* G_OS_WIN32 */
#endif /* G_OS_UNIX */