NetworkInterface.c 59.5 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
24 25
 */

26

D
duke 已提交
27 28
#include <errno.h>
#include <strings.h>
29 30 31
#if defined(_ALLBSD_SOURCE) && defined(__OpenBSD__)
#include <sys/types.h>
#endif
D
duke 已提交
32 33 34 35 36 37 38 39
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <net/if_arp.h>
40

D
duke 已提交
41 42 43 44
#ifdef __solaris__
#include <sys/dlpi.h>
#include <fcntl.h>
#include <stropts.h>
45
#include <sys/sockio.h>
D
duke 已提交
46
#endif
47

D
duke 已提交
48 49 50 51 52 53 54
#ifdef __linux__
#include <sys/ioctl.h>
#include <bits/ioctls.h>
#include <sys/utsname.h>
#include <stdio.h>
#endif

55 56 57 58 59 60 61
#if defined(_AIX)
#include <sys/ioctl.h>
#include <netinet/in6_var.h>
#include <sys/ndd_var.h>
#include <sys/kinfo.h>
#endif

D
duke 已提交
62 63 64 65
#ifdef __linux__
#define _PATH_PROCNET_IFINET6           "/proc/net/if_inet6"
#endif

66 67 68 69 70 71 72 73 74 75 76 77 78
#if defined(_ALLBSD_SOURCE)
#include <sys/param.h>
#include <sys/ioctl.h>
#include <sys/sockio.h>
#if defined(__APPLE__)
#include <net/ethernet.h>
#include <net/if_var.h>
#include <net/if_dl.h>
#include <netinet/in_var.h>
#include <ifaddrs.h>
#endif
#endif

D
duke 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
#include "jvm.h"
#include "jni_util.h"
#include "net_util.h"

typedef struct _netaddr  {
    struct sockaddr *addr;
    struct sockaddr *brdcast;
    short mask;
    int family; /* to make searches simple */
    struct _netaddr *next;
} netaddr;

typedef struct _netif {
    char *name;
    int index;
    char virtual;
    netaddr *addr;
    struct _netif *childs;
    struct _netif *next;
} netif;

/************************************************************************
 * NetworkInterface
 */

#include "java_net_NetworkInterface.h"

/************************************************************************
 * NetworkInterface
 */
jclass ni_class;
jfieldID ni_nameID;
jfieldID ni_indexID;
jfieldID ni_descID;
jfieldID ni_addrsID;
jfieldID ni_bindsID;
jfieldID ni_virutalID;
jfieldID ni_childsID;
jfieldID ni_parentID;
118
jfieldID ni_defaultIndexID;
D
duke 已提交
119 120 121 122 123 124 125 126 127 128 129 130 131
jmethodID ni_ctrID;

static jclass ni_iacls;
static jclass ni_ia4cls;
static jclass ni_ia6cls;
static jclass ni_ibcls;
static jmethodID ni_ia4ctrID;
static jmethodID ni_ia6ctrID;
static jmethodID ni_ibctrID;
static jfieldID ni_ibaddressID;
static jfieldID ni_ib4broadcastID;
static jfieldID ni_ib4maskID;

132
/** Private methods declarations **/
D
duke 已提交
133
static jobject createNetworkInterface(JNIEnv *env, netif *ifs);
134 135 136 137
static int     getFlags0(JNIEnv *env, jstring  ifname);

static netif  *enumInterfaces(JNIEnv *env);
static netif  *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs);
D
duke 已提交
138 139

#ifdef AF_INET6
140 141 142 143 144 145 146 147 148 149 150 151
static netif  *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs);
#endif

static netif  *addif(JNIEnv *env, int sock, const char * if_name, netif *ifs, struct sockaddr* ifr_addrP, int family, short prefix);
static void    freeif(netif *ifs);

static int     openSocket(JNIEnv *env, int proto);
static int     openSocketWithFallback(JNIEnv *env, const char *ifname);


static struct  sockaddr *getBroadcast(JNIEnv *env, int sock, const char *name, struct sockaddr *brdcast_store);
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 156 157 158 159 160 161 162
static int     getMacAddress(JNIEnv *env, int sock,  const char* ifname, const struct in_addr* addr, unsigned char *buf);
static int     getMTU(JNIEnv *env, int sock, const char *ifname);



#ifdef __solaris__
static netif *enumIPvXInterfaces(JNIEnv *env, int sock, netif *ifs, int family);
static int    getMacFromDevice(JNIEnv *env, const char* ifname, unsigned char* retbuf);
163 164 165

#ifndef SIOCGLIFHWADDR
#define SIOCGLIFHWADDR  _IOWR('i', 192, struct lifreq)
D
duke 已提交
166 167
#endif

168
#endif
169 170

/******************* Java entry points *****************************/
D
duke 已提交
171 172 173 174 175 176 177 178 179

/*
 * Class:     java_net_NetworkInterface
 * Method:    init
 * Signature: ()V
 */
JNIEXPORT void JNICALL
Java_java_net_NetworkInterface_init(JNIEnv *env, jclass cls) {
    ni_class = (*env)->FindClass(env,"java/net/NetworkInterface");
180
    CHECK_NULL(ni_class);
D
duke 已提交
181
    ni_class = (*env)->NewGlobalRef(env, ni_class);
182
    CHECK_NULL(ni_class);
D
duke 已提交
183
    ni_nameID = (*env)->GetFieldID(env, ni_class,"name", "Ljava/lang/String;");
184
    CHECK_NULL(ni_nameID);
D
duke 已提交
185
    ni_indexID = (*env)->GetFieldID(env, ni_class, "index", "I");
186
    CHECK_NULL(ni_indexID);
D
duke 已提交
187
    ni_addrsID = (*env)->GetFieldID(env, ni_class, "addrs", "[Ljava/net/InetAddress;");
188
    CHECK_NULL(ni_addrsID);
D
duke 已提交
189
    ni_bindsID = (*env)->GetFieldID(env, ni_class, "bindings", "[Ljava/net/InterfaceAddress;");
190
    CHECK_NULL(ni_bindsID);
D
duke 已提交
191
    ni_descID = (*env)->GetFieldID(env, ni_class, "displayName", "Ljava/lang/String;");
192
    CHECK_NULL(ni_descID);
D
duke 已提交
193
    ni_virutalID = (*env)->GetFieldID(env, ni_class, "virtual", "Z");
194
    CHECK_NULL(ni_virutalID);
D
duke 已提交
195
    ni_childsID = (*env)->GetFieldID(env, ni_class, "childs", "[Ljava/net/NetworkInterface;");
196
    CHECK_NULL(ni_childsID);
D
duke 已提交
197
    ni_parentID = (*env)->GetFieldID(env, ni_class, "parent", "Ljava/net/NetworkInterface;");
198
    CHECK_NULL(ni_parentID);
D
duke 已提交
199
    ni_ctrID = (*env)->GetMethodID(env, ni_class, "<init>", "()V");
200
    CHECK_NULL(ni_ctrID);
D
duke 已提交
201 202

    ni_iacls = (*env)->FindClass(env, "java/net/InetAddress");
203
    CHECK_NULL(ni_iacls);
D
duke 已提交
204
    ni_iacls = (*env)->NewGlobalRef(env, ni_iacls);
205
    CHECK_NULL(ni_iacls);
D
duke 已提交
206
    ni_ia4cls = (*env)->FindClass(env, "java/net/Inet4Address");
207
    CHECK_NULL(ni_ia4cls);
D
duke 已提交
208
    ni_ia4cls = (*env)->NewGlobalRef(env, ni_ia4cls);
209
    CHECK_NULL(ni_ia4cls);
D
duke 已提交
210
    ni_ia6cls = (*env)->FindClass(env, "java/net/Inet6Address");
211
    CHECK_NULL(ni_ia6cls);
D
duke 已提交
212
    ni_ia6cls = (*env)->NewGlobalRef(env, ni_ia6cls);
213
    CHECK_NULL(ni_ia6cls);
D
duke 已提交
214
    ni_ibcls = (*env)->FindClass(env, "java/net/InterfaceAddress");
215
    CHECK_NULL(ni_ibcls);
D
duke 已提交
216
    ni_ibcls = (*env)->NewGlobalRef(env, ni_ibcls);
217
    CHECK_NULL(ni_ibcls);
D
duke 已提交
218
    ni_ia4ctrID = (*env)->GetMethodID(env, ni_ia4cls, "<init>", "()V");
219
    CHECK_NULL(ni_ia4ctrID);
D
duke 已提交
220
    ni_ia6ctrID = (*env)->GetMethodID(env, ni_ia6cls, "<init>", "()V");
221
    CHECK_NULL(ni_ia6ctrID);
D
duke 已提交
222
    ni_ibctrID = (*env)->GetMethodID(env, ni_ibcls, "<init>", "()V");
223
    CHECK_NULL(ni_ibctrID);
D
duke 已提交
224
    ni_ibaddressID = (*env)->GetFieldID(env, ni_ibcls, "address", "Ljava/net/InetAddress;");
225
    CHECK_NULL(ni_ibaddressID);
D
duke 已提交
226
    ni_ib4broadcastID = (*env)->GetFieldID(env, ni_ibcls, "broadcast", "Ljava/net/Inet4Address;");
227
    CHECK_NULL(ni_ib4broadcastID);
D
duke 已提交
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");
D
duke 已提交
231 232 233 234 235 236 237 238 239 240 241 242 243
}


