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