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