/*
 * Class:     java_net_NetworkInterface
 * Method:    getByName0
 * Signature: (Ljava/lang/String;)Ljava/net/NetworkInterface;
 */
JNIEXPORT jobject JNICALL Java_java_net_NetworkInterface_getByName0
    (JNIEnv *env, jclass cls, jstring name) {

    netif *ifs, *curr;
    jboolean isCopy;
244
    const char* name_utf;
D
duke 已提交
245 246 247 248 249 250 251
    jobject obj = NULL;

    ifs = enumInterfaces(env);
    if (ifs == NULL) {
        return NULL;
    }

252 253
    name_utf = (*env)->GetStringUTFChars(env, name, &isCopy);

D
duke 已提交
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
    /*
     * Search the list of interface based on name
     */
    curr = ifs;
    while (curr != NULL) {
        if (strcmp(name_utf, curr->name) == 0) {
            break;
        }
        curr = curr->next;
    }

    /* if found create a NetworkInterface */
    if (curr != NULL) {;
        obj = createNetworkInterface(env, curr);
    }

    /* release the UTF string and interface list */
    (*env)->ReleaseStringUTFChars(env, name, name_utf);
    freeif(ifs);

    return obj;
}


/*
 * Class:     java_net_NetworkInterface
280
 * Method:    getByIndex0
D
duke 已提交
281 282
 * Signature: (Ljava/lang/String;)Ljava/net/NetworkInterface;
 */
283
JNIEXPORT jobject JNICALL Java_java_net_NetworkInterface_getByIndex0
D
duke 已提交
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
    (JNIEnv *env, jclass cls, jint index) {

    netif *ifs, *curr;
    jobject obj = NULL;

    if (index <= 0) {
        return NULL;
    }

    ifs = enumInterfaces(env);
    if (ifs == NULL) {
        return NULL;
    }

    /*
     * Search the list of interface based on index
     */
    curr = ifs;
    while (curr != NULL) {
        if (index == curr->index) {
            break;
        }
        curr = curr->next;
    }

    /* if found create a NetworkInterface */
    if (curr != NULL) {;
        obj = createNetworkInterface(env, curr);
    }

    freeif(ifs);
    return obj;
}

/*
 * Class:     java_net_NetworkInterface
 * Method:    getByInetAddress0
 * Signature: (Ljava/net/InetAddress;)Ljava/net/NetworkInterface;
 */
JNIEXPORT jobject JNICALL Java_java_net_NetworkInterface_getByInetAddress0
    (JNIEnv *env, jclass cls, jobject iaObj) {

    netif *ifs, *curr;
327

C
chegar 已提交
328
#ifdef AF_INET6
329
    int family = (getInetAddress_family(env, iaObj) == IPv4) ? AF_INET : AF_INET6;
C
chegar 已提交
330
#else
331
    int family =  AF_INET;
C
chegar 已提交
332
#endif
333

D
duke 已提交
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
    jobject obj = NULL;
    jboolean match = JNI_FALSE;

    ifs = enumInterfaces(env);
    if (ifs == NULL) {
        return NULL;
    }

    curr = ifs;
    while (curr != NULL) {
        netaddr *addrP = curr->addr;

        /*
         * Iterate through each address on the interface
         */
        while (addrP != NULL) {

            if (family == addrP->family) {
                if (family == AF_INET) {
                    int address1 = htonl(((struct sockaddr_in*)addrP->addr)->sin_addr.s_addr);
354
                    int address2 = getInetAddress_addr(env, iaObj);
D
duke 已提交
355 356 357 358 359 360 361 362 363 364 365 366

                    if (address1 == address2) {
                        match = JNI_TRUE;
                        break;
                    }
                }

#ifdef AF_INET6
                if (family == AF_INET6) {
                    jbyte *bytes = (jbyte *)&(((struct sockaddr_in6*)addrP->addr)->sin6_addr);
                    jbyte caddr[16];
                    int i;
M
michaelm 已提交
367
                    getInet6Address_ipaddress(env, iaObj, (char *)caddr);
D
duke 已提交
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
                    i = 0;
                    while (i < 16) {
                        if (caddr[i] != bytes[i]) {
                            break;
                        }
                        i++;
                    }
                    if (i >= 16) {
                        match = JNI_TRUE;
                        break;
                    }
                }
#endif

            }

            if (match) {
                break;
            }
            addrP = addrP->next;
        }

        if (match) {
            break;
        }
        curr = curr->next;
    }

    /* if found create a NetworkInterface */
    if (match) {;
        obj = createNetworkInterface(env, curr);
    }

    freeif(ifs);
    return obj;
}


/*
 * Class:     java_net_NetworkInterface
 * Method:    getAll
 * Signature: ()[Ljava/net/NetworkInterface;
 */
JNIEXPORT jobjectArray JNICALL Java_java_net_NetworkInterface_getAll
    (JNIEnv *env, jclass cls) {

    netif *ifs, *curr;
    jobjectArray netIFArr;
    jint arr_index, ifCount;

    ifs = enumInterfaces(env);
    if (ifs == NULL) {
        return NULL;
    }

    /* count the interface */
    ifCount = 0;
    curr = ifs;
    while (curr != NULL) {
        ifCount++;
        curr = curr->next;
    }

    /* allocate a NetworkInterface array */
    netIFArr = (*env)->NewObjectArray(env, ifCount, cls, NULL);
    if (netIFArr == NULL) {
        freeif(ifs);
        return NULL;
    }

    /*
     * Iterate through the interfaces, create a NetworkInterface instance
     * for each array element and populate the object.
     */
    curr = ifs;
    arr_index = 0;
    while (curr != NULL) {
        jobject netifObj;

        netifObj = createNetworkInterface(env, curr);
        if (netifObj == NULL) {
            freeif(ifs);
            return NULL;
        }

        /* put the NetworkInterface into the array */
        (*env)->SetObjectArrayElement(env, netIFArr, arr_index++, netifObj);

        curr = curr->next;
    }

    freeif(ifs);
    return netIFArr;
}

463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587

/*
 * Class:     java_net_NetworkInterface
 * Method:    isUp0
 * Signature: (Ljava/lang/String;I)Z
 */
JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_isUp0(JNIEnv *env, jclass cls, jstring name, jint index) {
    int ret = getFlags0(env, name);
    return ((ret & IFF_UP) && (ret & IFF_RUNNING)) ? JNI_TRUE :  JNI_FALSE;
}

/*
 * Class:     java_net_NetworkInterface
 * Method:    isP2P0
 * Signature: (Ljava/lang/String;I)Z
 */
JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_isP2P0(JNIEnv *env, jclass cls, jstring name, jint index) {
    int ret = getFlags0(env, name);
    return (ret & IFF_POINTOPOINT) ? JNI_TRUE :  JNI_FALSE;
}

/*
 * Class:     java_net_NetworkInterface
 * Method:    isLoopback0
 * Signature: (Ljava/lang/String;I)Z
 */
JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_isLoopback0(JNIEnv *env, jclass cls, jstring name, jint index) {
    int ret = getFlags0(env, name);
    return (ret & IFF_LOOPBACK) ? JNI_TRUE :  JNI_FALSE;
}

/*
 * Class:     java_net_NetworkInterface
 * Method:    supportsMulticast0
 * Signature: (Ljava/lang/String;I)Z
 */
JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_supportsMulticast0(JNIEnv *env, jclass cls, jstring name, jint index) {
    int ret = getFlags0(env, name);
    return (ret & IFF_MULTICAST) ? JNI_TRUE :  JNI_FALSE;
}

/*
 * Class:     java_net_NetworkInterface
 * Method:    getMacAddr0
 * Signature: ([bLjava/lang/String;I)[b
 */
JNIEXPORT jbyteArray JNICALL Java_java_net_NetworkInterface_getMacAddr0(JNIEnv *env, jclass class, jbyteArray addrArray, jstring name, jint index) {
    jint addr;
    jbyte caddr[4];
    struct in_addr iaddr;
    jbyteArray ret = NULL;
    unsigned char mac[16];
    int len;
    int sock;
    jboolean isCopy;
    const char* name_utf;

    name_utf = (*env)->GetStringUTFChars(env, name, &isCopy);

    if ((sock =openSocketWithFallback(env, name_utf)) < 0) {
       (*env)->ReleaseStringUTFChars(env, name, name_utf);
       return JNI_FALSE;
    }


    if (!IS_NULL(addrArray)) {
       (*env)->GetByteArrayRegion(env, addrArray, 0, 4, caddr);
       addr = ((caddr[0]<<24) & 0xff000000);
       addr |= ((caddr[1] <<16) & 0xff0000);
       addr |= ((caddr[2] <<8) & 0xff00);
       addr |= (caddr[3] & 0xff);
       iaddr.s_addr = htonl(addr);
       len = getMacAddress(env, sock, name_utf, &iaddr, mac);
    } else {
       len = getMacAddress(env, sock, name_utf,NULL, mac);
    }
    if (len > 0) {
       ret = (*env)->NewByteArray(env, len);
       if (IS_NULL(ret)) {
          /* we may have memory to free at the end of this */
          goto fexit;
       }
       (*env)->SetByteArrayRegion(env, ret, 0, len, (jbyte *) (mac));
    }
 fexit:
   /* release the UTF string and interface list */
   (*env)->ReleaseStringUTFChars(env, name, name_utf);

   close(sock);
   return ret;
}

