1 /*
   2  * Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 #include <arpa/inet.h>
  26 #include <errno.h>
  27 #include <net/if.h>
  28 #include <net/if_arp.h>
  29 #include <stdlib.h>
  30 #include <string.h>
  31 #include <sys/ioctl.h>
  32 
  33 #if defined(_AIX)
  34 #include <netinet/in6_var.h>
  35 #include <sys/ndd_var.h>
  36 #include <sys/kinfo.h>
  37 #endif
  38 
  39 #if defined(__solaris__)
  40 #include <stropts.h>
  41 #include <sys/dlpi.h>
  42 #include <sys/sockio.h>
  43 #endif
  44 
  45 #if defined(_ALLBSD_SOURCE)
  46 #include <net/ethernet.h>
  47 #include <net/if_dl.h>
  48 #include <ifaddrs.h>
  49 #endif
  50 
  51 #include "net_util.h"
  52 
  53 #include "java_net_InetAddress.h"
  54 
  55 #if defined(__linux__)
  56     #define _PATH_PROCNET_IFINET6 "/proc/net/if_inet6"
  57 #elif defined(__solaris__)
  58     #ifndef SIOCGLIFHWADDR
  59         #define SIOCGLIFHWADDR _IOWR('i', 192, struct lifreq)
  60     #endif
  61     #define DEV_PREFIX "/dev/"
  62 #endif
  63 
  64 #ifdef LIFNAMSIZ
  65     #define IFNAMESIZE LIFNAMSIZ
  66 #else
  67     #define IFNAMESIZE IFNAMSIZ
  68 #endif
  69 
  70 #define CHECKED_MALLOC3(_pointer, _type, _size) \
  71     do { \
  72         _pointer = (_type)malloc(_size); \
  73         if (_pointer == NULL) { \
  74             JNU_ThrowOutOfMemoryError(env, "Native heap allocation failed"); \
  75             return ifs; /* return untouched list */ \
  76         } \
  77     } while(0)
  78 
  79 typedef struct _netaddr  {
  80     struct sockaddr *addr;
  81     struct sockaddr *brdcast;
  82     short mask;
  83     int family; /* to make searches simple */
  84     struct _netaddr *next;
  85 } netaddr;
  86 
  87 typedef struct _netif {
  88     char *name;
  89     int index;
  90     char virtual;
  91     netaddr *addr;
  92     struct _netif *childs;
  93     struct _netif *next;
  94 } netif;
  95 
  96 /************************************************************************
  97  * NetworkInterface
  98  */
  99 
 100 #include "java_net_NetworkInterface.h"
 101 
 102 /************************************************************************
 103  * NetworkInterface
 104  */
 105 jclass ni_class;
 106 jfieldID ni_nameID;
 107 jfieldID ni_indexID;
 108 jfieldID ni_descID;
 109 jfieldID ni_addrsID;
 110 jfieldID ni_bindsID;
 111 jfieldID ni_virutalID;
 112 jfieldID ni_childsID;
 113 jfieldID ni_parentID;
 114 jfieldID ni_defaultIndexID;
 115 jmethodID ni_ctrID;
 116 
 117 static jclass ni_ibcls;
 118 static jmethodID ni_ibctrID;
 119 static jfieldID ni_ibaddressID;
 120 static jfieldID ni_ib4broadcastID;
 121 static jfieldID ni_ib4maskID;
 122 
 123 /** Private methods declarations **/
 124 static jobject createNetworkInterface(JNIEnv *env, netif *ifs);
 125 static int     getFlags0(JNIEnv *env, jstring  ifname);
 126 
 127 static netif  *enumInterfaces(JNIEnv *env);
 128 static netif  *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs);
 129 static netif  *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs);
 130 
 131 static netif  *addif(JNIEnv *env, int sock, const char *if_name, netif *ifs,
 132                      struct sockaddr *ifr_addrP,
 133                      struct sockaddr *ifr_broadaddrP,
 134                      int family, short prefix);
 135 static void    freeif(netif *ifs);
 136 
 137 static int     openSocket(JNIEnv *env, int proto);
 138 static int     openSocketWithFallback(JNIEnv *env, const char *ifname);
 139 
 140 static short   translateIPv4AddressToPrefix(struct sockaddr_in *addr);
 141 static short   translateIPv6AddressToPrefix(struct sockaddr_in6 *addr);
 142 
 143 static int     getIndex(int sock, const char *ifname);
 144 static int     getFlags(int sock, const char *ifname, int *flags);
 145 static int     getMacAddress(JNIEnv *env, const char *ifname,
 146                              const struct in_addr *addr, unsigned char *buf);
 147 static int     getMTU(JNIEnv *env, int sock, const char *ifname);
 148 
 149 #if defined(__solaris__)
 150 static int     getMacFromDevice(JNIEnv *env, const char *ifname,
 151                                 unsigned char *retbuf);
 152 #endif
 153 
 154 /******************* Java entry points *****************************/
 155 
 156 /*
 157  * Class:     java_net_NetworkInterface
 158  * Method:    init
 159  * Signature: ()V
 160  */
 161 JNIEXPORT void JNICALL Java_java_net_NetworkInterface_init
 162   (JNIEnv *env, jclass cls)
 163 {
 164     ni_class = (*env)->FindClass(env, "java/net/NetworkInterface");
 165     CHECK_NULL(ni_class);
 166     ni_class = (*env)->NewGlobalRef(env, ni_class);
 167     CHECK_NULL(ni_class);
 168     ni_nameID = (*env)->GetFieldID(env, ni_class, "name", "Ljava/lang/String;");
 169     CHECK_NULL(ni_nameID);
 170     ni_indexID = (*env)->GetFieldID(env, ni_class, "index", "I");
 171     CHECK_NULL(ni_indexID);
 172     ni_addrsID = (*env)->GetFieldID(env, ni_class, "addrs",
 173                                     "[Ljava/net/InetAddress;");
 174     CHECK_NULL(ni_addrsID);
 175     ni_bindsID = (*env)->GetFieldID(env, ni_class, "bindings",
 176                                     "[Ljava/net/InterfaceAddress;");
 177     CHECK_NULL(ni_bindsID);
 178     ni_descID = (*env)->GetFieldID(env, ni_class, "displayName",
 179                                    "Ljava/lang/String;");
 180     CHECK_NULL(ni_descID);
 181     ni_virutalID = (*env)->GetFieldID(env, ni_class, "virtual", "Z");
 182     CHECK_NULL(ni_virutalID);
 183     ni_childsID = (*env)->GetFieldID(env, ni_class, "childs",
 184                                      "[Ljava/net/NetworkInterface;");
 185     CHECK_NULL(ni_childsID);
 186     ni_parentID = (*env)->GetFieldID(env, ni_class, "parent",
 187                                      "Ljava/net/NetworkInterface;");
 188     CHECK_NULL(ni_parentID);
 189     ni_ctrID = (*env)->GetMethodID(env, ni_class, "<init>", "()V");
 190     CHECK_NULL(ni_ctrID);
 191     ni_ibcls = (*env)->FindClass(env, "java/net/InterfaceAddress");
 192     CHECK_NULL(ni_ibcls);
 193     ni_ibcls = (*env)->NewGlobalRef(env, ni_ibcls);
 194     CHECK_NULL(ni_ibcls);
 195     ni_ibctrID = (*env)->GetMethodID(env, ni_ibcls, "<init>", "()V");
 196     CHECK_NULL(ni_ibctrID);
 197     ni_ibaddressID = (*env)->GetFieldID(env, ni_ibcls, "address",
 198                                         "Ljava/net/InetAddress;");
 199     CHECK_NULL(ni_ibaddressID);
 200     ni_ib4broadcastID = (*env)->GetFieldID(env, ni_ibcls, "broadcast",
 201                                            "Ljava/net/Inet4Address;");
 202     CHECK_NULL(ni_ib4broadcastID);
 203     ni_ib4maskID = (*env)->GetFieldID(env, ni_ibcls, "maskLength", "S");
 204     CHECK_NULL(ni_ib4maskID);
 205     ni_defaultIndexID = (*env)->GetStaticFieldID(env, ni_class, "defaultIndex",
 206                                                  "I");
 207     CHECK_NULL(ni_defaultIndexID);
 208     initInetAddressIDs(env);
 209 }
 210 
 211 /*
 212  * Class:     java_net_NetworkInterface
 213  * Method:    getByName0
 214  * Signature: (Ljava/lang/String;)Ljava/net/NetworkInterface;
 215  */
 216 JNIEXPORT jobject JNICALL Java_java_net_NetworkInterface_getByName0
 217   (JNIEnv *env, jclass cls, jstring name)
 218 {
 219     netif *ifs, *curr;
 220     jboolean isCopy;
 221     const char* name_utf;
 222     char *colonP;
 223     char searchName[IFNAMESIZE];
 224     jobject obj = NULL;
 225 
 226     if (name != NULL) {
 227         name_utf = (*env)->GetStringUTFChars(env, name, &isCopy);
 228     } else {
 229         JNU_ThrowNullPointerException(env, "network interface name is NULL");
 230         return NULL;
 231     }
 232 
 233     if (name_utf == NULL) {
 234         if (!(*env)->ExceptionCheck(env))
 235             JNU_ThrowOutOfMemoryError(env, NULL);
 236         return NULL;
 237     }
 238 
 239     ifs = enumInterfaces(env);
 240     if (ifs == NULL) {
 241         return NULL;
 242     }
 243 
 244     // search the list of interfaces based on name,
 245     // if it is virtual sub interface search with parent first.
 246     strncpy(searchName, name_utf, IFNAMESIZE);
 247     searchName[IFNAMESIZE - 1] = '\0';
 248     colonP = strchr(searchName, ':');
 249     if (colonP != NULL) {
 250         *colonP = '\0';
 251     }
 252     curr = ifs;
 253     while (curr != NULL) {
 254         if (strcmp(searchName, curr->name) == 0) {
 255             break;
 256         }
 257         curr = curr->next;
 258     }
 259 
 260     // search the child list
 261     if (colonP != NULL && curr != NULL) {
 262         curr = curr->childs;
 263         while (curr != NULL) {
 264             if (strcmp(name_utf, curr->name) == 0) {
 265                 break;
 266             }
 267             curr = curr->next;
 268         }
 269     }
 270 
 271     // if found create a NetworkInterface
 272     if (curr != NULL) {
 273         obj = createNetworkInterface(env, curr);
 274     }
 275 
 276     // release the UTF string and interface list
 277     (*env)->ReleaseStringUTFChars(env, name, name_utf);
 278     freeif(ifs);
 279 
 280     return obj;
 281 }
 282 
 283 /*
 284  * Class:     java_net_NetworkInterface
 285  * Method:    getByIndex0
 286  * Signature: (Ljava/lang/String;)Ljava/net/NetworkInterface;
 287  */
 288 JNIEXPORT jobject JNICALL Java_java_net_NetworkInterface_getByIndex0
 289   (JNIEnv *env, jclass cls, jint index)
 290 {
 291     netif *ifs, *curr;
 292     jobject obj = NULL;
 293 
 294     if (index <= 0) {
 295         return NULL;
 296     }
 297 
 298     ifs = enumInterfaces(env);
 299     if (ifs == NULL) {
 300         return NULL;
 301     }
 302 
 303     // search the list of interfaces based on index
 304     curr = ifs;
 305     while (curr != NULL) {
 306         if (index == curr->index) {
 307             break;
 308         }
 309         curr = curr->next;
 310     }
 311 
 312     // if found create a NetworkInterface
 313     if (curr != NULL) {
 314         obj = createNetworkInterface(env, curr);
 315     }
 316 
 317     // release the interface list
 318     freeif(ifs);
 319 
 320     return obj;
 321 }
 322 
 323 /*
 324  * Class:     java_net_NetworkInterface
 325  * Method:    getByInetAddress0
 326  * Signature: (Ljava/net/InetAddress;)Ljava/net/NetworkInterface;
 327  */
 328 JNIEXPORT jobject JNICALL Java_java_net_NetworkInterface_getByInetAddress0
 329   (JNIEnv *env, jclass cls, jobject iaObj)
 330 {
 331     netif *ifs, *curr;
 332     jobject obj = NULL;
 333     jboolean match = JNI_FALSE;
 334     int family = getInetAddress_family(env, iaObj);
 335     JNU_CHECK_EXCEPTION_RETURN(env, NULL);
 336 
 337     if (family == java_net_InetAddress_IPv4) {
 338         family = AF_INET;
 339     } else if (family == java_net_InetAddress_IPv6) {
 340         family = AF_INET6;
 341     } else {
 342         return NULL; // Invalid family
 343     }
 344     ifs = enumInterfaces(env);
 345     if (ifs == NULL) {
 346         return NULL;
 347     }
 348 
 349     curr = ifs;
 350     while (curr != NULL) {
 351         netaddr *addrP = curr->addr;
 352 
 353         // iterate through each address on the interface
 354         while (addrP != NULL) {
 355 
 356             if (family == addrP->family) {
 357                 if (family == AF_INET) {
 358                     int address1 = htonl(
 359                         ((struct sockaddr_in *)addrP->addr)->sin_addr.s_addr);
 360                     int address2 = getInetAddress_addr(env, iaObj);
 361                     if ((*env)->ExceptionCheck(env)) {
 362                         goto cleanup;
 363                     }
 364                     if (address1 == address2) {
 365                         match = JNI_TRUE;
 366                         break;
 367                     }
 368                 } else if (family == AF_INET6) {
 369                     jbyte *bytes = (jbyte *)&(
 370                         ((struct sockaddr_in6*)addrP->addr)->sin6_addr);
 371                     jbyte caddr[16];
 372                     int i;
 373                     unsigned int scopeid;
 374                     getInet6Address_ipaddress(env, iaObj, (char *)caddr);
 375                     scopeid = (unsigned int)getInet6Address_scopeid(env, iaObj);
 376                     if (scopeid != 0 && scopeid != ((struct sockaddr_in6*)addrP->addr)->sin6_scope_id)
 377                         break;
 378                     i = 0;
 379                     while (i < 16) {
 380                         if (caddr[i] != bytes[i]) {
 381                             break;
 382                         }
 383                         i++;
 384                     }
 385                     if (i >= 16) {
 386                         match = JNI_TRUE;
 387                         break;
 388                     }
 389                 }
 390             }
 391 
 392             if (match) {
 393                 break;
 394             }
 395             addrP = addrP->next;
 396         }
 397 
 398         if (match) {
 399             break;
 400         }
 401         curr = curr->next;
 402     }
 403 
 404     // if found create a NetworkInterface
 405     if (match) {
 406         obj = createNetworkInterface(env, curr);
 407     }
 408 
 409 cleanup:
 410     // release the interface list
 411     freeif(ifs);
 412 
 413     return obj;
 414 }
 415 
 416 /*
 417  * Class:     java_net_NetworkInterface
 418  * Method:    getAll
 419  * Signature: ()[Ljava/net/NetworkInterface;
 420  */
 421 JNIEXPORT jobjectArray JNICALL Java_java_net_NetworkInterface_getAll
 422   (JNIEnv *env, jclass cls)
 423 {
 424     netif *ifs, *curr;
 425     jobjectArray netIFArr;
 426     jint arr_index, ifCount;
 427 
 428     ifs = enumInterfaces(env);
 429     if (ifs == NULL) {
 430         return NULL;
 431     }
 432 
 433     // count the interfaces
 434     ifCount = 0;
 435     curr = ifs;
 436     while (curr != NULL) {
 437         ifCount++;
 438         curr = curr->next;
 439     }
 440 
 441     // allocate a NetworkInterface array
 442     netIFArr = (*env)->NewObjectArray(env, ifCount, cls, NULL);
 443     if (netIFArr == NULL) {
 444         freeif(ifs);
 445         return NULL;
 446     }
 447 
 448     // iterate through the interfaces, create a NetworkInterface instance
 449     // for each array element and populate the object
 450     curr = ifs;
 451     arr_index = 0;
 452     while (curr != NULL) {
 453         jobject netifObj;
 454 
 455         netifObj = createNetworkInterface(env, curr);
 456         if (netifObj == NULL) {
 457             freeif(ifs);
 458             return NULL;
 459         }
 460 
 461         // put the NetworkInterface into the array
 462         (*env)->SetObjectArrayElement(env, netIFArr, arr_index++, netifObj);
 463 
 464         curr = curr->next;
 465     }
 466 
 467     // release the interface list
 468     freeif(ifs);
 469 
 470     return netIFArr;
 471 }
 472 
 473 /*
 474  * Class:     java_net_NetworkInterface
 475  * Method:    isUp0
 476  * Signature: (Ljava/lang/String;I)Z
 477  */
 478 JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_isUp0
 479   (JNIEnv *env, jclass cls, jstring name, jint index)
 480 {
 481     int ret = getFlags0(env, name);
 482     return ((ret & IFF_UP) && (ret & IFF_RUNNING)) ? JNI_TRUE :  JNI_FALSE;
 483 }
 484 
 485 /*
 486  * Class:     java_net_NetworkInterface
 487  * Method:    isP2P0
 488  * Signature: (Ljava/lang/String;I)Z
 489  */
 490 JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_isP2P0
 491   (JNIEnv *env, jclass cls, jstring name, jint index)
 492 {
 493     int ret = getFlags0(env, name);
 494     return (ret & IFF_POINTOPOINT) ? JNI_TRUE :  JNI_FALSE;
 495 }
 496 
 497 /*
 498  * Class:     java_net_NetworkInterface
 499  * Method:    isLoopback0
 500  * Signature: (Ljava/lang/String;I)Z
 501  */
 502 JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_isLoopback0
 503   (JNIEnv *env, jclass cls, jstring name, jint index)
 504 {
 505     int ret = getFlags0(env, name);
 506     return (ret & IFF_LOOPBACK) ? JNI_TRUE :  JNI_FALSE;
 507 }
 508 
 509 /*
 510  * Class:     java_net_NetworkInterface
 511  * Method:    supportsMulticast0
 512  * Signature: (Ljava/lang/String;I)Z
 513  */
 514 JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_supportsMulticast0
 515   (JNIEnv *env, jclass cls, jstring name, jint index)
 516 {
 517     int ret = getFlags0(env, name);
 518     return (ret & IFF_MULTICAST) ? JNI_TRUE :  JNI_FALSE;
 519 }
 520 
 521 /*
 522  * Class:     java_net_NetworkInterface
 523  * Method:    getMacAddr0
 524  * Signature: ([bLjava/lang/String;I)[b
 525  */
 526 JNIEXPORT jbyteArray JNICALL Java_java_net_NetworkInterface_getMacAddr0
 527   (JNIEnv *env, jclass cls, jbyteArray addrArray, jstring name, jint index)
 528 {
 529     jint addr;
 530     jbyte caddr[4];
 531     struct in_addr iaddr;
 532     jbyteArray ret = NULL;
 533     unsigned char mac[16];
 534     int len;
 535     jboolean isCopy;
 536     const char *name_utf;
 537 
 538     if (name != NULL) {
 539         name_utf = (*env)->GetStringUTFChars(env, name, &isCopy);
 540     } else {
 541         JNU_ThrowNullPointerException(env, "network interface name is NULL");
 542         return NULL;
 543     }
 544 
 545     if (name_utf == NULL) {
 546         if (!(*env)->ExceptionCheck(env))
 547             JNU_ThrowOutOfMemoryError(env, NULL);
 548         return NULL;
 549     }
 550 
 551     if (!IS_NULL(addrArray)) {
 552         (*env)->GetByteArrayRegion(env, addrArray, 0, 4, caddr);
 553         addr = ((caddr[0]<<24) & 0xff000000);
 554         addr |= ((caddr[1] <<16) & 0xff0000);
 555         addr |= ((caddr[2] <<8) & 0xff00);
 556         addr |= (caddr[3] & 0xff);
 557         iaddr.s_addr = htonl(addr);
 558         len = getMacAddress(env, name_utf, &iaddr, mac);
 559     } else {
 560         len = getMacAddress(env, name_utf, NULL, mac);
 561     }
 562 
 563     if (len > 0) {
 564         ret = (*env)->NewByteArray(env, len);
 565         if (!IS_NULL(ret)) {
 566             (*env)->SetByteArrayRegion(env, ret, 0, len, (jbyte *)(mac));
 567         }
 568     }
 569 
 570     // release the UTF string and interface list
 571     (*env)->ReleaseStringUTFChars(env, name, name_utf);
 572 
 573     return ret;
 574 }
 575 
 576 /*
 577  * Class:       java_net_NetworkInterface
 578  * Method:      getMTU0
 579  * Signature:   ([bLjava/lang/String;I)I
 580  */
 581 JNIEXPORT jint JNICALL Java_java_net_NetworkInterface_getMTU0
 582   (JNIEnv *env, jclass cls, jstring name, jint index)
 583 {
 584     jboolean isCopy;
 585     int sock, ret = -1;
 586     const char* name_utf = NULL;
 587 
 588     if (name != NULL) {
 589         name_utf = (*env)->GetStringUTFChars(env, name, &isCopy);
 590     } else {
 591         JNU_ThrowNullPointerException(env, "network interface name is NULL");
 592         return ret;
 593     }
 594 
 595     if (name_utf == NULL) {
 596         if (!(*env)->ExceptionCheck(env))
 597             JNU_ThrowOutOfMemoryError(env, NULL);
 598         return ret;
 599     }
 600 
 601     if ((sock = openSocketWithFallback(env, name_utf)) < 0) {
 602         (*env)->ReleaseStringUTFChars(env, name, name_utf);
 603         return JNI_FALSE;
 604     }
 605 
 606     ret = getMTU(env, sock, name_utf);
 607 
 608     (*env)->ReleaseStringUTFChars(env, name, name_utf);
 609 
 610     close(sock);
 611     return ret;
 612 }
 613 
 614 /*** Private methods definitions ****/
 615 
 616 static int getFlags0(JNIEnv *env, jstring name) {
 617     jboolean isCopy;
 618     int ret, sock, flags = 0;
 619     const char *name_utf;
 620 
 621     if (name != NULL) {
 622         name_utf = (*env)->GetStringUTFChars(env, name, &isCopy);
 623     } else {
 624         JNU_ThrowNullPointerException(env, "network interface name is NULL");
 625         return -1;
 626     }
 627 
 628     if (name_utf == NULL) {
 629         if (!(*env)->ExceptionCheck(env))
 630             JNU_ThrowOutOfMemoryError(env, NULL);
 631         return -1;
 632     }
 633     if ((sock = openSocketWithFallback(env, name_utf)) < 0) {
 634         (*env)->ReleaseStringUTFChars(env, name, name_utf);
 635         return -1;
 636     }
 637 
 638     ret = getFlags(sock, name_utf, &flags);
 639 
 640     close(sock);
 641     (*env)->ReleaseStringUTFChars(env, name, name_utf);
 642 
 643     if (ret < 0) {
 644         JNU_ThrowByNameWithMessageAndLastError
 645             (env, JNU_JAVANETPKG "SocketException", "getFlags() failed");
 646         return -1;
 647     }
 648 
 649     return flags;
 650 }
 651 
 652 /*
 653  * Creates a NetworkInterface object, populates the name, the index, and
 654  * populates the InetAddress array based on the IP addresses for this
 655  * interface.
 656  */
 657 static jobject createNetworkInterface(JNIEnv *env, netif *ifs) {
 658     jobject netifObj;
 659     jobject name;
 660     jobjectArray addrArr;
 661     jobjectArray bindArr;
 662     jobjectArray childArr;
 663     netaddr *addrs;
 664     jint addr_index, addr_count, bind_index;
 665     jint child_count, child_index;
 666     netaddr *addrP;
 667     netif *childP;
 668     jobject tmp;
 669 
 670     // create a NetworkInterface object and populate it
 671     netifObj = (*env)->NewObject(env, ni_class, ni_ctrID);
 672     CHECK_NULL_RETURN(netifObj, NULL);
 673     name = (*env)->NewStringUTF(env, ifs->name);
 674     CHECK_NULL_RETURN(name, NULL);
 675     (*env)->SetObjectField(env, netifObj, ni_nameID, name);
 676     (*env)->SetObjectField(env, netifObj, ni_descID, name);
 677     (*env)->SetIntField(env, netifObj, ni_indexID, ifs->index);
 678     (*env)->SetBooleanField(env, netifObj, ni_virutalID,
 679                             ifs->virtual ? JNI_TRUE : JNI_FALSE);
 680 
 681     // count the number of addresses on this interface
 682     addr_count = 0;
 683     addrP = ifs->addr;
 684     while (addrP != NULL) {
 685         addr_count++;
 686         addrP = addrP->next;
 687     }
 688 
 689     // create the array of InetAddresses
 690     addrArr = (*env)->NewObjectArray(env, addr_count, ia_class, NULL);
 691     if (addrArr == NULL) {
 692         return NULL;
 693     }
 694 
 695     bindArr = (*env)->NewObjectArray(env, addr_count, ni_ibcls, NULL);
 696     if (bindArr == NULL) {
 697        return NULL;
 698     }
 699     addrP = ifs->addr;
 700     addr_index = 0;
 701     bind_index = 0;
 702     while (addrP != NULL) {
 703         jobject iaObj = NULL;
 704         jobject ibObj = NULL;
 705 
 706         if (addrP->family == AF_INET) {
 707             iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
 708             if (iaObj) {
 709                 setInetAddress_addr(env, iaObj, htonl(
 710                     ((struct sockaddr_in*)addrP->addr)->sin_addr.s_addr));
 711                 JNU_CHECK_EXCEPTION_RETURN(env, NULL);
 712             } else {
 713                 return NULL;
 714             }
 715             ibObj = (*env)->NewObject(env, ni_ibcls, ni_ibctrID);
 716             if (ibObj) {
 717                 (*env)->SetObjectField(env, ibObj, ni_ibaddressID, iaObj);
 718                 if (addrP->brdcast) {
 719                     jobject ia2Obj = NULL;
 720                     ia2Obj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
 721                     if (ia2Obj) {
 722                         setInetAddress_addr(env, ia2Obj, htonl(
 723                             ((struct sockaddr_in*)addrP->brdcast)->sin_addr.s_addr));
 724                         JNU_CHECK_EXCEPTION_RETURN(env, NULL);
 725                         (*env)->SetObjectField(env, ibObj, ni_ib4broadcastID, ia2Obj);
 726                     } else {
 727                         return NULL;
 728                     }
 729                 }
 730                 (*env)->SetShortField(env, ibObj, ni_ib4maskID, addrP->mask);
 731                 (*env)->SetObjectArrayElement(env, bindArr, bind_index++, ibObj);
 732             } else {
 733                 return NULL;
 734             }
 735         }
 736         if (addrP->family == AF_INET6) {
 737             int scope=0;
 738             iaObj = (*env)->NewObject(env, ia6_class, ia6_ctrID);
 739             if (iaObj) {
 740                 jboolean ret = setInet6Address_ipaddress(env, iaObj,
 741                     (char *)&(((struct sockaddr_in6*)addrP->addr)->sin6_addr));
 742                 if (ret == JNI_FALSE) {
 743                     return NULL;
 744                 }
 745 
 746                 scope = ((struct sockaddr_in6*)addrP->addr)->sin6_scope_id;
 747 
 748                 if (scope != 0) { /* zero is default value, no need to set */
 749                     setInet6Address_scopeid(env, iaObj, scope);
 750                     setInet6Address_scopeifname(env, iaObj, netifObj);
 751                 }
 752             } else {
 753                 return NULL;
 754             }
 755             ibObj = (*env)->NewObject(env, ni_ibcls, ni_ibctrID);
 756             if (ibObj) {
 757                 (*env)->SetObjectField(env, ibObj, ni_ibaddressID, iaObj);
 758                 (*env)->SetShortField(env, ibObj, ni_ib4maskID, addrP->mask);
 759                 (*env)->SetObjectArrayElement(env, bindArr, bind_index++, ibObj);
 760             } else {
 761                 return NULL;
 762             }
 763         }
 764 
 765         (*env)->SetObjectArrayElement(env, addrArr, addr_index++, iaObj);
 766         addrP = addrP->next;
 767     }
 768 
 769     // see if there is any virtual interface attached to this one.
 770     child_count = 0;
 771     childP = ifs->childs;
 772     while (childP) {
 773         child_count++;
 774         childP = childP->next;
 775     }
 776 
 777     childArr = (*env)->NewObjectArray(env, child_count, ni_class, NULL);
 778     if (childArr == NULL) {
 779         return NULL;
 780     }
 781 
 782     // create the NetworkInterface instances for the sub-interfaces as well
 783     child_index = 0;
 784     childP = ifs->childs;
 785     while(childP) {
 786         tmp = createNetworkInterface(env, childP);
 787         if (tmp == NULL) {
 788             return NULL;
 789         }
 790         (*env)->SetObjectField(env, tmp, ni_parentID, netifObj);
 791         (*env)->SetObjectArrayElement(env, childArr, child_index++, tmp);
 792         childP = childP->next;
 793     }
 794     (*env)->SetObjectField(env, netifObj, ni_addrsID, addrArr);
 795     (*env)->SetObjectField(env, netifObj, ni_bindsID, bindArr);
 796     (*env)->SetObjectField(env, netifObj, ni_childsID, childArr);
 797 
 798     // return the NetworkInterface
 799     return netifObj;
 800 }
 801 
 802 /*
 803  * Enumerates all interfaces
 804  */
 805 static netif *enumInterfaces(JNIEnv *env) {
 806     netif *ifs = NULL;
 807     int sock;
 808 
 809     sock = openSocket(env, AF_INET);
 810     if (sock < 0 && (*env)->ExceptionOccurred(env)) {
 811         return NULL;
 812     }
 813 
 814     // enumerate IPv4 addresses
 815     if (sock >= 0) {
 816         ifs = enumIPv4Interfaces(env, sock, ifs);
 817         close(sock);
 818 
 819         if ((*env)->ExceptionOccurred(env)) {
 820             freeif(ifs);
 821             return NULL;
 822         }
 823     }
 824 
 825     // If IPv6 is available then enumerate IPv6 addresses.
 826     // User can disable ipv6 explicitly by -Djava.net.preferIPv4Stack=true,
 827     // so we have to call ipv6_available()
 828     if (ipv6_available()) {
 829         sock = openSocket(env, AF_INET6);
 830         if (sock < 0) {
 831             freeif(ifs);
 832             return NULL;
 833         }
 834 
 835         ifs = enumIPv6Interfaces(env, sock, ifs);
 836         close(sock);
 837 
 838         if ((*env)->ExceptionOccurred(env)) {
 839             freeif(ifs);
 840             return NULL;
 841         }
 842     }
 843 
 844     return ifs;
 845 }
 846 
 847 /*
 848  * Frees an interface list (including any attached addresses).
 849  */
 850 static void freeif(netif *ifs) {
 851     netif *currif = ifs;
 852     netif *child = NULL;
 853 
 854     while (currif != NULL) {
 855         netaddr *addrP = currif->addr;
 856         while (addrP != NULL) {
 857             netaddr *next = addrP->next;
 858             free(addrP);
 859             addrP = next;
 860         }
 861 
 862         // don't forget to free the sub-interfaces
 863         if (currif->childs != NULL) {
 864             freeif(currif->childs);
 865         }
 866 
 867         ifs = currif->next;
 868         free(currif);
 869         currif = ifs;
 870     }
 871 }
 872 
 873 static netif *addif(JNIEnv *env, int sock, const char *if_name, netif *ifs,
 874                     struct sockaddr *ifr_addrP,
 875                     struct sockaddr *ifr_broadaddrP,
 876                     int family, short prefix)
 877 {
 878     netif *currif = ifs, *parent;
 879     netaddr *addrP;
 880     char name[IFNAMESIZE], vname[IFNAMESIZE];
 881     char *name_colonP;
 882     int isVirtual = 0;
 883     int addr_size;
 884 
 885     // If the interface name is a logical interface then we remove the unit
 886     // number so that we have the physical interface (eg: hme0:1 -> hme0).
 887     // NetworkInterface currently doesn't have any concept of physical vs.
 888     // logical interfaces.
 889     strncpy(name, if_name, IFNAMESIZE);
 890     name[IFNAMESIZE - 1] = '\0';
 891     *vname = 0;
 892 
 893     // Create and populate the netaddr node. If allocation fails
 894     // return an un-updated list.
 895 
 896     // Allocate for addr and brdcast at once
 897 
 898     addr_size = (family == AF_INET) ? sizeof(struct sockaddr_in)
 899                                     : sizeof(struct sockaddr_in6);
 900 
 901     CHECKED_MALLOC3(addrP, netaddr *, sizeof(netaddr) + 2 * addr_size);
 902     addrP->addr = (struct sockaddr *)((char *)addrP + sizeof(netaddr));
 903     memcpy(addrP->addr, ifr_addrP, addr_size);
 904 
 905     addrP->family = family;
 906     addrP->mask = prefix;
 907     addrP->next = 0;
 908 
 909     // for IPv4 add broadcast address
 910     if (family == AF_INET && ifr_broadaddrP != NULL) {
 911         addrP->brdcast = (struct sockaddr *)
 912                              ((char *)addrP + sizeof(netaddr) + addr_size);
 913         memcpy(addrP->brdcast, ifr_broadaddrP, addr_size);
 914     } else {
 915         addrP->brdcast = NULL;
 916     }
 917 
 918     // Deal with virtual interface with colon notation e.g. eth0:1
 919     name_colonP = strchr(name, ':');
 920     if (name_colonP != NULL) {
 921         int flags = 0;
 922         // This is a virtual interface. If we are able to access the parent
 923         // we need to create a new entry if it doesn't exist yet *and* update
 924         // the 'parent' interface with the new records.
 925         *name_colonP = 0;
 926         if (getFlags(sock, name, &flags) < 0 || flags < 0) {
 927             // failed to access parent interface do not create parent.
 928             // We are a virtual interface with no parent.
 929             isVirtual = 1;
 930             *name_colonP = ':';
 931         } else {
 932             // Got access to parent, so create it if necessary.
 933             // Save original name to vname and truncate name by ':'
 934             memcpy(vname, name, sizeof(vname));
 935             vname[name_colonP - name] = ':';
 936         }
 937     }
 938 
 939     // Check if this is a "new" interface. Use the interface name for
 940     // matching because index isn't supported on Solaris 2.6 & 7.
 941     while (currif != NULL) {
 942         if (strcmp(name, currif->name) == 0) {
 943             break;
 944         }
 945         currif = currif->next;
 946     }
 947 
 948     // If "new" then create a netif structure and insert it into the list.
 949     if (currif == NULL) {
 950          CHECKED_MALLOC3(currif, netif *, sizeof(netif) + IFNAMESIZE);
 951          currif->name = (char *)currif + sizeof(netif);
 952          strncpy(currif->name, name, IFNAMESIZE);
 953          currif->name[IFNAMESIZE - 1] = '\0';
 954          currif->index = getIndex(sock, name);
 955          currif->addr = NULL;
 956          currif->childs = NULL;
 957          currif->virtual = isVirtual;
 958          currif->next = ifs;
 959          ifs = currif;
 960     }
 961 
 962     // Finally insert the address on the interface
 963     addrP->next = currif->addr;
 964     currif->addr = addrP;
 965 
 966     parent = currif;
 967 
 968     // Deal with the virtual interface now.
 969     if (vname[0]) {
 970         netaddr *tmpaddr;
 971 
 972         currif = parent->childs;
 973 
 974         while (currif != NULL) {
 975             if (strcmp(vname, currif->name) == 0) {
 976                 break;
 977             }
 978             currif = currif->next;
 979         }
 980 
 981         if (currif == NULL) {
 982             CHECKED_MALLOC3(currif, netif *, sizeof(netif) + IFNAMESIZE);
 983             currif->name = (char *)currif + sizeof(netif);
 984             strncpy(currif->name, vname, IFNAMESIZE);
 985             currif->name[IFNAMESIZE - 1] = '\0';
 986             currif->index = getIndex(sock, vname);
 987             currif->addr = NULL; // Need to duplicate the addr entry?
 988             currif->virtual = 1;
 989             currif->childs = NULL;
 990             currif->next = parent->childs;
 991             parent->childs = currif;
 992         }
 993 
 994         CHECKED_MALLOC3(tmpaddr, netaddr *, sizeof(netaddr) + 2 * addr_size);
 995         memcpy(tmpaddr, addrP, sizeof(netaddr));
 996         if (addrP->addr != NULL) {
 997             tmpaddr->addr = (struct sockaddr *)
 998                 ((char*)tmpaddr + sizeof(netaddr));
 999             memcpy(tmpaddr->addr, addrP->addr, addr_size);
1000         }
1001 
1002         if (addrP->brdcast != NULL) {
1003             tmpaddr->brdcast = (struct sockaddr *)
1004                 ((char *)tmpaddr + sizeof(netaddr) + addr_size);
1005             memcpy(tmpaddr->brdcast, addrP->brdcast, addr_size);
1006         }
1007 
1008         tmpaddr->next = currif->addr;
1009         currif->addr = tmpaddr;
1010     }
1011 
1012     return ifs;
1013 }
1014 
1015 /*
1016  * Determines the prefix value for an AF_INET subnet address.
1017  */
1018 static short translateIPv4AddressToPrefix(struct sockaddr_in *addr) {
1019     short prefix = 0;
1020     unsigned int mask;
1021     if (addr == NULL) {
1022         return 0;
1023     }
1024     mask = ntohl(addr->sin_addr.s_addr);
1025     while (mask) {
1026         mask <<= 1;
1027         prefix++;
1028     }
1029     return prefix;
1030 }
1031 
1032 /*
1033  * Determines the prefix value for an AF_INET6 subnet address.
1034  */
1035 static short translateIPv6AddressToPrefix(struct sockaddr_in6 *addr) {
1036     short prefix = 0;
1037     u_char *addrBytes;
1038     if (addr == NULL) {
1039         return 0;
1040     }
1041     addrBytes = (u_char *)&(addr->sin6_addr);
1042     unsigned int byte, bit;
1043 
1044     for (byte = 0; byte < sizeof(struct in6_addr); byte++, prefix += 8) {
1045         if (addrBytes[byte] != 0xff) {
1046             break;
1047         }
1048     }
1049     if (byte != sizeof(struct in6_addr)) {
1050         for (bit = 7; bit != 0; bit--, prefix++) {
1051             if (!(addrBytes[byte] & (1 << bit))) {
1052                 break;
1053             }
1054         }
1055         for (; bit != 0; bit--) {
1056             if (addrBytes[byte] & (1 << bit)) {
1057                 prefix = 0;
1058                 break;
1059             }
1060         }
1061         if (prefix > 0) {
1062             byte++;
1063             for (; byte < sizeof(struct in6_addr); byte++) {
1064                 if (addrBytes[byte]) {
1065                     prefix = 0;
1066                 }
1067             }
1068         }
1069     }
1070 
1071     return prefix;
1072 }
1073 
1074 /*
1075  * Opens a socket for further ioct calls. proto is one of AF_INET or AF_INET6.
1076  */
1077 static int openSocket(JNIEnv *env, int proto) {
1078     int sock;
1079 
1080     if ((sock = socket(proto, SOCK_DGRAM, 0)) < 0) {
1081         // If we lack support for this address family or protocol,
1082         // don't throw an exception.
1083         if (errno != EPROTONOSUPPORT && errno != EAFNOSUPPORT) {
1084             JNU_ThrowByNameWithMessageAndLastError
1085                 (env, JNU_JAVANETPKG "SocketException", "Socket creation failed");
1086         }
1087         return -1;
1088     }
1089 
1090     return sock;
1091 }
1092 
1093 /** Linux **/
1094 #if defined(__linux__)
1095 
1096 /*
1097  * Opens a socket for further ioctl calls. Tries AF_INET socket first and
1098  * if it fails return AF_INET6 socket.
1099  */
1100 static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
1101     int sock;
1102 
1103     if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
1104         if (errno == EPROTONOSUPPORT || errno == EAFNOSUPPORT) {
1105             if ((sock = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
1106                 JNU_ThrowByNameWithMessageAndLastError
1107                     (env, JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
1108                 return -1;
1109             }
1110         } else { // errno is not NOSUPPORT
1111             JNU_ThrowByNameWithMessageAndLastError
1112                 (env, JNU_JAVANETPKG "SocketException", "IPV4 Socket creation failed");
1113             return -1;
1114         }
1115     }
1116 
1117     // Linux starting from 2.6.? kernel allows ioctl call with either IPv4 or
1118     // IPv6 socket regardless of type of address of an interface.
1119     return sock;
1120 }
1121 
1122 /*
1123  * Enumerates and returns all IPv4 interfaces on Linux.
1124  */
1125 static netif *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs) {
1126     struct ifconf ifc;
1127     struct ifreq *ifreqP;
1128     char *buf = NULL;
1129     unsigned i;
1130 
1131     // do a dummy SIOCGIFCONF to determine the buffer size
1132     // SIOCGIFCOUNT doesn't work
1133     ifc.ifc_buf = NULL;
1134     if (ioctl(sock, SIOCGIFCONF, (char *)&ifc) < 0) {
1135         JNU_ThrowByNameWithMessageAndLastError
1136             (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFCONF) failed");
1137         return ifs;
1138     }
1139 
1140     // call SIOCGIFCONF to enumerate the interfaces
1141     CHECKED_MALLOC3(buf, char *, ifc.ifc_len);
1142     ifc.ifc_buf = buf;
1143     if (ioctl(sock, SIOCGIFCONF, (char *)&ifc) < 0) {
1144         JNU_ThrowByNameWithMessageAndLastError
1145             (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFCONF) failed");
1146         free(buf);
1147         return ifs;
1148     }
1149 
1150     // iterate through each interface
1151     ifreqP = ifc.ifc_req;
1152     for (i = 0; i < ifc.ifc_len / sizeof(struct ifreq); i++, ifreqP++) {
1153         struct sockaddr addr, broadaddr, *broadaddrP = NULL;
1154         short prefix = 0;
1155 
1156         // ignore non IPv4 addresses
1157         if (ifreqP->ifr_addr.sa_family != AF_INET) {
1158             continue;
1159         }
1160 
1161         // save socket address
1162         memcpy(&addr, &(ifreqP->ifr_addr), sizeof(struct sockaddr));
1163 
1164         // determine broadcast address, if applicable
1165         if ((ioctl(sock, SIOCGIFFLAGS, ifreqP) == 0) &&
1166             ifreqP->ifr_flags & IFF_BROADCAST) {
1167 
1168             // restore socket address to ifreqP
1169             memcpy(&(ifreqP->ifr_addr), &addr, sizeof(struct sockaddr));
1170 
1171             if (ioctl(sock, SIOCGIFBRDADDR, ifreqP) == 0) {
1172                 memcpy(&broadaddr, &(ifreqP->ifr_broadaddr),
1173                        sizeof(struct sockaddr));
1174                 broadaddrP = &broadaddr;
1175             }
1176         }
1177 
1178         // restore socket address to ifreqP
1179         memcpy(&(ifreqP->ifr_addr), &addr, sizeof(struct sockaddr));
1180 
1181         // determine netmask
1182         if (ioctl(sock, SIOCGIFNETMASK, ifreqP) == 0) {
1183             prefix = translateIPv4AddressToPrefix(
1184                          (struct sockaddr_in *)&(ifreqP->ifr_netmask));
1185         }
1186 
1187         // add interface to the list
1188         ifs = addif(env, sock, ifreqP->ifr_name, ifs,
1189                     &addr, broadaddrP, AF_INET, prefix);
1190 
1191         // in case of exception, free interface list and buffer and return NULL
1192         if ((*env)->ExceptionOccurred(env)) {
1193             free(buf);
1194             freeif(ifs);
1195             return NULL;
1196         }
1197     }
1198 
1199     // free buffer
1200     free(buf);
1201     return ifs;
1202 }
1203 
1204 /*
1205  * Enumerates and returns all IPv6 interfaces on Linux.
1206  */
1207 static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
1208     FILE *f;
1209     char devname[21], addr6p[8][5];
1210     int prefix, scope, dad_status, if_idx;
1211 
1212     if ((f = fopen(_PATH_PROCNET_IFINET6, "r")) != NULL) {
1213         while (fscanf(f, "%4s%4s%4s%4s%4s%4s%4s%4s %08x %02x %02x %02x %20s\n",
1214                       addr6p[0], addr6p[1], addr6p[2], addr6p[3],
1215                       addr6p[4], addr6p[5], addr6p[6], addr6p[7],
1216                       &if_idx, &prefix, &scope, &dad_status, devname) != EOF) {
1217 
1218             char addr6[40];
1219             struct sockaddr_in6 addr;
1220 
1221             sprintf(addr6, "%s:%s:%s:%s:%s:%s:%s:%s",
1222                     addr6p[0], addr6p[1], addr6p[2], addr6p[3],
1223                     addr6p[4], addr6p[5], addr6p[6], addr6p[7]);
1224 
1225             memset(&addr, 0, sizeof(struct sockaddr_in6));
1226             inet_pton(AF_INET6, addr6, (void*)addr.sin6_addr.s6_addr);
1227 
1228             // set scope ID to interface index
1229             addr.sin6_scope_id = if_idx;
1230 
1231             // add interface to the list
1232             ifs = addif(env, sock, devname, ifs, (struct sockaddr *)&addr,
1233                         NULL, AF_INET6, (short)prefix);
1234 
1235             // if an exception occurred then return the list as is
1236             if ((*env)->ExceptionOccurred(env)) {
1237                 break;
1238             }
1239        }
1240        fclose(f);
1241     }
1242     return ifs;
1243 }
1244 
1245 /*
1246  * Try to get the interface index.
1247  */
1248 static int getIndex(int sock, const char *name) {
1249     struct ifreq if2;
1250     memset((char *)&if2, 0, sizeof(if2));
1251     strncpy(if2.ifr_name, name, sizeof(if2.ifr_name) - 1);
1252 
1253     if (ioctl(sock, SIOCGIFINDEX, (char *)&if2) < 0) {
1254         return -1;
1255     }
1256 
1257     return if2.ifr_ifindex;
1258 }
1259 
1260 /*
1261  * Gets the Hardware address (usually MAC address) for the named interface.
1262  * On return puts the data in buf, and returns the length, in byte, of the
1263  * MAC address. Returns -1 if there is no hardware address on that interface.
1264  */
1265 static int getMacAddress
1266   (JNIEnv *env, const char *ifname, const struct in_addr *addr,
1267    unsigned char *buf)
1268 {
1269     struct ifreq ifr;
1270     int i, sock;
1271 
1272     if ((sock = openSocketWithFallback(env, ifname)) < 0) {
1273         return -1;
1274     }
1275 
1276     memset((char *)&ifr, 0, sizeof(ifr));
1277     strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name) - 1);
1278     if (ioctl(sock, SIOCGIFHWADDR, &ifr) < 0) {
1279         JNU_ThrowByNameWithMessageAndLastError
1280             (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFHWADDR) failed");
1281         close(sock);
1282         return -1;
1283     }
1284 
1285     close(sock);
1286     memcpy(buf, &ifr.ifr_hwaddr.sa_data, IFHWADDRLEN);
1287 
1288     // all bytes to 0 means no hardware address
1289     for (i = 0; i < IFHWADDRLEN; i++) {
1290         if (buf[i] != 0)
1291             return IFHWADDRLEN;
1292     }
1293 
1294     return -1;
1295 }
1296 
1297 static int getMTU(JNIEnv *env, int sock, const char *ifname) {
1298     struct ifreq if2;
1299     memset((char *)&if2, 0, sizeof(if2));
1300     strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
1301 
1302     if (ioctl(sock, SIOCGIFMTU, (char *)&if2) < 0) {
1303         JNU_ThrowByNameWithMessageAndLastError
1304             (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFMTU) failed");
1305         return -1;
1306     }
1307 
1308     return if2.ifr_mtu;
1309 }
1310 
1311 static int getFlags(int sock, const char *ifname, int *flags) {
1312     struct ifreq if2;
1313     memset((char *)&if2, 0, sizeof(if2));
1314     strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
1315 
1316     if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) < 0) {
1317         return -1;
1318     }
1319 
1320     if (sizeof(if2.ifr_flags) == sizeof(short)) {
1321         *flags = (if2.ifr_flags & 0xffff);
1322     } else {
1323         *flags = if2.ifr_flags;
1324     }
1325     return 0;
1326 }
1327 
1328 #endif /* __linux__ */
1329 
1330 /** AIX **/
1331 #if defined(_AIX)
1332 
1333 /*
1334  * Opens a socket for further ioctl calls. Tries AF_INET socket first and
1335  * if it fails return AF_INET6 socket.
1336  */
1337 static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
1338     int sock;
1339 
1340     if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
1341         if (errno == EPROTONOSUPPORT || errno == EAFNOSUPPORT) {
1342             if ((sock = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
1343                 JNU_ThrowByNameWithMessageAndLastError
1344                     (env, JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
1345                 return -1;
1346             }
1347         } else { // errno is not NOSUPPORT
1348             JNU_ThrowByNameWithMessageAndLastError
1349                 (env, JNU_JAVANETPKG "SocketException", "IPV4 Socket creation failed");
1350             return -1;
1351         }
1352     }
1353 
1354     return sock;
1355 }
1356 
1357 /*
1358  * Enumerates and returns all IPv4 interfaces on AIX.
1359  */
1360 static netif *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs) {
1361     struct ifconf ifc;
1362     struct ifreq *ifreqP;
1363     char *buf = NULL;
1364     unsigned i;
1365 
1366     // call SIOCGSIZIFCONF to get the size of SIOCGIFCONF buffer
1367     if (ioctl(sock, SIOCGSIZIFCONF, &(ifc.ifc_len)) < 0) {
1368         JNU_ThrowByNameWithMessageAndLastError
1369             (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGSIZIFCONF) failed");
1370         return ifs;
1371     }
1372 
1373     // call CSIOCGIFCONF instead of SIOCGIFCONF where interface
1374     // records will always have sizeof(struct ifreq) length.
1375     // Be aware that only IPv4 data is complete this way.
1376     CHECKED_MALLOC3(buf, char *, ifc.ifc_len);
1377     ifc.ifc_buf = buf;
1378     if (ioctl(sock, CSIOCGIFCONF, (char *)&ifc) < 0) {
1379         JNU_ThrowByNameWithMessageAndLastError
1380             (env, JNU_JAVANETPKG "SocketException", "ioctl(CSIOCGIFCONF) failed");
1381         free(buf);
1382         return ifs;
1383     }
1384 
1385     // iterate through each interface
1386     ifreqP = ifc.ifc_req;
1387     for (i = 0; i < ifc.ifc_len / sizeof(struct ifreq); i++, ifreqP++) {
1388         struct sockaddr addr, broadaddr, *broadaddrP = NULL;
1389         short prefix = 0;
1390 
1391         // ignore non IPv4 addresses
1392         if (ifreqP->ifr_addr.sa_family != AF_INET) {
1393             continue;
1394         }
1395 
1396         // save socket address
1397         memcpy(&addr, &(ifreqP->ifr_addr), sizeof(struct sockaddr));
1398 
1399         // determine broadcast address, if applicable
1400         if ((ioctl(sock, SIOCGIFFLAGS, ifreqP) == 0) &&
1401             ifreqP->ifr_flags & IFF_BROADCAST) {
1402 
1403             // restore socket address to ifreqP
1404             memcpy(&(ifreqP->ifr_addr), &addr, sizeof(struct sockaddr));
1405 
1406             if (ioctl(sock, SIOCGIFBRDADDR, ifreqP) == 0) {
1407                 memcpy(&broadaddr, &(ifreqP->ifr_broadaddr),
1408                        sizeof(struct sockaddr));
1409                 broadaddrP = &broadaddr;
1410             }
1411         }
1412 
1413         // restore socket address to ifreqP
1414         memcpy(&(ifreqP->ifr_addr), &addr, sizeof(struct sockaddr));
1415 
1416         // determine netmask
1417         if (ioctl(sock, SIOCGIFNETMASK, ifreqP) == 0) {
1418             prefix = translateIPv4AddressToPrefix(
1419                          (struct sockaddr_in *)&(ifreqP->ifr_addr));
1420         }
1421 
1422         // add interface to the list
1423         ifs = addif(env, sock, ifreqP->ifr_name, ifs,
1424                     &addr, broadaddrP, AF_INET, prefix);
1425 
1426         // in case of exception, free interface list and buffer and return NULL
1427         if ((*env)->ExceptionOccurred(env)) {
1428             free(buf);
1429             freeif(ifs);
1430             return NULL;
1431         }
1432     }
1433 
1434     // free buffer
1435     free(buf);
1436     return ifs;
1437 }
1438 
1439 /*
1440  * Enumerates and returns all IPv6 interfaces on AIX.
1441  */
1442 static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
1443     struct ifconf ifc;
1444     struct ifreq *ifreqP;
1445     char *buf, *cp, *cplimit;
1446 
1447     // call SIOCGSIZIFCONF to get size for SIOCGIFCONF buffer
1448     if (ioctl(sock, SIOCGSIZIFCONF, &(ifc.ifc_len)) < 0) {
1449         JNU_ThrowByNameWithMessageAndLastError
1450             (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGSIZIFCONF) failed");
1451         return ifs;
1452     }
1453 
1454     // call SIOCGIFCONF to enumerate the interfaces
1455     CHECKED_MALLOC3(buf, char *, ifc.ifc_len);
1456     ifc.ifc_buf = buf;
1457     if (ioctl(sock, SIOCGIFCONF, (char *)&ifc) < 0) {
1458         JNU_ThrowByNameWithMessageAndLastError
1459             (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFCONF) failed");
1460         free(buf);
1461         return ifs;
1462     }
1463 
1464     // iterate through each interface
1465     ifreqP = ifc.ifc_req;
1466     cp = (char *)ifc.ifc_req;
1467     cplimit = cp + ifc.ifc_len;
1468 
1469     for (; cp < cplimit;
1470          cp += (sizeof(ifreqP->ifr_name) +
1471                 MAX((ifreqP->ifr_addr).sa_len, sizeof(ifreqP->ifr_addr))))
1472     {
1473         ifreqP = (struct ifreq *)cp;
1474         short prefix = 0;
1475 
1476         // ignore non IPv6 addresses
1477         if (ifreqP->ifr_addr.sa_family != AF_INET6) {
1478             continue;
1479         }
1480 
1481         // determine netmask
1482         struct in6_ifreq if6;
1483         memset((char *)&if6, 0, sizeof(if6));
1484         strncpy(if6.ifr_name, ifreqP->ifr_name, sizeof(if6.ifr_name) - 1);
1485         memcpy(&(if6.ifr_Addr), &(ifreqP->ifr_addr),
1486                sizeof(struct sockaddr_in6));
1487         if (ioctl(sock, SIOCGIFNETMASK6, (char *)&if6) >= 0) {
1488             prefix = translateIPv6AddressToPrefix(&(if6.ifr_Addr));
1489         }
1490 
1491         // set scope ID to interface index
1492         ((struct sockaddr_in6 *)&(ifreqP->ifr_addr))->sin6_scope_id =
1493             getIndex(sock, ifreqP->ifr_name);
1494 
1495         // add interface to the list
1496         ifs = addif(env, sock, ifreqP->ifr_name, ifs,
1497                     (struct sockaddr *)&(ifreqP->ifr_addr),
1498                     NULL, AF_INET6, prefix);
1499 
1500         // if an exception occurred then free the list
1501         if ((*env)->ExceptionOccurred(env)) {
1502             free(buf);
1503             freeif(ifs);
1504             return NULL;
1505         }
1506     }
1507 
1508     // free buffer
1509     free(buf);
1510     return ifs;
1511 }
1512 
1513 /*
1514  * Try to get the interface index.
1515  */
1516 static int getIndex(int sock, const char *name) {
1517     int index = if_nametoindex(name);
1518     return (index == 0) ? -1 : index;
1519 }
1520 
1521 /*
1522  * Gets the Hardware address (usually MAC address) for the named interface.
1523  * On return puts the data in buf, and returns the length, in byte, of the
1524  * MAC address. Returns -1 if there is no hardware address on that interface.
1525  */
1526 static int getMacAddress
1527   (JNIEnv *env, const char *ifname, const struct in_addr *addr,
1528    unsigned char *buf)
1529 {
1530     int size;
1531     struct kinfo_ndd *nddp;
1532     void *end;
1533 
1534     size = getkerninfo(KINFO_NDD, 0, 0, 0);
1535     if (size == 0) {
1536         return -1;
1537     }
1538 
1539     if (size < 0) {
1540         perror("getkerninfo 1");
1541         return -1;
1542     }
1543 
1544     nddp = (struct kinfo_ndd *)malloc(size);
1545 
1546     if (!nddp) {
1547         JNU_ThrowOutOfMemoryError(env,
1548             "Network interface getMacAddress native buffer allocation failed");
1549         return -1;
1550     }
1551 
1552     if (getkerninfo(KINFO_NDD, nddp, &size, 0) < 0) {
1553         perror("getkerninfo 2");
1554         free(nddp);
1555         return -1;
1556     }
1557 
1558     end = (void *)nddp + size;
1559     while ((void *)nddp < end) {
1560         if (!strcmp(nddp->ndd_alias, ifname) ||
1561                  !strcmp(nddp->ndd_name, ifname)) {
1562             bcopy(nddp->ndd_addr, buf, 6);
1563             free(nddp);
1564             return 6;
1565         } else {
1566             nddp++;
1567         }
1568     }
1569 
1570     free(nddp);
1571     return -1;
1572 }
1573 
1574 static int getMTU(JNIEnv *env, int sock, const char *ifname) {
1575     struct ifreq if2;
1576     memset((char *)&if2, 0, sizeof(if2));
1577     strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
1578 
1579     if (ioctl(sock, SIOCGIFMTU, (char *)&if2) < 0) {
1580         JNU_ThrowByNameWithMessageAndLastError
1581             (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFMTU) failed");
1582         return -1;
1583     }
1584 
1585     return if2.ifr_mtu;
1586 }
1587 
1588 static int getFlags(int sock, const char *ifname, int *flags) {
1589     struct ifreq if2;
1590     memset((char *)&if2, 0, sizeof(if2));
1591     strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
1592 
1593     if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) < 0) {
1594         return -1;
1595     }
1596 
1597     if (sizeof(if2.ifr_flags) == sizeof(short)) {
1598         *flags = (if2.ifr_flags & 0xffff);
1599     } else {
1600         *flags = if2.ifr_flags;
1601     }
1602     return 0;
1603 }
1604 
1605 #endif /* _AIX */
1606 
1607 /** Solaris **/
1608 #if defined(__solaris__)
1609 
1610 /*
1611  * Opens a socket for further ioctl calls. Tries AF_INET socket first and
1612  * if it fails return AF_INET6 socket.
1613  */
1614 static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
1615     int sock, alreadyV6 = 0;
1616     struct lifreq if2;
1617 
1618     if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
1619         if (errno == EPROTONOSUPPORT || errno == EAFNOSUPPORT) {
1620             if ((sock = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
1621                 JNU_ThrowByNameWithMessageAndLastError
1622                     (env, JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
1623                 return -1;
1624             }
1625             alreadyV6 = 1;
1626         } else { // errno is not NOSUPPORT
1627             JNU_ThrowByNameWithMessageAndLastError
1628                 (env, JNU_JAVANETPKG "SocketException", "IPV4 Socket creation failed");
1629             return -1;
1630         }
1631     }
1632 
1633     // Solaris requires that we have an IPv6 socket to query an  interface
1634     // without an IPv4 address - check it here. POSIX 1 require the kernel to
1635     // return ENOTTY if the call is inappropriate for a device e.g. the NETMASK
1636     // for a device having IPv6 only address but not all devices follow the
1637     // standard so fall back on any error. It's not an ecologically friendly
1638     // gesture but more reliable.
1639     if (!alreadyV6) {
1640         memset((char *)&if2, 0, sizeof(if2));
1641         strncpy(if2.lifr_name, ifname, sizeof(if2.lifr_name) - 1);
1642         if (ioctl(sock, SIOCGLIFNETMASK, (char *)&if2) < 0) {
1643             close(sock);
1644             if ((sock = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
1645                 JNU_ThrowByNameWithMessageAndLastError
1646                     (env, JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
1647                 return -1;
1648             }
1649         }
1650     }
1651 
1652     return sock;
1653 }
1654 
1655 /*
1656  * Enumerates and returns all IPv4 interfaces on Solaris.
1657  */
1658 static netif *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs) {
1659     struct lifconf ifc;
1660     struct lifreq *ifreqP;
1661     struct lifnum numifs;
1662     char *buf = NULL;
1663     unsigned i;
1664 
1665     // call SIOCGLIFNUM to get the interface count
1666     numifs.lifn_family = AF_INET;
1667     numifs.lifn_flags = 0;
1668     if (ioctl(sock, SIOCGLIFNUM, (char *)&numifs) < 0) {
1669         JNU_ThrowByNameWithMessageAndLastError
1670             (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGLIFNUM) failed");
1671         return ifs;
1672     }
1673 
1674     // call SIOCGLIFCONF to enumerate the interfaces
1675     ifc.lifc_len = numifs.lifn_count * sizeof(struct lifreq);
1676     CHECKED_MALLOC3(buf, char *, ifc.lifc_len);
1677     ifc.lifc_buf = buf;
1678     ifc.lifc_family = AF_INET;
1679     ifc.lifc_flags = 0;
1680     if (ioctl(sock, SIOCGLIFCONF, (char *)&ifc) < 0) {
1681         JNU_ThrowByNameWithMessageAndLastError
1682             (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGLIFCONF) failed");
1683         free(buf);
1684         return ifs;
1685     }
1686 
1687     // iterate through each interface
1688     ifreqP = ifc.lifc_req;
1689     for (i = 0; i < numifs.lifn_count; i++, ifreqP++) {
1690         struct sockaddr addr, *broadaddrP = NULL;
1691 
1692         // ignore non IPv4 addresses
1693         if (ifreqP->lifr_addr.ss_family != AF_INET) {
1694             continue;
1695         }
1696 
1697         // save socket address
1698         memcpy(&addr, &(ifreqP->lifr_addr), sizeof(struct sockaddr));
1699 
1700         // determine broadcast address, if applicable
1701         if ((ioctl(sock, SIOCGLIFFLAGS, ifreqP) == 0) &&
1702             ifreqP->lifr_flags & IFF_BROADCAST) {
1703 
1704             // restore socket address to ifreqP
1705             memcpy(&(ifreqP->lifr_addr), &addr, sizeof(struct sockaddr));
1706 
1707             // query broadcast address and set pointer to it
1708             if (ioctl(sock, SIOCGLIFBRDADDR, ifreqP) == 0) {
1709                 broadaddrP = (struct sockaddr *)&(ifreqP->lifr_broadaddr);
1710             }
1711         }
1712 
1713         // add to the list
1714         ifs = addif(env, sock, ifreqP->lifr_name, ifs,
1715                     &addr, broadaddrP, AF_INET, (short)ifreqP->lifr_addrlen);
1716 
1717         // if an exception occurred we return immediately
1718         if ((*env)->ExceptionOccurred(env)) {
1719             free(buf);
1720             return ifs;
1721         }
1722    }
1723 
1724     // free buffer
1725     free(buf);
1726     return ifs;
1727 }
1728 
1729 /*
1730  * Enumerates and returns all IPv6 interfaces on Solaris.
1731  */
1732 static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
1733     struct lifconf ifc;
1734     struct lifreq *ifreqP;
1735     struct lifnum numifs;
1736     char *buf = NULL;
1737     unsigned i;
1738 
1739     // call SIOCGLIFNUM to get the interface count
1740     numifs.lifn_family = AF_INET6;
1741     numifs.lifn_flags = 0;
1742     if (ioctl(sock, SIOCGLIFNUM, (char *)&numifs) < 0) {
1743         JNU_ThrowByNameWithMessageAndLastError
1744             (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGLIFNUM) failed");
1745         return ifs;
1746     }
1747 
1748     // call SIOCGLIFCONF to enumerate the interfaces
1749     ifc.lifc_len = numifs.lifn_count * sizeof(struct lifreq);
1750     CHECKED_MALLOC3(buf, char *, ifc.lifc_len);
1751     ifc.lifc_buf = buf;
1752     ifc.lifc_family = AF_INET6;
1753     ifc.lifc_flags = 0;
1754     if (ioctl(sock, SIOCGLIFCONF, (char *)&ifc) < 0) {
1755         JNU_ThrowByNameWithMessageAndLastError
1756             (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGLIFCONF) failed");
1757         free(buf);
1758         return ifs;
1759     }
1760 
1761     // iterate through each interface
1762     ifreqP = ifc.lifc_req;
1763     for (i = 0; i < numifs.lifn_count; i++, ifreqP++) {
1764 
1765         // ignore non IPv6 addresses
1766         if (ifreqP->lifr_addr.ss_family != AF_INET6) {
1767             continue;
1768         }
1769 
1770         // set scope ID to interface index
1771         ((struct sockaddr_in6 *)&(ifreqP->lifr_addr))->sin6_scope_id =
1772             getIndex(sock, ifreqP->lifr_name);
1773 
1774         // add to the list
1775         ifs = addif(env, sock, ifreqP->lifr_name, ifs,
1776                     (struct sockaddr *)&(ifreqP->lifr_addr),
1777                     NULL, AF_INET6, (short)ifreqP->lifr_addrlen);
1778 
1779         // if an exception occurred we return immediately
1780         if ((*env)->ExceptionOccurred(env)) {
1781             free(buf);
1782             return ifs;
1783         }
1784     }
1785 
1786     // free buffer
1787     free(buf);
1788     return ifs;
1789 }
1790 
1791 /*
1792  * Try to get the interface index.
1793  * (Not supported on Solaris 2.6 or 7)
1794  */
1795 static int getIndex(int sock, const char *name) {
1796     struct lifreq if2;
1797     memset((char *)&if2, 0, sizeof(if2));
1798     strncpy(if2.lifr_name, name, sizeof(if2.lifr_name) - 1);
1799 
1800     if (ioctl(sock, SIOCGLIFINDEX, (char *)&if2) < 0) {
1801         return -1;
1802     }
1803 
1804     return if2.lifr_index;
1805 }
1806 
1807 /*
1808  * Solaris specific DLPI code to get hardware address from a device.
1809  * Unfortunately, at least up to Solaris X, you have to have special
1810  * privileges (i.e. be root).
1811  */
1812 static int getMacFromDevice
1813   (JNIEnv *env, const char *ifname, unsigned char *retbuf)
1814 {
1815     char style1dev[MAXPATHLEN];
1816     int fd;
1817     dl_phys_addr_req_t dlpareq;
1818     dl_phys_addr_ack_t *dlpaack;
1819     struct strbuf msg;
1820     char buf[128];
1821     int flags = 0;
1822 
1823     // Device is in /dev.  e.g.: /dev/bge0
1824     strcpy(style1dev, DEV_PREFIX);
1825     strcat(style1dev, ifname);
1826     if ((fd = open(style1dev, O_RDWR)) < 0) {
1827         // Can't open it. We probably are missing the privilege.
1828         // We'll have to try something else
1829         return 0;
1830     }
1831 
1832     dlpareq.dl_primitive = DL_PHYS_ADDR_REQ;
1833     dlpareq.dl_addr_type = DL_CURR_PHYS_ADDR;
1834 
1835     msg.buf = (char *)&dlpareq;
1836     msg.len = DL_PHYS_ADDR_REQ_SIZE;
1837 
1838     if (putmsg(fd, &msg, NULL, 0) < 0) {
1839         JNU_ThrowByNameWithMessageAndLastError
1840             (env, JNU_JAVANETPKG "SocketException", "putmsg() failed");
1841         return -1;
1842     }
1843 
1844     dlpaack = (dl_phys_addr_ack_t *)buf;
1845 
1846     msg.buf = (char *)buf;
1847     msg.len = 0;
1848     msg.maxlen = sizeof (buf);
1849     if (getmsg(fd, &msg, NULL, &flags) < 0) {
1850         JNU_ThrowByNameWithMessageAndLastError
1851             (env, JNU_JAVANETPKG "SocketException", "getmsg() failed");
1852         return -1;
1853     }
1854 
1855     if (msg.len < DL_PHYS_ADDR_ACK_SIZE || dlpaack->dl_primitive != DL_PHYS_ADDR_ACK) {
1856         JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
1857                         "Couldn't obtain phys addr\n");
1858         return -1;
1859     }
1860 
1861     memcpy(retbuf, &buf[dlpaack->dl_addr_offset], dlpaack->dl_addr_length);
1862     return dlpaack->dl_addr_length;
1863 }
1864 
1865 /*
1866  * Gets the Hardware address (usually MAC address) for the named interface.
1867  * On return puts the data in buf, and returns the length, in byte, of the
1868  * MAC address. Returns -1 if there is no hardware address on that interface.
1869  */
1870 static int getMacAddress
1871   (JNIEnv *env, const char *ifname, const struct in_addr *addr,
1872    unsigned char *buf)
1873 {
1874     struct lifreq if2;
1875     int len, i, sock;
1876 
1877     if ((sock = openSocketWithFallback(env, ifname)) < 0) {
1878         return -1;
1879     }
1880 
1881     // First, try the new (S11) SIOCGLIFHWADDR ioctl(). If that fails
1882     // try the old way.
1883     memset((char *)&if2, 0, sizeof(if2));
1884     strncpy(if2.lifr_name, ifname, sizeof(if2.lifr_name) - 1);
1885 
1886     if (ioctl(sock, SIOCGLIFHWADDR, &if2) != -1) {
1887         struct sockaddr_dl *sp;
1888         sp = (struct sockaddr_dl *)&if2.lifr_addr;
1889         memcpy(buf, &sp->sdl_data[0], sp->sdl_alen);
1890         close(sock);
1891         return sp->sdl_alen;
1892     }
1893 
1894     // On Solaris we have to use DLPI, but it will only work if we have
1895     // privileged access (i.e. root). If that fails, we try a lookup
1896     // in the ARP table, which requires an IPv4 address.
1897     if (((len = getMacFromDevice(env, ifname, buf)) == 0) && (addr != NULL)) {
1898         struct arpreq arpreq;
1899         struct sockaddr_in *sin;
1900         struct sockaddr_in ipAddr;
1901 
1902         len = 6; //???
1903 
1904         sin = (struct sockaddr_in *)&arpreq.arp_pa;
1905         memset((char *)&arpreq, 0, sizeof(struct arpreq));
1906         ipAddr.sin_port = 0;
1907         ipAddr.sin_family = AF_INET;
1908         memcpy(&ipAddr.sin_addr, addr, sizeof(struct in_addr));
1909         memcpy(&arpreq.arp_pa, &ipAddr, sizeof(struct sockaddr_in));
1910         arpreq.arp_flags= ATF_PUBL;
1911 
1912         if (ioctl(sock, SIOCGARP, &arpreq) < 0) {
1913             close(sock);
1914             return -1;
1915         }
1916 
1917         memcpy(buf, &arpreq.arp_ha.sa_data[0], len);
1918     }
1919     close(sock);
1920 
1921     // all bytes to 0 means no hardware address
1922     for (i = 0; i < len; i++) {
1923         if (buf[i] != 0)
1924             return len;
1925     }
1926 
1927     return -1;
1928 }
1929 
1930 static int getMTU(JNIEnv *env, int sock, const char *ifname) {
1931     struct lifreq if2;
1932     memset((char *)&if2, 0, sizeof(if2));
1933     strncpy(if2.lifr_name, ifname, sizeof(if2.lifr_name) - 1);
1934 
1935     if (ioctl(sock, SIOCGLIFMTU, (char *)&if2) < 0) {
1936         JNU_ThrowByNameWithMessageAndLastError
1937             (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGLIFMTU) failed");
1938         return -1;
1939     }
1940 
1941     return if2.lifr_mtu;
1942 }
1943 
1944 static int getFlags(int sock, const char *ifname, int *flags) {
1945     struct lifreq if2;
1946     memset((char *)&if2, 0, sizeof(if2));
1947     strncpy(if2.lifr_name, ifname, sizeof(if2.lifr_name) - 1);
1948 
1949     if (ioctl(sock, SIOCGLIFFLAGS, (char *)&if2) < 0) {
1950         return -1;
1951     }
1952 
1953     *flags = if2.lifr_flags;
1954     return 0;
1955 }
1956 
1957 #endif /* __solaris__ */
1958 
1959 /** BSD **/
1960 #if defined(_ALLBSD_SOURCE)
1961 
1962 /*
1963  * Opens a socket for further ioctl calls. Tries AF_INET socket first and
1964  * if it fails return AF_INET6 socket.
1965  */
1966 static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
1967     int sock;
1968 
1969     if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
1970         if (errno == EPROTONOSUPPORT || errno == EAFNOSUPPORT) {
1971             if ((sock = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
1972                 JNU_ThrowByNameWithMessageAndLastError
1973                     (env, JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
1974                 return -1;
1975             }
1976         } else { // errno is not NOSUPPORT
1977             JNU_ThrowByNameWithMessageAndLastError
1978                 (env, JNU_JAVANETPKG "SocketException", "IPV4 Socket creation failed");
1979             return -1;
1980         }
1981     }
1982 
1983     return sock;
1984 }
1985 
1986 /*
1987  * Enumerates and returns all IPv4 interfaces on BSD.
1988  */
1989 static netif *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs) {
1990     struct ifaddrs *ifa, *origifa;
1991 
1992     if (getifaddrs(&origifa) != 0) {
1993         JNU_ThrowByNameWithMessageAndLastError
1994             (env, JNU_JAVANETPKG "SocketException", "getifaddrs() failed");
1995         return ifs;
1996     }
1997 
1998     for (ifa = origifa; ifa != NULL; ifa = ifa->ifa_next) {
1999         struct sockaddr *broadaddrP = NULL;
2000 
2001         // ignore non IPv4 addresses
2002         if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != AF_INET)
2003             continue;
2004 
2005         // set ifa_broadaddr, if there is one
2006         if ((ifa->ifa_flags & IFF_POINTOPOINT) == 0 &&
2007             ifa->ifa_flags & IFF_BROADCAST) {
2008             broadaddrP = ifa->ifa_dstaddr;
2009         }
2010 
2011         // add interface to the list
2012         ifs = addif(env, sock, ifa->ifa_name, ifs, ifa->ifa_addr,
2013                     broadaddrP, AF_INET,
2014                     translateIPv4AddressToPrefix((struct sockaddr_in *)
2015                                                  ifa->ifa_netmask));
2016 
2017         // if an exception occurred then free the list
2018         if ((*env)->ExceptionOccurred(env)) {
2019             freeifaddrs(origifa);
2020             freeif(ifs);
2021             return NULL;
2022         }
2023     }
2024 
2025     // free ifaddrs buffer
2026     freeifaddrs(origifa);
2027     return ifs;
2028 }
2029 
2030 /*
2031  * Enumerates and returns all IPv6 interfaces on BSD.
2032  */
2033 static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
2034     struct ifaddrs *ifa, *origifa;
2035 
2036     if (getifaddrs(&origifa) != 0) {
2037         JNU_ThrowByNameWithMessageAndLastError
2038             (env, JNU_JAVANETPKG "SocketException", "getifaddrs() failed");
2039         return ifs;
2040     }
2041 
2042     for (ifa = origifa; ifa != NULL; ifa = ifa->ifa_next) {
2043         // ignore non IPv6 addresses
2044         if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != AF_INET6)
2045             continue;
2046 
2047         // set scope ID to interface index
2048         ((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_scope_id =
2049             getIndex(sock, ifa->ifa_name);
2050 
2051         // add interface to the list
2052         ifs = addif(env, sock, ifa->ifa_name, ifs, ifa->ifa_addr, NULL,
2053                     AF_INET6,
2054                     translateIPv6AddressToPrefix((struct sockaddr_in6 *)
2055                                                  ifa->ifa_netmask));
2056 
2057         // if an exception occurred then free the list
2058         if ((*env)->ExceptionOccurred(env)) {
2059             freeifaddrs(origifa);
2060             freeif(ifs);
2061             return NULL;
2062         }
2063     }
2064 
2065     // free ifaddrs buffer
2066     freeifaddrs(origifa);
2067     return ifs;
2068 }
2069 
2070 /*
2071  * Try to get the interface index.
2072  */
2073 static int getIndex(int sock, const char *name) {
2074 #if !defined(__FreeBSD__)
2075     int index = if_nametoindex(name);
2076     return (index == 0) ? -1 : index;
2077 #else
2078     struct ifreq if2;
2079     memset((char *)&if2, 0, sizeof(if2));
2080     strncpy(if2.ifr_name, name, sizeof(if2.ifr_name) - 1);
2081 
2082     if (ioctl(sock, SIOCGIFINDEX, (char *)&if2) < 0) {
2083         return -1;
2084     }
2085 
2086     return if2.ifr_index;
2087 #endif
2088 }
2089 
2090 /*
2091  * Gets the Hardware address (usually MAC address) for the named interface.
2092  * On return puts the data in buf, and returns the length, in byte, of the
2093  * MAC address. Returns -1 if there is no hardware address on that interface.
2094  */
2095 static int getMacAddress
2096   (JNIEnv *env, const char *ifname, const struct in_addr *addr,
2097    unsigned char *buf)
2098 {
2099     struct ifaddrs *ifa0, *ifa;
2100     struct sockaddr *saddr;
2101     int i;
2102 
2103     // grab the interface list
2104     if (!getifaddrs(&ifa0)) {
2105         // cycle through the interfaces
2106         for (i = 0, ifa = ifa0; ifa != NULL; ifa = ifa->ifa_next, i++) {
2107             saddr = ifa->ifa_addr;
2108             if (saddr != NULL) {
2109                 // link layer contains the MAC address
2110                 if (saddr->sa_family == AF_LINK && !strcmp(ifname, ifa->ifa_name)) {
2111                     struct sockaddr_dl *sadl = (struct sockaddr_dl *) saddr;
2112                     // check the address has the correct length
2113                     if (sadl->sdl_alen == ETHER_ADDR_LEN) {
2114                         memcpy(buf, (sadl->sdl_data + sadl->sdl_nlen), ETHER_ADDR_LEN);
2115                         freeifaddrs(ifa0);
2116                         return ETHER_ADDR_LEN;
2117                     }
2118                 }
2119             }
2120         }
2121         freeifaddrs(ifa0);
2122     }
2123 
2124     return -1;
2125 }
2126 
2127 static int getMTU(JNIEnv *env, int sock, const char *ifname) {
2128     struct ifreq if2;
2129     memset((char *)&if2, 0, sizeof(if2));
2130     strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
2131 
2132     if (ioctl(sock, SIOCGIFMTU, (char *)&if2) < 0) {
2133         JNU_ThrowByNameWithMessageAndLastError
2134             (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFMTU) failed");
2135         return -1;
2136     }
2137 
2138     return if2.ifr_mtu;
2139 }
2140 
2141 static int getFlags(int sock, const char *ifname, int *flags) {
2142     struct ifreq if2;
2143     memset((char *)&if2, 0, sizeof(if2));
2144     strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
2145 
2146     if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) < 0) {
2147         return -1;
2148     }
2149 
2150     if (sizeof(if2.ifr_flags) == sizeof(short)) {
2151         *flags = (if2.ifr_flags & 0xffff);
2152     } else {
2153         *flags = if2.ifr_flags;
2154     }
2155     return 0;
2156 }
2157 #endif /* _ALLBSD_SOURCE */