/*
 * Class:       java_net_NetworkInterface
 * Method:      getMTU0
 * Signature:   ([bLjava/lang/String;I)I
 */

JNIEXPORT jint JNICALL Java_java_net_NetworkInterface_getMTU0(JNIEnv *env, jclass class, jstring name, jint index) {
    jboolean isCopy;
    int ret = -1;
    int sock;
    const char* name_utf;

    name_utf = (*env)->GetStringUTFChars(env, name, &isCopy);

    if ((sock =openSocketWithFallback(env, name_utf)) < 0) {
       (*env)->ReleaseStringUTFChars(env, name, name_utf);
       return JNI_FALSE;
    }

    ret = getMTU(env, sock, name_utf);

    (*env)->ReleaseStringUTFChars(env, name, name_utf);

    close(sock);
    return ret;
}

/*** Private methods definitions ****/

static int getFlags0(JNIEnv *env, jstring name) {
    jboolean isCopy;
    int ret, sock;
    const char* name_utf;
588
    int flags = 0;
589 590 591 592 593

    name_utf = (*env)->GetStringUTFChars(env, name, &isCopy);

    if ((sock = openSocketWithFallback(env, name_utf)) < 0) {
        (*env)->ReleaseStringUTFChars(env, name, name_utf);
594
        return -1;
595 596
    }

597
    ret = getFlags(sock, name_utf, &flags);
598 599 600 601 602 603 604 605 606

    close(sock);
    (*env)->ReleaseStringUTFChars(env, name, name_utf);

    if (ret < 0) {
        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL  SIOCGLIFFLAGS failed");
        return -1;
    }

607
    return flags;
608 609 610 611 612
}




D
duke 已提交
613 614 615 616 617
/*
 * Create a NetworkInterface object, populate the name and index, and
 * populate the InetAddress array based on the IP addresses for this
 * interface.
 */
618
jobject createNetworkInterface(JNIEnv *env, netif *ifs) {
D
duke 已提交
619 620 621 622 623
    jobject netifObj;
    jobject name;
    jobjectArray addrArr;
    jobjectArray bindArr;
    jobjectArray childArr;
624
    netaddr *addrs;
D
duke 已提交
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
    jint addr_index, addr_count, bind_index;
    jint child_count, child_index;
    netaddr *addrP;
    netif *childP;
    jobject tmp;

    /*
     * Create a NetworkInterface object and populate it
     */
    netifObj = (*env)->NewObject(env, ni_class, ni_ctrID);
    name = (*env)->NewStringUTF(env, ifs->name);
    if (netifObj == NULL || name == NULL) {
        return NULL;
    }
    (*env)->SetObjectField(env, netifObj, ni_nameID, name);
    (*env)->SetObjectField(env, netifObj, ni_descID, name);
    (*env)->SetIntField(env, netifObj, ni_indexID, ifs->index);
    (*env)->SetBooleanField(env, netifObj, ni_virutalID, ifs->virtual ? JNI_TRUE : JNI_FALSE);

    /*
     * Count the number of address on this interface
     */
    addr_count = 0;
    addrP = ifs->addr;
    while (addrP != NULL) {
        addr_count++;
        addrP = addrP->next;
    }

    /*
     * Create the array of InetAddresses
     */
    addrArr = (*env)->NewObjectArray(env, addr_count,  ni_iacls, NULL);
    if (addrArr == NULL) {
        return NULL;
    }

    bindArr = (*env)->NewObjectArray(env, addr_count, ni_ibcls, NULL);
    if (bindArr == NULL) {
664
       return NULL;
D
duke 已提交
665 666 667 668 669 670 671 672 673 674 675
    }
    addrP = ifs->addr;
    addr_index = 0;
    bind_index = 0;
    while (addrP != NULL) {
        jobject iaObj = NULL;
        jobject ibObj = NULL;

        if (addrP->family == AF_INET) {
            iaObj = (*env)->NewObject(env, ni_ia4cls, ni_ia4ctrID);
            if (iaObj) {
676
                 setInetAddress_addr(env, iaObj, htonl(((struct sockaddr_in*)addrP->addr)->sin_addr.s_addr));
D
duke 已提交
677 678 679
            }
            ibObj = (*env)->NewObject(env, ni_ibcls, ni_ibctrID);
            if (ibObj) {
680 681 682 683 684
                 (*env)->SetObjectField(env, ibObj, ni_ibaddressID, iaObj);
                 if (addrP->brdcast) {
                    jobject ia2Obj = NULL;
                    ia2Obj = (*env)->NewObject(env, ni_ia4cls, ni_ia4ctrID);
                    if (ia2Obj) {
685
                       setInetAddress_addr(env, ia2Obj, htonl(((struct sockaddr_in*)addrP->brdcast)->sin_addr.s_addr));
686 687 688
                       (*env)->SetObjectField(env, ibObj, ni_ib4broadcastID, ia2Obj);
                    }
                 }
689
                 (*env)->SetShortField(env, ibObj, ni_ib4maskID, addrP->mask);
690
                 (*env)->SetObjectArrayElement(env, bindArr, bind_index++, ibObj);
D
duke 已提交
691 692 693 694 695 696 697 698
            }
        }

#ifdef AF_INET6
        if (addrP->family == AF_INET6) {
            int scope=0;
            iaObj = (*env)->NewObject(env, ni_ia6cls, ni_ia6ctrID);
            if (iaObj) {
M
michaelm 已提交
699 700
                int ret = setInet6Address_ipaddress(env, iaObj, (char *)&(((struct sockaddr_in6*)addrP->addr)->sin6_addr));
                if (ret == JNI_FALSE) {
D
duke 已提交
701 702
                    return NULL;
                }
703

D
duke 已提交
704
                scope = ((struct sockaddr_in6*)addrP->addr)->sin6_scope_id;
705

D
duke 已提交
706
                if (scope != 0) { /* zero is default value, no need to set */
M
michaelm 已提交
707 708
                    setInet6Address_scopeid(env, iaObj, scope);
                    setInet6Address_scopeifname(env, iaObj, netifObj);
D
duke 已提交
709 710 711 712
                }
            }
            ibObj = (*env)->NewObject(env, ni_ibcls, ni_ibctrID);
            if (ibObj) {
713 714 715
                (*env)->SetObjectField(env, ibObj, ni_ibaddressID, iaObj);
                (*env)->SetShortField(env, ibObj, ni_ib4maskID, addrP->mask);
                (*env)->SetObjectArrayElement(env, bindArr, bind_index++, ibObj);
D
duke 已提交
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
            }
        }
#endif

        if (iaObj == NULL) {
            return NULL;
        }

        (*env)->SetObjectArrayElement(env, addrArr, addr_index++, iaObj);
        addrP = addrP->next;
    }

    /*
     * See if there is any virtual interface attached to this one.
     */
    child_count = 0;
    childP = ifs->childs;
    while (childP) {
734 735
        child_count++;
        childP = childP->next;
D
duke 已提交
736 737 738 739
    }

    childArr = (*env)->NewObjectArray(env, child_count, ni_class, NULL);
    if (childArr == NULL) {
740
        return NULL;
D
duke 已提交
741 742 743 744 745 746 747 748 749 750 751
    }

    /*
     * Create the NetworkInterface instances for the sub-interfaces as
     * well.
     */
    child_index = 0;
    childP = ifs->childs;
    while(childP) {
      tmp = createNetworkInterface(env, childP);
      if (tmp == NULL) {
752
         return NULL;
D
duke 已提交
753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
      }
      (*env)->SetObjectField(env, tmp, ni_parentID, netifObj);
      (*env)->SetObjectArrayElement(env, childArr, child_index++, tmp);
      childP = childP->next;
    }
    (*env)->SetObjectField(env, netifObj, ni_addrsID, addrArr);
    (*env)->SetObjectField(env, netifObj, ni_bindsID, bindArr);
    (*env)->SetObjectField(env, netifObj, ni_childsID, childArr);

    /* return the NetworkInterface */
    return netifObj;
}

/*
 * Enumerates all interfaces
 */
static netif *enumInterfaces(JNIEnv *env) {
    netif *ifs;
771
    int sock;
D
duke 已提交
772 773 774 775

    /*
     * Enumerate IPv4 addresses
     */
776 777 778 779 780 781 782 783 784 785 786

    sock = openSocket(env, AF_INET);
    if (sock < 0 && (*env)->ExceptionOccurred(env)) {
        return NULL;
    }

    ifs = enumIPv4Interfaces(env, sock, NULL);
    close(sock);

    if (ifs == NULL && (*env)->ExceptionOccurred(env)) {
        return NULL;
D
duke 已提交
787 788
    }

789
    /* return partial list if an exception occurs in the middle of process ???*/
790

D
duke 已提交
791 792 793 794
    /*
     * If IPv6 is available then enumerate IPv6 addresses.
     */
#ifdef AF_INET6
795

796
        /* User can disable ipv6 explicitly by -Djava.net.preferIPv4Stack=true,
797 798 799
         * so we have to call ipv6_available()
         */
        if (ipv6_available()) {
D
duke 已提交
800

801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
           sock =  openSocket(env, AF_INET6);
           if (sock < 0 && (*env)->ExceptionOccurred(env)) {
               freeif(ifs);
               return NULL;
           }

           ifs = enumIPv6Interfaces(env, sock, ifs);
           close(sock);

           if ((*env)->ExceptionOccurred(env)) {
              freeif(ifs);
              return NULL;
           }

       }
D
duke 已提交
816 817 818 819 820
#endif

    return ifs;
}

821 822 823 824
#define CHECKED_MALLOC3(_pointer,_type,_size) \
       do{ \
        _pointer = (_type)malloc( _size ); \
        if (_pointer == NULL) { \
825
            JNU_ThrowOutOfMemoryError(env, "Native heap allocation failed"); \
826 827 828 829
            return ifs; /* return untouched list */ \
        } \
       } while(0)

D
duke 已提交
830 831

/*
832
 * Free an interface list (including any attached addresses)
D
duke 已提交
833
 */
834 835 836
void freeif(netif *ifs) {
    netif *currif = ifs;
    netif *child = NULL;
D
duke 已提交
837

838 839 840 841 842 843 844
    while (currif != NULL) {
        netaddr *addrP = currif->addr;
        while (addrP != NULL) {
            netaddr *next = addrP->next;
            free(addrP);
            addrP = next;
         }
D
duke 已提交
845

846 847 848 849 850 851
            /*
            * Don't forget to free the sub-interfaces.
            */
          if (currif->childs != NULL) {
                freeif(currif->childs);
          }
D
duke 已提交
852

853 854 855
          ifs = currif->next;
          free(currif);
          currif = ifs;
D
duke 已提交
856
    }
857
}
D
duke 已提交
858

859 860 861 862
netif *addif(JNIEnv *env, int sock, const char * if_name,
             netif *ifs, struct sockaddr* ifr_addrP, int family,
             short prefix)
{
863 864
    netif *currif = ifs, *parent;
    netaddr *addrP;
D
duke 已提交
865

866
#ifdef LIFNAMSIZ
867 868
    int ifnam_size = LIFNAMSIZ;
    char name[LIFNAMSIZ], vname[LIFNAMSIZ];
869
#else
870 871
    int ifnam_size = IFNAMSIZ;
    char name[IFNAMSIZ], vname[IFNAMSIZ];
872
#endif
D
duke 已提交
873

874 875 876 877
    char  *name_colonP;
    int mask;
    int isVirtual = 0;
    int addr_size;
878
    int flags = 0;
D
duke 已提交
879

880 881 882 883 884 885 886
    /*
     * If the interface name is a logical interface then we
     * remove the unit number so that we have the physical
     * interface (eg: hme0:1 -> hme0). NetworkInterface
     * currently doesn't have any concept of physical vs.
     * logical interfaces.
     */
887 888
    strncpy(name, if_name, ifnam_size);
    name[ifnam_size - 1] = '\0';
889
    *vname = 0;
D
duke 已提交
890 891

    /*
892 893
     * Create and populate the netaddr node. If allocation fails
     * return an un-updated list.
D
duke 已提交
894
     */
895
    /*Allocate for addr and brdcast at once*/
D
duke 已提交
896

897 898 899 900 901
#ifdef AF_INET6
    addr_size = (family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6);
#else
    addr_size = sizeof(struct sockaddr_in);
#endif
D
duke 已提交
902

903 904 905
    CHECKED_MALLOC3(addrP, netaddr *, sizeof(netaddr)+2*addr_size);
    addrP->addr = (struct sockaddr *)( (char *) addrP+sizeof(netaddr) );
    memcpy(addrP->addr, ifr_addrP, addr_size);
D
duke 已提交
906

907 908 909 910 911
    addrP->family = family;
    addrP->brdcast = NULL;
    addrP->mask = prefix;
    addrP->next = 0;
    if (family == AF_INET) {
912
       // Deal with broadcast addr & subnet mask
913 914
       struct sockaddr * brdcast_to = (struct sockaddr *) ((char *) addrP + sizeof(netaddr) + addr_size);
       addrP->brdcast = getBroadcast(env, sock, name,  brdcast_to );
D
duke 已提交
915

916
       if ((mask = getSubnet(env, sock, name)) != -1)
917 918 919 920
           addrP->mask = mask;
     }

    /**
921
     * Deal with virtual interface with colon notation e.g. eth0:1
922 923 924 925 926 927 928 929 930
     */
    name_colonP = strchr(name, ':');
    if (name_colonP != NULL) {
      /**
       * This is a virtual interface. If we are able to access the parent
       * we need to create a new entry if it doesn't exist yet *and* update
       * the 'parent' interface with the new records.
       */
        *name_colonP = 0;
931
        if (getFlags(sock, name, &flags) < 0 || flags < 0) {
932 933 934 935 936 937 938 939 940 941 942 943
            // failed to access parent interface do not create parent.
            // We are a virtual interface with no parent.
            isVirtual = 1;
            *name_colonP = ':';
        }
        else{
           // Got access to parent, so create it if necessary.
           // Save original name to vname and truncate name by ':'
            memcpy(vname, name, sizeof(vname) );
            vname[name_colonP - name] = ':';
        }
    }
D
duke 已提交
944 945

    /*
946 947 948
     * Check if this is a "new" interface. Use the interface
     * name for matching because index isn't supported on
     * Solaris 2.6 & 7.
D
duke 已提交
949
     */
950 951 952 953 954
    while (currif != NULL) {
        if (strcmp(name, currif->name) == 0) {
            break;
        }
        currif = currif->next;
D
duke 已提交
955
    }
956 957 958 959 960 961

    /*
     * If "new" then create an netif structure and
     * insert it onto the list.
     */
    if (currif == NULL) {
962
         CHECKED_MALLOC3(currif, netif *, sizeof(netif) + ifnam_size);
963
         currif->name = (char *) currif+sizeof(netif);
964 965
         strncpy(currif->name, name, ifnam_size);
         currif->name[ifnam_size - 1] = '\0';
966
         currif->index = getIndex(sock, name);
967 968 969 970 971
         currif->addr = NULL;
         currif->childs = NULL;
         currif->virtual = isVirtual;
         currif->next = ifs;
         ifs = currif;
D
duke 已提交
972 973 974
    }

    /*
975
     * Finally insert the address on the interface
D
duke 已提交
976
     */
977 978
    addrP->next = currif->addr;
    currif->addr = addrP;
D
duke 已提交
979

980 981 982 983 984 985 986 987 988 989 990 991 992 993 994
    parent = currif;

    /**
     * Let's deal with the virtual interface now.
     */
    if (vname[0]) {
        netaddr *tmpaddr;

        currif = parent->childs;

        while (currif != NULL) {
            if (strcmp(vname, currif->name) == 0) {
                break;
            }
            currif = currif->next;
D
duke 已提交
995 996
        }

997
        if (currif == NULL) {
998
            CHECKED_MALLOC3(currif, netif *, sizeof(netif) + ifnam_size);
999
            currif->name = (char *) currif + sizeof(netif);
1000 1001
            strncpy(currif->name, vname, ifnam_size);
            currif->name[ifnam_size - 1] = '\0';
1002
            currif->index = getIndex(sock, vname);
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
            currif->addr = NULL;
           /* Need to duplicate the addr entry? */
            currif->virtual = 1;
            currif->childs = NULL;
            currif->next = parent->childs;
            parent->childs = currif;
        }

        CHECKED_MALLOC3(tmpaddr, netaddr *, sizeof(netaddr)+2*addr_size);
        memcpy(tmpaddr, addrP, sizeof(netaddr));
        if (addrP->addr != NULL) {
            tmpaddr->addr = (struct sockaddr *) ( (char*)tmpaddr + sizeof(netaddr) ) ;
            memcpy(tmpaddr->addr, addrP->addr, addr_size);
        }

        if (addrP->brdcast != NULL) {
            tmpaddr->brdcast = (struct sockaddr *) ((char *) tmpaddr + sizeof(netaddr)+addr_size);
            memcpy(tmpaddr->brdcast, addrP->brdcast, addr_size);
        }

        tmpaddr->next = currif->addr;
        currif->addr = tmpaddr;
    }

    return ifs;
}

/* Open socket for further ioct calls
 * proto is AF_INET/AF_INET6
 */
static int  openSocket(JNIEnv *env, int proto){
    int sock;

    if ((sock = JVM_Socket(proto, SOCK_DGRAM, 0)) < 0) {
D
duke 已提交
1037
        /*
1038 1039
         * If EPROTONOSUPPORT is returned it means we don't have
         * support  for this proto so don't throw an exception.
D
duke 已提交
1040
         */
1041 1042
        if (errno != EPROTONOSUPPORT) {
            NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "Socket creation failed");
D
duke 已提交
1043
        }
1044 1045
        return -1;
    }
D
duke 已提交
1046

1047 1048 1049 1050
    return sock;
}


1051 1052
/** Linux, AIX **/
#if defined(__linux__) || defined(_AIX)
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
/* Open socket for further ioct calls, try v4 socket first and
 * if it falls return v6 socket
 */

#ifdef AF_INET6
static int openSocketWithFallback(JNIEnv *env, const char *ifname){
    int sock;
    struct ifreq if2;

     if ((sock = JVM_Socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
         if (errno == EPROTONOSUPPORT){
              if ( (sock = JVM_Socket(AF_INET6, SOCK_DGRAM, 0)) < 0 ){
                 NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
                 return -1;
              }
         }
         else{ // errno is not NOSUPPORT
             NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "IPV4 Socket creation failed");
             return -1;
         }
   }

     /* Linux starting from 2.6.? kernel allows ioctl call with either IPv4 or IPv6 socket regardless of type
        of address of an interface */

       return sock;
}

#else
static int openSocketWithFallback(JNIEnv *env, const char *ifname){
    return openSocket(env,AF_INET);
}
#endif

static netif *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs) {
    struct ifconf ifc;
    struct ifreq *ifreqP;
1090
    char *buf = NULL;
1091 1092
    int numifs;
    unsigned i;
1093
    int siocgifconfRequest = SIOCGIFCONF;
1094 1095


1096
#if defined(__linux__)
1097 1098 1099 1100 1101 1102 1103 1104
    /* need to do a dummy SIOCGIFCONF to determine the buffer size.
     * SIOCGIFCOUNT doesn't work
     */
    ifc.ifc_buf = NULL;
    if (ioctl(sock, SIOCGIFCONF, (char *)&ifc) < 0) {
        NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "ioctl SIOCGIFCONF failed");
        return ifs;
    }
1105 1106 1107 1108 1109 1110 1111
#elif defined(_AIX)
    ifc.ifc_buf = NULL;
    if (ioctl(sock, SIOCGSIZIFCONF, &(ifc.ifc_len)) < 0) {
        NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "ioctl SIOCGSIZIFCONF failed");
        return ifs;
    }
#endif /* __linux__ */
1112 1113 1114 1115

    CHECKED_MALLOC3(buf,char *, ifc.ifc_len);

    ifc.ifc_buf = buf;
1116 1117 1118 1119
#if defined(_AIX)
    siocgifconfRequest = CSIOCGIFCONF;
#endif
    if (ioctl(sock, siocgifconfRequest, (char *)&ifc) < 0) {
1120 1121 1122 1123
        NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "ioctl SIOCGIFCONF failed");
        (void) free(buf);
        return ifs;
    }
D
duke 已提交
1124

1125 1126 1127 1128 1129
    /*
     * Iterate through each interface
     */
    ifreqP = ifc.ifc_req;
    for (i=0; i<ifc.ifc_len/sizeof (struct ifreq); i++, ifreqP++) {
1130 1131 1132
#if defined(_AIX)
        if (ifreqP->ifr_addr.sa_family != AF_INET) continue;
#endif
D
duke 已提交
1133
        /*
1134 1135 1136 1137 1138 1139
         * Add to the list
         */
        ifs = addif(env, sock, ifreqP->ifr_name, ifs, (struct sockaddr *) & (ifreqP->ifr_addr), AF_INET, 0);

        /*
         * If an exception occurred then free the list
D
duke 已提交
1140 1141 1142
         */
        if ((*env)->ExceptionOccurred(env)) {
            free(buf);
1143 1144
            freeif(ifs);
            return NULL;
D
duke 已提交
1145 1146 1147
        }
    }

1148 1149 1150
    /*
     * Free socket and buffer
     */
D
duke 已提交
1151 1152 1153 1154 1155 1156 1157 1158
    free(buf);
    return ifs;
}


/*
 * Enumerates and returns all IPv6 interfaces on Linux
 */
1159

1160
#if defined(AF_INET6) && defined(__linux__)
1161
static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
D
duke 已提交
1162
    FILE *f;
1163
    char addr6[40], devname[21];
D
duke 已提交
1164 1165 1166 1167 1168
    char addr6p[8][5];
    int plen, scope, dad_status, if_idx;
    uint8_t ipv6addr[16];

    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 1171 1172 1173 1174
                         addr6p[0], addr6p[1], addr6p[2], addr6p[3], addr6p[4], addr6p[5], addr6p[6], addr6p[7],
                         &if_idx, &plen, &scope, &dad_status, devname) != EOF) {

            struct netif *ifs_ptr = NULL;
            struct netif *last_ptr = NULL;
D
duke 已提交
1175 1176 1177
            struct sockaddr_in6 addr;

            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]);
D
duke 已提交
1179 1180 1181 1182
            inet_pton(AF_INET6, addr6, ipv6addr);

            memset(&addr, 0, sizeof(struct sockaddr_in6));
            memcpy((void*)addr.sin6_addr.s6_addr, (const void*)ipv6addr, 16);
1183

D
duke 已提交
1184 1185
            addr.sin6_scope_id = if_idx;

1186 1187
            ifs = addif(env, sock, devname, ifs, (struct sockaddr *)&addr, AF_INET6, plen);

D
duke 已提交
1188 1189 1190 1191 1192 1193 1194 1195

            /*
             * If an exception occurred then return the list as is.
             */
            if ((*env)->ExceptionOccurred(env)) {
                fclose(f);
                return ifs;
            }
1196 1197
       }
       fclose(f);
D
duke 已提交
1198 1199 1200 1201 1202 1203
    }
    return ifs;
}
#endif


1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
/*
 * Enumerates and returns all IPv6 interfaces on AIX
 */

#if defined(AF_INET6) && defined(_AIX)
static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
    struct ifconf ifc;
    struct ifreq *ifreqP;
    char *buf;
    int numifs;
    unsigned i;
    unsigned bufsize;
    char *cp, *cplimit;

    /* use SIOCGSIZIFCONF to get size for  SIOCGIFCONF */

    ifc.ifc_buf = NULL;
    if (ioctl(sock, SIOCGSIZIFCONF, &(ifc.ifc_len)) < 0) {
        NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException",
                        "ioctl SIOCGSIZIFCONF failed");
        return ifs;
    }
    bufsize = ifc.ifc_len;

    buf = (char *)malloc(bufsize);
    if (!buf) {
        JNU_ThrowOutOfMemoryError(env, "Network interface native buffer allocation failed");
        return ifs;
    }
    ifc.ifc_len = bufsize;
    ifc.ifc_buf = buf;
    if (ioctl(sock, SIOCGIFCONF, (char *)&ifc) < 0) {
        NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException",
                       "ioctl CSIOCGIFCONF failed");
        free(buf);
        return ifs;
    }

    /*
     * Iterate through each interface
     */
    ifreqP = ifc.ifc_req;
    cp = (char *)ifc.ifc_req;
    cplimit = cp + ifc.ifc_len;

    for ( ; cp < cplimit; cp += (sizeof(ifreqP->ifr_name) + MAX((ifreqP->ifr_addr).sa_len, sizeof(ifreqP->ifr_addr)))) {
        ifreqP = (struct ifreq *)cp;
        struct ifreq if2;

        memset((char *)&if2, 0, sizeof(if2));
        strcpy(if2.ifr_name, ifreqP->ifr_name);

        /*
         * Skip interface that aren't UP
         */
        if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) >= 0) {
            if (!(if2.ifr_flags & IFF_UP)) {
                continue;
            }
        }

        if (ifreqP->ifr_addr.sa_family != AF_INET6)
            continue;

1268 1269 1270 1271 1272
        if (ioctl(sock, SIOCGIFSITE6, (char *)&if2) >= 0) {
            struct sockaddr_in6 *s6= (struct sockaddr_in6 *)&(ifreqP->ifr_addr);
            s6->sin6_scope_id = if2.ifr_site6;
        }

1273 1274 1275 1276 1277
        /*
         * Add to the list
         */
        ifs = addif(env, sock, ifreqP->ifr_name, ifs,
                    (struct sockaddr *)&(ifreqP->ifr_addr),
1278
                    AF_INET6, 0);
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298

        /*
         * If an exception occurred then free the list
         */
        if ((*env)->ExceptionOccurred(env)) {
            free(buf);
            freeif(ifs);
            return NULL;
        }
    }

    /*
     * Free socket and buffer
     */
    free(buf);
    return ifs;
}
#endif


1299
static int getIndex(int sock, const char *name){
1300 1301 1302
     /*
      * Try to get the interface index
      */
1303 1304 1305
#if defined(_AIX)
    return if_nametoindex(name);
#else
1306 1307 1308 1309 1310 1311 1312 1313
    struct ifreq if2;
    strcpy(if2.ifr_name, name);

    if (ioctl(sock, SIOCGIFINDEX, (char *)&if2) < 0) {
        return -1;
    }

    return if2.ifr_ifindex;
1314
#endif
1315 1316 1317 1318 1319
}

/**
 * Returns the IPv4 broadcast address of a named interface, if it exists.
 * Returns 0 if it doesn't have one.
D
duke 已提交
1320
 */
1321 1322 1323
static struct sockaddr *getBroadcast(JNIEnv *env, int sock, const char *ifname, struct sockaddr *brdcast_store) {
  struct sockaddr *ret = NULL;
  struct ifreq if2;
D
duke 已提交
1324

1325 1326
  memset((char *) &if2, 0, sizeof(if2));
  strcpy(if2.ifr_name, ifname);
D
duke 已提交
1327

1328 1329 1330 1331 1332
  /* Let's make sure the interface does have a broadcast address */
  if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2)  < 0) {
      NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL  SIOCGIFFLAGS failed");
      return ret;
  }
D
duke 已提交
1333

1334 1335 1336 1337 1338 1339
  if (if2.ifr_flags & IFF_BROADCAST) {
      /* It does, let's retrieve it*/
      if (ioctl(sock, SIOCGIFBRDADDR, (char *)&if2) < 0) {
          NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFBRDADDR failed");
          return ret;
      }
D
duke 已提交
1340

1341 1342 1343 1344 1345
      ret = brdcast_store;
      memcpy(ret, &if2.ifr_broadaddr, sizeof(struct sockaddr));
  }

  return ret;
D
duke 已提交
1346 1347
}

1348 1349 1350
/**
 * Returns the IPv4 subnet prefix length (aka subnet mask) for the named
 * interface, if it has one, otherwise return -1.
D
duke 已提交
1351
 */
1352 1353 1354 1355
static short getSubnet(JNIEnv *env, int sock, const char *ifname) {
    unsigned int mask;
    short ret;
    struct ifreq if2;
D
duke 已提交
1356

1357 1358
    memset((char *) &if2, 0, sizeof(if2));
    strcpy(if2.ifr_name, ifname);
D
duke 已提交
1359

1360 1361 1362
    if (ioctl(sock, SIOCGIFNETMASK, (char *)&if2) < 0) {
        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFNETMASK failed");
        return -1;
D
duke 已提交
1363
    }
1364 1365 1366 1367 1368 1369

    mask = ntohl(((struct sockaddr_in*)&(if2.ifr_addr))->sin_addr.s_addr);
    ret = 0;
    while (mask) {
       mask <<= 1;
       ret++;
D
duke 已提交
1370 1371
    }

1372 1373 1374 1375 1376 1377 1378 1379 1380
    return ret;
}

/**
 * Get the Hardware address (usually MAC address) for the named interface.
 * return puts the data in buf, and returns the length, in byte, of the
 * MAC address. Returns -1 if there is no hardware address on that interface.
 */
static int getMacAddress(JNIEnv *env, int sock, const char* ifname, const struct in_addr* addr, unsigned char *buf) {
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
#if defined (_AIX)
    int size;
    struct kinfo_ndd *nddp;
    void *end;

    size = getkerninfo(KINFO_NDD, 0, 0, 0);
    if (size == 0) {
        return -1;
    }

    if (size < 0) {
        perror("getkerninfo 1");
        return -1;
    }

    nddp = (struct kinfo_ndd *)malloc(size);

    if (!nddp) {
        return -1;
    }

    if (getkerninfo(KINFO_NDD, nddp, &size, 0) < 0) {
        perror("getkerninfo 2");
        return -1;
    }

    end = (void *)nddp + size;
    while ((void *)nddp < end) {
        if (!strcmp(nddp->ndd_alias, ifname) ||
                !strcmp(nddp->ndd_name, ifname)) {
            bcopy(nddp->ndd_addr, buf, 6);
            return 6;
        } else {
            nddp++;
        }
    }

    return -1;

#elif defined(__linux__)
1421 1422 1423 1424 1425 1426 1427
    static struct ifreq ifr;
    int i;

    strcpy(ifr.ifr_name, ifname);
    if (ioctl(sock, SIOCGIFHWADDR, &ifr) < 0) {
        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFHWADDR failed");
        return -1;
D
duke 已提交
1428 1429
    }

1430 1431 1432 1433 1434
    memcpy(buf, &ifr.ifr_hwaddr.sa_data, IFHWADDRLEN);

   /*
    * All bytes to 0 means no hardware address.
    */
D
duke 已提交
1435

1436 1437 1438 1439 1440 1441
    for (i = 0; i < IFHWADDRLEN; i++) {
        if (buf[i] != 0)
            return IFHWADDRLEN;
    }

    return -1;
1442
#endif
1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
}

static int getMTU(JNIEnv *env, int sock,  const char *ifname) {
    struct ifreq if2;

    memset((char *) &if2, 0, sizeof(if2));
    strcpy(if2.ifr_name, ifname);

    if (ioctl(sock, SIOCGIFMTU, (char *)&if2) < 0) {
        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFMTU failed");
        return -1;
    }

    return  if2.ifr_mtu;
}
D
duke 已提交
1458

1459
static int getFlags(int sock, const char *ifname, int *flags) {
1460 1461 1462 1463 1464 1465 1466 1467 1468
  struct ifreq if2;

  memset((char *) &if2, 0, sizeof(if2));
  strcpy(if2.ifr_name, ifname);

  if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) < 0){
      return -1;
  }

1469 1470 1471 1472 1473 1474
  if (sizeof(if2.ifr_flags) == sizeof(short)) {
      *flags = (if2.ifr_flags & 0xffff);
  } else {
      *flags = if2.ifr_flags;
  }
  return 0;
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505
}

#endif

/** Solaris **/
#ifdef __solaris__
/* Open socket for further ioct calls, try v4 socket first and
 * if it falls return v6 socket
 */

#ifdef AF_INET6
static int openSocketWithFallback(JNIEnv *env, const char *ifname){
    int sock, alreadyV6 = 0;
    struct lifreq if2;

     if ((sock = JVM_Socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
         if (errno == EPROTONOSUPPORT){
              if ( (sock = JVM_Socket(AF_INET6, SOCK_DGRAM, 0)) < 0 ){
                 NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
                 return -1;
              }

              alreadyV6=1;
         }
         else{ // errno is not NOSUPPORT
             NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "IPV4 Socket creation failed");
             return -1;
         }
   }

     /**
1506 1507 1508 1509 1510 1511 1512
      * Solaris requires that we have an IPv6 socket to query an
      * interface without an IPv4 address - check it here.
      * POSIX 1 require the kernel to return ENOTTY if the call is
      * inappropriate for a device e.g. the NETMASK for a device having IPv6
      * only address but not all devices follow the standard so
      * fall back on any error. It's not an ecologically friendly gesture
      * but more reliable.
1513 1514 1515
      */

    if (! alreadyV6 ){
D
duke 已提交
1516
        memset((char *) &if2, 0, sizeof(if2));
1517 1518 1519 1520 1521 1522 1523 1524 1525
        strcpy(if2.lifr_name, ifname);
        if (ioctl(sock, SIOCGLIFNETMASK, (char *)&if2) < 0) {
                close(sock);
                if ( (sock = JVM_Socket(AF_INET6, SOCK_DGRAM, 0)) < 0 ){
                      NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
                      return -1;
                }
        }
    }
D
duke 已提交
1526

1527 1528
    return sock;
}
1529 1530

#else
1531 1532 1533 1534 1535 1536 1537
static int openSocketWithFallback(JNIEnv *env, const char *ifname){
    return openSocket(env,AF_INET);
}
#endif

/*
 * Enumerates and returns all IPv4 interfaces
1538
 * (linux verision)
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548
 */

static netif *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs) {
     return enumIPvXInterfaces(env,sock, ifs, AF_INET);
}

#ifdef AF_INET6
static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
    return enumIPvXInterfaces(env,sock, ifs, AF_INET6);
}
1549
#endif
1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561

/*
   Enumerates and returns all interfaces on Solaris
   use the same code for IPv4 and IPv6
 */
static netif *enumIPvXInterfaces(JNIEnv *env, int sock, netif *ifs, int family) {
    struct lifconf ifc;
    struct lifreq *ifr;
    int n;
    char *buf;
    struct lifnum numifs;
    unsigned bufsize;
D
duke 已提交
1562 1563

    /*
1564
     * Get the interface count
D
duke 已提交
1565
     */
1566 1567 1568 1569 1570
    numifs.lifn_family = family;
    numifs.lifn_flags = 0;
    if (ioctl(sock, SIOCGLIFNUM, (char *)&numifs) < 0) {
        NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "ioctl SIOCGLIFNUM failed");
        return ifs;
D
duke 已提交
1571 1572 1573
    }

    /*
1574
     *  Enumerate the interface configurations
D
duke 已提交
1575
     */
1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586
    bufsize = numifs.lifn_count * sizeof (struct lifreq);
    CHECKED_MALLOC3(buf, char *, bufsize);

    ifc.lifc_family = family;
    ifc.lifc_flags = 0;
    ifc.lifc_len = bufsize;
    ifc.lifc_buf = buf;
    if (ioctl(sock, SIOCGLIFCONF, (char *)&ifc) < 0) {
        NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "ioctl SIOCGLIFCONF failed");
        free(buf);
        return ifs;
D
duke 已提交
1587 1588 1589
    }

    /*
1590
     * Iterate through each interface
D
duke 已提交
1591
     */
1592 1593 1594 1595
    ifr = ifc.lifc_req;
    for (n=0; n<numifs.lifn_count; n++, ifr++) {
        int index = -1;
        struct lifreq if2;
D
duke 已提交
1596

1597 1598 1599 1600 1601 1602
        /*
        * Ignore either IPv4 or IPv6 addresses
        */
        if (ifr->lifr_addr.ss_family != family) {
            continue;
        }
D
duke 已提交
1603

1604 1605 1606 1607 1608 1609 1610
#ifdef AF_INET6
        if (ifr->lifr_addr.ss_family == AF_INET6) {
            struct sockaddr_in6 *s6= (struct sockaddr_in6 *)&(ifr->lifr_addr);
            s6->sin6_scope_id = getIndex(sock, ifr->lifr_name);
        }
#endif

1611 1612
        /* add to the list */
        ifs = addif(env, sock,ifr->lifr_name, ifs, (struct sockaddr *)&(ifr->lifr_addr),family, (short) ifr->lifr_addrlen);
D
duke 已提交
1613

1614 1615 1616 1617 1618 1619
        /*
        * If an exception occurred we return immediately
        */
        if ((*env)->ExceptionOccurred(env)) {
            free(buf);
            return ifs;
D
duke 已提交
1620 1621
        }

1622
   }
D
duke 已提交
1623

1624
    free(buf);
D
duke 已提交
1625 1626 1627
    return ifs;
}

1628
static int getIndex(int sock, const char *name){
1629 1630 1631 1632 1633 1634
   /*
    * Try to get the interface index
    * (Not supported on Solaris 2.6 or 7)
    */
    struct lifreq if2;
    strcpy(if2.lifr_name, name);
1635

1636 1637
    if (ioctl(sock, SIOCGLIFINDEX, (char *)&if2) < 0) {
        return -1;
1638
    }
D
duke 已提交
1639

1640
    return if2.lifr_index;
D
duke 已提交
1641 1642 1643 1644 1645 1646
}

/**
 * Returns the IPv4 broadcast address of a named interface, if it exists.
 * Returns 0 if it doesn't have one.
 */
1647 1648 1649
static struct sockaddr *getBroadcast(JNIEnv *env, int sock, const char *ifname, struct sockaddr *brdcast_store) {
    struct sockaddr *ret = NULL;
    struct lifreq if2;
D
duke 已提交
1650

1651 1652
    memset((char *) &if2, 0, sizeof(if2));
    strcpy(if2.lifr_name, ifname);
D
duke 已提交
1653

1654 1655 1656 1657
    /* Let's make sure the interface does have a broadcast address */
    if (ioctl(sock, SIOCGLIFFLAGS, (char *)&if2)  < 0) {
        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL  SIOCGLIFFLAGS failed");
        return ret;
D
duke 已提交
1658
    }
1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671

    if (if2.lifr_flags & IFF_BROADCAST) {
        /* It does, let's retrieve it*/
        if (ioctl(sock, SIOCGLIFBRDADDR, (char *)&if2) < 0) {
            NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGLIFBRDADDR failed");
            return ret;
        }

        ret = brdcast_store;
        memcpy(ret, &if2.lifr_broadaddr, sizeof(struct sockaddr));
    }

    return ret;
D
duke 已提交
1672 1673 1674 1675 1676 1677
}

/**
 * Returns the IPv4 subnet prefix length (aka subnet mask) for the named
 * interface, if it has one, otherwise return -1.
 */
1678 1679 1680 1681
static short getSubnet(JNIEnv *env, int sock, const char *ifname) {
    unsigned int mask;
    short ret;
    struct lifreq if2;
D
duke 已提交
1682

1683 1684
    memset((char *) &if2, 0, sizeof(if2));
    strcpy(if2.lifr_name, ifname);
D
duke 已提交
1685

1686 1687 1688 1689 1690 1691
    if (ioctl(sock, SIOCGLIFNETMASK, (char *)&if2) < 0) {
        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGLIFNETMASK failed");
        return -1;
    }

    mask = ntohl(((struct sockaddr_in*)&(if2.lifr_addr))->sin_addr.s_addr);
D
duke 已提交
1692
    ret = 0;
1693

D
duke 已提交
1694
    while (mask) {
1695 1696
       mask <<= 1;
       ret++;
D
duke 已提交
1697
    }
1698

D
duke 已提交
1699 1700 1701
    return ret;
}

1702 1703 1704


#define DEV_PREFIX  "/dev/"
D
duke 已提交
1705 1706 1707 1708 1709 1710 1711

/**
 * Solaris specific DLPI code to get hardware address from a device.
 * Unfortunately, at least up to Solaris X, you have to have special
 * privileges (i.e. be root).
 */
static int getMacFromDevice(JNIEnv *env, const char* ifname, unsigned char* retbuf) {
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758
    char style1dev[MAXPATHLEN];
    int fd;
    dl_phys_addr_req_t dlpareq;
    dl_phys_addr_ack_t *dlpaack;
    struct strbuf msg;
    char buf[128];
    int flags = 0;

   /**
    * Device is in /dev
    * e.g.: /dev/bge0
    */
    strcpy(style1dev, DEV_PREFIX);
    strcat(style1dev, ifname);
    if ((fd = open(style1dev, O_RDWR)) < 0) {
        /*
         * Can't open it. We probably are missing the privilege.
         * We'll have to try something else
         */
         return 0;
    }

    dlpareq.dl_primitive = DL_PHYS_ADDR_REQ;
    dlpareq.dl_addr_type = DL_CURR_PHYS_ADDR;

    msg.buf = (char *)&dlpareq;
    msg.len = DL_PHYS_ADDR_REQ_SIZE;

    if (putmsg(fd, &msg, NULL, 0) < 0) {
        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "putmsg failed");
        return -1;
    }

    dlpaack = (dl_phys_addr_ack_t *)buf;

    msg.buf = (char *)buf;
    msg.len = 0;
    msg.maxlen = sizeof (buf);
    if (getmsg(fd, &msg, NULL, &flags) < 0) {
        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "getmsg failed");
        return -1;
    }

    if (msg.len < DL_PHYS_ADDR_ACK_SIZE || dlpaack->dl_primitive != DL_PHYS_ADDR_ACK) {
        JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", "Couldn't obtain phys addr\n");
        return -1;
    }
D
duke 已提交
1759

1760 1761
    memcpy(retbuf, &buf[dlpaack->dl_addr_offset], dlpaack->dl_addr_length);
    return dlpaack->dl_addr_length;
D
duke 已提交
1762 1763 1764 1765 1766 1767 1768
}

/**
 * Get the Hardware address (usually MAC address) for the named interface.
 * return puts the data in buf, and returns the length, in byte, of the
 * MAC address. Returns -1 if there is no hardware address on that interface.
 */
1769 1770 1771 1772 1773
static int getMacAddress(JNIEnv *env, int sock, const char *ifname,  const struct in_addr* addr, unsigned char *buf) {
    struct arpreq arpreq;
    struct sockaddr_in* sin;
    struct sockaddr_in ipAddr;
    int len, i;
1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787
    struct lifreq lif;

    /* First, try the new (S11) SIOCGLIFHWADDR ioctl(). If that fails
     * try the old way.
     */
    memset(&lif, 0, sizeof(lif));
    strlcpy(lif.lifr_name, ifname, sizeof(lif.lifr_name));

    if (ioctl(sock, SIOCGLIFHWADDR, &lif) != -1) {
        struct sockaddr_dl *sp;
        sp = (struct sockaddr_dl *)&lif.lifr_addr;
        memcpy(buf, &sp->sdl_data[0], sp->sdl_alen);
        return sp->sdl_alen;
    }
1788 1789 1790 1791 1792 1793 1794 1795 1796

   /**
    * On Solaris we have to use DLPI, but it will only work if we have
    * privileged access (i.e. root). If that fails, we try a lookup
    * in the ARP table, which requires an IPv4 address.
    */
    if ((len = getMacFromDevice(env, ifname, buf))  == 0) {
        /*DLPI failed - trying to do arp lookup*/

1797 1798 1799 1800 1801 1802
        if (addr == NULL) {
            /**
             * No IPv4 address for that interface, so can't do an ARP lookup.
             */
             return -1;
         }
D
duke 已提交
1803

1804
         len = 6; //???
D
duke 已提交
1805

1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819
         sin = (struct sockaddr_in *) &arpreq.arp_pa;
         memset((char *) &arpreq, 0, sizeof(struct arpreq));
         ipAddr.sin_port = 0;
         ipAddr.sin_family = AF_INET;
         memcpy(&ipAddr.sin_addr, addr, sizeof(struct in_addr));
         memcpy(&arpreq.arp_pa, &ipAddr, sizeof(struct sockaddr_in));
         arpreq.arp_flags= ATF_PUBL;

         if (ioctl(sock, SIOCGARP, &arpreq) < 0) {
             return -1;
         }

         memcpy(buf, &arpreq.arp_ha.sa_data[0], len );
    }
D
duke 已提交
1820

1821 1822
    /*
     * All bytes to 0 means no hardware address.
D
duke 已提交
1823 1824
     */

1825 1826 1827 1828
    for (i = 0; i < len; i++) {
      if (buf[i] != 0)
         return len;
    }
D
duke 已提交
1829

1830
    return -1;
D
duke 已提交
1831 1832
}

1833 1834
static int getMTU(JNIEnv *env, int sock,  const char *ifname) {
    struct lifreq if2;
D
duke 已提交
1835

1836 1837
    memset((char *) &if2, 0, sizeof(if2));
    strcpy(if2.lifr_name, ifname);
D
duke 已提交
1838

1839 1840 1841 1842
    if (ioctl(sock, SIOCGLIFMTU, (char *)&if2) < 0) {
        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGLIFMTU failed");
        return -1;
    }
D
duke 已提交
1843

1844
    return  if2.lifr_mtu;
D
duke 已提交
1845 1846 1847
}


1848
static int getFlags(int sock, const char *ifname, int *flags) {
1849 1850 1851
     struct   lifreq lifr;
     memset((caddr_t)&lifr, 0, sizeof(lifr));
     strcpy((caddr_t)&(lifr.lifr_name), ifname);
D
duke 已提交
1852

1853 1854 1855
     if (ioctl(sock, SIOCGLIFFLAGS, (char *)&lifr) < 0) {
         return -1;
     }
D
duke 已提交
1856

1857 1858
     *flags = lifr.lifr_flags;
     return 0;
1859
}
D
duke 已提交
1860 1861


1862
#endif
1863 1864


1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153
/** BSD **/
#ifdef _ALLBSD_SOURCE
/* Open socket for further ioct calls, try v4 socket first and
 * if it falls return v6 socket
 */

#ifdef AF_INET6
static int openSocketWithFallback(JNIEnv *env, const char *ifname){
    int sock;
    struct ifreq if2;

     if ((sock = JVM_Socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
         if (errno == EPROTONOSUPPORT){
              if ( (sock = JVM_Socket(AF_INET6, SOCK_DGRAM, 0)) < 0 ){
                 NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
                 return -1;
              }
         }
         else{ // errno is not NOSUPPORT
             NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "IPV4 Socket creation failed");
             return -1;
         }
   }

   return sock;
}

#else
static int openSocketWithFallback(JNIEnv *env, const char *ifname){
    return openSocket(env,AF_INET);
}
#endif

/*
 * Enumerates and returns all IPv4 interfaces
 */
static netif *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs) {
    struct ifaddrs *ifa, *origifa;

    if (getifaddrs(&origifa) != 0) {
        NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException",
                         "getifaddrs() function failed");
        return ifs;
    }

    for (ifa = origifa; ifa != NULL; ifa = ifa->ifa_next) {

        /*
         * Skip non-AF_INET entries.
         */
        if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != AF_INET)
            continue;

        /*
         * Add to the list.
         */
        ifs = addif(env, sock, ifa->ifa_name, ifs, ifa->ifa_addr, AF_INET, 0);

        /*
         * If an exception occurred then free the list.
         */
        if ((*env)->ExceptionOccurred(env)) {
            freeifaddrs(origifa);
            freeif(ifs);
            return NULL;
        }
    }

    /*
     * Free socket and buffer
     */
    freeifaddrs(origifa);
    return ifs;
}


/*
 * Enumerates and returns all IPv6 interfaces on Linux
 */

#ifdef AF_INET6
/*
 * Determines the prefix on BSD for IPv6 interfaces.
 */
static
int prefix(void *val, int size) {
    u_char *name = (u_char *)val;
    int byte, bit, plen = 0;

    for (byte = 0; byte < size; byte++, plen += 8)
        if (name[byte] != 0xff)
            break;
    if (byte == size)
        return (plen);
    for (bit = 7; bit != 0; bit--, plen++)
        if (!(name[byte] & (1 << bit)))
            break;
    for (; bit != 0; bit--)
        if (name[byte] & (1 << bit))
            return (0);
    byte++;
    for (; byte < size; byte++)
        if (name[byte])
            return (0);
    return (plen);
}

/*
 * Enumerates and returns all IPv6 interfaces on BSD
 */
static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
    struct ifaddrs *ifa, *origifa;
    struct sockaddr_in6 *sin6;
    struct in6_ifreq ifr6;

    if (getifaddrs(&origifa) != 0) {
        NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException",
                         "getifaddrs() function failed");
        return ifs;
    }

    for (ifa = origifa; ifa != NULL; ifa = ifa->ifa_next) {

        /*
         * Skip non-AF_INET6 entries.
         */
        if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != AF_INET6)
            continue;

        memset(&ifr6, 0, sizeof(ifr6));
        strlcpy(ifr6.ifr_name, ifa->ifa_name, sizeof(ifr6.ifr_name));
        memcpy(&ifr6.ifr_addr, ifa->ifa_addr, MIN(sizeof(ifr6.ifr_addr), ifa->ifa_addr->sa_len));

        if (ioctl(sock, SIOCGIFNETMASK_IN6, (caddr_t)&ifr6) < 0) {
            NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException",
                             "ioctl SIOCGIFNETMASK_IN6 failed");
            freeifaddrs(origifa);
            freeif(ifs);
            return NULL;
        }

        /* Add to the list.  */
        sin6 = (struct sockaddr_in6 *)&ifr6.ifr_addr;
        ifs = addif(env, sock, ifa->ifa_name, ifs, ifa->ifa_addr, AF_INET6,
                    prefix(&sin6->sin6_addr, sizeof(struct in6_addr)));

        /* If an exception occurred then free the list.  */
        if ((*env)->ExceptionOccurred(env)) {
            freeifaddrs(origifa);
            freeif(ifs);
            return NULL;
        }
    }

    /*
     * Free socket and ifaddrs buffer
     */
    freeifaddrs(origifa);
    return ifs;
}
#endif

static int getIndex(int sock, const char *name){
#ifdef __FreeBSD__
     /*
      * Try to get the interface index
      * (Not supported on Solaris 2.6 or 7)
      */
    struct ifreq if2;
    strcpy(if2.ifr_name, name);

    if (ioctl(sock, SIOCGIFINDEX, (char *)&if2) < 0) {
        return -1;
    }

    return if2.ifr_index;
#else
    /*
     * Try to get the interface index using BSD specific if_nametoindex
     */
    int index = if_nametoindex(name);
    return (index == 0) ? -1 : index;
#endif
}

/**
 * Returns the IPv4 broadcast address of a named interface, if it exists.
 * Returns 0 if it doesn't have one.
 */
static struct sockaddr *getBroadcast(JNIEnv *env, int sock, const char *ifname, struct sockaddr *brdcast_store) {
  struct sockaddr *ret = NULL;
  struct ifreq if2;

  memset((char *) &if2, 0, sizeof(if2));
  strcpy(if2.ifr_name, ifname);

  /* Let's make sure the interface does have a broadcast address */
  if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) < 0) {
      NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFFLAGS failed");
      return ret;
  }

  if (if2.ifr_flags & IFF_BROADCAST) {
      /* It does, let's retrieve it*/
      if (ioctl(sock, SIOCGIFBRDADDR, (char *)&if2) < 0) {
          NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFBRDADDR failed");
          return ret;
      }

      ret = brdcast_store;
      memcpy(ret, &if2.ifr_broadaddr, sizeof(struct sockaddr));
  }

  return ret;
}

/**
 * Returns the IPv4 subnet prefix length (aka subnet mask) for the named
 * interface, if it has one, otherwise return -1.
 */
static short getSubnet(JNIEnv *env, int sock, const char *ifname) {
    unsigned int mask;
    short ret;
    struct ifreq if2;

    memset((char *) &if2, 0, sizeof(if2));
    strcpy(if2.ifr_name, ifname);

    if (ioctl(sock, SIOCGIFNETMASK, (char *)&if2) < 0) {
        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFNETMASK failed");
        return -1;
    }

    mask = ntohl(((struct sockaddr_in*)&(if2.ifr_addr))->sin_addr.s_addr);
    ret = 0;
    while (mask) {
       mask <<= 1;
       ret++;
    }

    return ret;
}

/**
 * Get the Hardware address (usually MAC address) for the named interface.
 * return puts the data in buf, and returns the length, in byte, of the
 * MAC address. Returns -1 if there is no hardware address on that interface.
 */
static int getMacAddress(JNIEnv *env, int sock, const char* ifname, const struct in_addr* addr, unsigned char *buf) {
    struct ifaddrs *ifa0, *ifa;
    struct sockaddr *saddr;
    int i;

    /* Grab the interface list */
    if (!getifaddrs(&ifa0)) {
        /* Cycle through the interfaces */
        for (i = 0, ifa = ifa0; ifa != NULL; ifa = ifa->ifa_next, i++) {
            saddr = ifa->ifa_addr;
            /* Link layer contains the MAC address */
            if (saddr->sa_family == AF_LINK && !strcmp(ifname, ifa->ifa_name)) {
                struct sockaddr_dl *sadl = (struct sockaddr_dl *) saddr;
                /* Check the address is the correct length */
                if (sadl->sdl_alen == ETHER_ADDR_LEN) {
                    memcpy(buf, (sadl->sdl_data + sadl->sdl_nlen), ETHER_ADDR_LEN);
                    freeifaddrs(ifa0);
                    return ETHER_ADDR_LEN;
                }
            }
        }
        freeifaddrs(ifa0);
    }

    return -1;
}

static int getMTU(JNIEnv *env, int sock,  const char *ifname) {
    struct ifreq if2;

    memset((char *) &if2, 0, sizeof(if2));
    strcpy(if2.ifr_name, ifname);

    if (ioctl(sock, SIOCGIFMTU, (char *)&if2) < 0) {
        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFMTU failed");
        return -1;
    }

    return  if2.ifr_mtu;
}

2154
static int getFlags(int sock, const char *ifname, int *flags) {
2155 2156 2157 2158 2159 2160 2161 2162 2163 2164
  struct ifreq if2;
  int ret = -1;

  memset((char *) &if2, 0, sizeof(if2));
  strcpy(if2.ifr_name, ifname);

  if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) < 0){
      return -1;
  }

2165 2166 2167 2168 2169 2170
  if (sizeof(if2.ifr_flags) == sizeof(short)) {
    *flags = (if2.ifr_flags & 0xffff);
  } else {
    *flags = if2.ifr_flags;
  }
  return 0;
2171 2172 2173
}

#endif