NetworkInterface.c 29.9 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2000, 2008, 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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
 */

#include <stdlib.h>
#include <windows.h>
#include <winsock2.h>           /* needed for htonl */
#include <iprtrmib.h>
#include <assert.h>

#include "java_net_NetworkInterface.h"
#include "jni_util.h"

#include "NetworkInterface.h"

/*
 * Windows implementation of the java.net.NetworkInterface native methods.
 * This module provides the implementations of getAll, getByName, getByIndex,
 * and getByAddress.
 *
 * Interfaces and addresses are enumerated using the IP helper routines
 * GetIfTable, GetIfAddrTable resp. These routines are available on Windows
 * 98, NT SP+4, 2000, and XP. They are also available on Windows 95 if
 * IE is upgraded to 5.x.
 *
 * Windows does not have any standard for device names so we are forced
 * to use our own convention which is based on the normal Unix naming
 * convention ("lo" for the loopback, eth0, eth1, .. for ethernet devices,
 * tr0, tr1, .. for token ring, and so on). This convention gives us
 * consistency across multiple Windows editions and also consistency with
 * Solaris/Linux device names. Note that we always enumerate in index
 * order and this ensures consistent device number across invocations.
 */

/* various JNI ids */

jclass ni_class;            /* NetworkInterface */

jmethodID ni_ctor;          /* NetworkInterface() */

jfieldID ni_indexID;        /* NetworkInterface.index */
jfieldID ni_addrsID;        /* NetworkInterface.addrs */
jfieldID ni_bindsID;        /* NetworkInterface.bindings */
jfieldID ni_nameID;         /* NetworkInterface.name */
jfieldID ni_displayNameID;  /* NetworkInterface.displayName */
jfieldID ni_childsID;       /* NetworkInterface.childs */
jclass ni_iacls;            /* InetAddress */
jfieldID ni_iaAddr;         /* InetAddress.address */

jclass ni_ia4cls;           /* Inet4Address */
jmethodID ni_ia4Ctor;       /* Inet4Address() */

jclass ni_ia6cls;           /* Inet6Address */
jmethodID ni_ia6ctrID;      /* Inet6Address() */
jfieldID ni_ia6ipaddressID;
jfieldID ni_ia6ipaddressID;

jclass ni_ibcls;            /* InterfaceAddress */
jmethodID ni_ibctrID;       /* InterfaceAddress() */
jfieldID ni_ibaddressID;        /* InterfaceAddress.address */
jfieldID ni_ibbroadcastID;      /* InterfaceAddress.broadcast */
jfieldID ni_ibmaskID;           /* InterfaceAddress.maskLength */

/*
 * Support routines to free netif and netaddr lists
 */
void free_netif(netif *netifP) {
    netif *curr = netifP;
    while (curr != NULL) {
        if (curr->name != NULL)
            free(curr->name);
        if (curr->displayName != NULL)
            free(curr->displayName);
        if (curr->addrs != NULL)
            free_netaddr (curr->addrs);
        netifP = netifP->next;
        free(curr);
        curr = netifP;
    }
}

void free_netaddr(netaddr *netaddrP) {
    netaddr *curr = netaddrP;
    while (curr != NULL) {
        netaddrP = netaddrP->next;
        free(curr);
        curr = netaddrP;
    }
}

/*
 * Returns the interface structure from the table with the matching index.
 */
MIB_IFROW *getIF(jint index) {
    MIB_IFTABLE *tableP;
    MIB_IFROW *ifrowP, *ret = NULL;
    ULONG size;
    DWORD i, count;
    jint ifindex;

    /*
     * Ask the IP Helper library to enumerate the adapters
     */
    size = sizeof(MIB_IFTABLE);
    tableP = (MIB_IFTABLE *)malloc(size);
127
    count = GetIfTable(tableP, &size, TRUE);
D
duke 已提交
128 129
    if (count == ERROR_INSUFFICIENT_BUFFER || count == ERROR_BUFFER_OVERFLOW) {
        tableP = (MIB_IFTABLE *)realloc(tableP, size);
130
        count = GetIfTable(tableP, &size, TRUE);
D
duke 已提交
131 132 133 134 135 136 137 138 139 140 141 142 143 144
    }

    if (count != NO_ERROR) {
        if (tableP != NULL)
            free(tableP);
        return NULL;
    }

    if (tableP != NULL) {
      ifrowP = tableP->table;
      for (i=0; i<tableP->dwNumEntries; i++) {
        /*
         * Warning the real index is obtained by GetFriendlyIfIndex()
         */
145
        ifindex = GetFriendlyIfIndex(ifrowP->dwIndex);
D
duke 已提交
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
        if (ifindex == index) {
          /*
           * Create a copy of the entry so that we can free the table.
           */
          ret = (MIB_IFROW *) malloc(sizeof(MIB_IFROW));
          memcpy(ret, ifrowP, sizeof(MIB_IFROW));
          break;
        }

        /* onto the next interface */
        ifrowP++;
      }
      free(tableP);
    }
    return ret;
}

/*
 * Enumerate network interfaces using IP Helper Library routine GetIfTable.
 * We use GetIfTable rather than other IP helper routines because it's
 * available on 98 & NT SP4+.
 *
 * Returns the number of interfaces found or -1 if error. If no error
 * occurs then netifPP be returned as list of netif structures or NULL
 * if no interfaces are found.
 */
172
int enumInterfaces(JNIEnv *env, netif **netifPP)
D
duke 已提交
173 174 175 176 177 178 179 180
{
    MIB_IFTABLE *tableP;
    MIB_IFROW *ifrowP;
    ULONG size;
    DWORD ret;
    int count;
    netif *netifP;
    DWORD i;
181
    int lo=0, eth=0, tr=0, fddi=0, ppp=0, sl=0, wlan=0, net=0;
D
duke 已提交
182 183 184 185 186 187

    /*
     * Ask the IP Helper library to enumerate the adapters
     */
    size = sizeof(MIB_IFTABLE);
    tableP = (MIB_IFTABLE *)malloc(size);
188
    ret = GetIfTable(tableP, &size, TRUE);
D
duke 已提交
189 190
    if (ret == ERROR_INSUFFICIENT_BUFFER || ret == ERROR_BUFFER_OVERFLOW) {
        tableP = (MIB_IFTABLE *)realloc(tableP, size);
191
        ret = GetIfTable(tableP, &size, TRUE);
D
duke 已提交
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
    }

    if (ret != NO_ERROR) {
        if (tableP != NULL)
            free(tableP);

        JNU_ThrowByName(env, "java/lang/Error",
                "IP Helper Library GetIfTable function failed");

        return -1;
    }

    /*
     * Iterate through the list of adapters
     */
    count = 0;
    netifP = NULL;

    ifrowP = tableP->table;
    for (i=0; i<tableP->dwNumEntries; i++) {
        char dev_name[8];
        netif *curr;

        /*
         * Generate a name for the device as Windows doesn't have any
         * real concept of a device name.
         */
        switch (ifrowP->dwType) {
            case MIB_IF_TYPE_ETHERNET:
221
                _snprintf_s(dev_name, 8, _TRUNCATE, "eth%d", eth++);
D
duke 已提交
222 223 224
                break;

            case MIB_IF_TYPE_TOKENRING:
225
                _snprintf_s(dev_name, 8, _TRUNCATE, "tr%d", tr++);
D
duke 已提交
226 227 228
                break;

            case MIB_IF_TYPE_FDDI:
229
                _snprintf_s(dev_name, 8, _TRUNCATE, "fddi%d", fddi++);
D
duke 已提交
230 231 232 233 234 235 236
                break;

            case MIB_IF_TYPE_LOOPBACK:
                /* There should only be only IPv4 loopback address */
                if (lo > 0) {
                    continue;
                }
237
                strncpy_s(dev_name, 8, "lo", _TRUNCATE);
D
duke 已提交
238 239 240 241
                lo++;
                break;

            case MIB_IF_TYPE_PPP:
242
                _snprintf_s(dev_name, 8, _TRUNCATE, "ppp%d", ppp++);
D
duke 已提交
243 244 245
                break;

            case MIB_IF_TYPE_SLIP:
246 247 248 249 250
                _snprintf_s(dev_name, 8, _TRUNCATE, "sl%d", sl++);
                break;

            case IF_TYPE_IEEE80211:
                _snprintf_s(dev_name, 8, _TRUNCATE, "wlan%d", wlan++);
D
duke 已提交
251 252 253
                break;

            default:
254
                _snprintf_s(dev_name, 8, _TRUNCATE, "net%d", net++);
D
duke 已提交
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
        }

        /*
         * Allocate a netif structure and space for the name and
         * display name (description in this case).
         */
        curr = (netif *)calloc(1, sizeof(netif));
        if (curr != NULL) {
            curr->name = (char *)malloc(strlen(dev_name) + 1);
            curr->displayName = (char *)malloc(ifrowP->dwDescrLen + 1);

            if (curr->name == NULL || curr->displayName == NULL) {
                if (curr->name) free(curr->name);
                if (curr->displayName) free(curr->displayName);
                curr = NULL;
            }
        }
        if (curr == NULL) {
273
            JNU_ThrowOutOfMemoryError(env, "Native heap allocation failure");
D
duke 已提交
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
            free_netif(netifP);
            free(tableP);
            return -1;
        }

        /*
         * Populate the interface. Note that we need to convert the
         * index into its "friendly" value as otherwise we will expose
         * 32-bit numbers as index values.
         */
        strcpy(curr->name, dev_name);
        strncpy(curr->displayName, ifrowP->bDescr, ifrowP->dwDescrLen);
        curr->displayName[ifrowP->dwDescrLen] = '\0';
        curr->dwIndex = ifrowP->dwIndex;
        curr->ifType = ifrowP->dwType;
289
        curr->index = GetFriendlyIfIndex(ifrowP->dwIndex);
D
duke 已提交
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 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344

        /*
         * Put the interface at tail of list as GetIfTable(,,TRUE) is
         * returning the interfaces in index order.
         */
        count++;
        if (netifP == NULL) {
            netifP = curr;
        } else {
            netif *tail = netifP;
            while (tail->next != NULL) {
                tail = tail->next;
            }
            tail->next = curr;
        }

        /* onto the next interface */
        ifrowP++;
    }

    /*
     * Free the interface table and return the interface list
     */
    if (tableP) {
        free(tableP);
    }
    *netifPP = netifP;
    return count;
}

/*
 * Enumerate the IP addresses on an interface using the IP helper library
 * routine GetIfAddrTable and matching based on the index name. There are
 * more efficient routines but we use GetIfAddrTable because it's avaliable
 * on 98 and NT.
 *
 * Returns the count of addresses, or -1 if error. If no error occurs then
 * netaddrPP will return a list of netaddr structures with the IP addresses.
 */
int enumAddresses_win(JNIEnv *env, netif *netifP, netaddr **netaddrPP)
{
    MIB_IPADDRTABLE *tableP;
    ULONG size;
    DWORD ret;
    DWORD i;
    netaddr *netaddrP;
    int count = 0;
    unsigned long mask;

    /*
     * Use GetIpAddrTable to enumerate the IP Addresses
     */
    size = sizeof(MIB_IPADDRTABLE);
    tableP = (MIB_IPADDRTABLE *)malloc(size);

345
    ret = GetIpAddrTable(tableP, &size, FALSE);
D
duke 已提交
346 347
    if (ret == ERROR_INSUFFICIENT_BUFFER || ret == ERROR_BUFFER_OVERFLOW) {
        tableP = (MIB_IPADDRTABLE *)realloc(tableP, size);
348
        ret = GetIpAddrTable(tableP, &size, FALSE);
D
duke 已提交
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
    }
    if (ret != NO_ERROR) {
        if (tableP) {
            free(tableP);
        }
        JNU_ThrowByName(env, "java/lang/Error",
                "IP Helper Library GetIpAddrTable function failed");
        return -1;
    }

    /*
     * Iterate through the table to find the addresses with the
     * matching dwIndex. Ignore 0.0.0.0 addresses.
     */
    count = 0;
    netaddrP = NULL;

    i = 0;
    while (i<tableP->dwNumEntries) {
        if (tableP->table[i].dwIndex == netifP->dwIndex &&
            tableP->table[i].dwAddr != 0) {

            netaddr *curr = (netaddr *)malloc(sizeof(netaddr));
            if (curr == NULL) {
373
                JNU_ThrowOutOfMemoryError(env, "Native heap allocation failure");
D
duke 已提交
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
                free_netaddr(netaddrP);
                free(tableP);
                return -1;
            }

            curr->addr.him4.sin_family = AF_INET;
            curr->addr.him4.sin_addr.s_addr = tableP->table[i].dwAddr;
            /*
             * Get netmask / broadcast address
             */
            switch (netifP->ifType) {
            case MIB_IF_TYPE_ETHERNET:
            case MIB_IF_TYPE_TOKENRING:
            case MIB_IF_TYPE_FDDI:
            case MIB_IF_TYPE_LOOPBACK:
389
            case IF_TYPE_IEEE80211:
D
duke 已提交
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
              /**
               * Contrary to what it seems to indicate, dwBCastAddr doesn't
               * contain the broadcast address but 0 or 1 depending on whether
               * the broadcast address should set the bits of the host part
               * to 0 or 1.
               * Yes, I know it's stupid, but what can I say, it's MSFTs API.
               */
              curr->brdcast.him4.sin_family = AF_INET;
              if (tableP->table[i].dwBCastAddr == 1)
                curr->brdcast.him4.sin_addr.s_addr = (tableP->table[i].dwAddr & tableP->table[i].dwMask) | (0xffffffff ^ tableP->table[i].dwMask);
              else
                curr->brdcast.him4.sin_addr.s_addr = (tableP->table[i].dwAddr & tableP->table[i].dwMask);
              mask = ntohl(tableP->table[i].dwMask);
              curr->mask = 0;
              while (mask) {
                mask <<= 1;
                curr->mask++;
              }
              break;
            case MIB_IF_TYPE_PPP:
            case MIB_IF_TYPE_SLIP:
            default:
              /**
               * these don't have broadcast/subnet
               */
              curr->mask = -1;
                break;
            }

            curr->next = netaddrP;
            netaddrP = curr;
            count++;
        }
        i++;
    }

    *netaddrPP = netaddrP;
    free(tableP);
    return count;
}

/*
 * Class:     java_net_NetworkInterface
 * Method:    init
 * Signature: ()V
 */
JNIEXPORT void JNICALL
Java_java_net_NetworkInterface_init(JNIEnv *env, jclass cls)
{
    /*
     * Get the various JNI ids that we require
     */
    ni_class = (*env)->NewGlobalRef(env, cls);
    ni_nameID = (*env)->GetFieldID(env, ni_class, "name", "Ljava/lang/String;");
    ni_displayNameID = (*env)->GetFieldID(env, ni_class, "displayName", "Ljava/lang/String;");
    ni_indexID = (*env)->GetFieldID(env, ni_class, "index", "I");
    ni_addrsID = (*env)->GetFieldID(env, ni_class, "addrs", "[Ljava/net/InetAddress;");
    ni_bindsID = (*env)->GetFieldID(env, ni_class, "bindings", "[Ljava/net/InterfaceAddress;");
    ni_childsID = (*env)->GetFieldID(env, ni_class, "childs", "[Ljava/net/NetworkInterface;");
    ni_ctor = (*env)->GetMethodID(env, ni_class, "<init>", "()V");

451
    ni_iacls = (*env)->FindClass(env, "java/net/InetAddress");
D
duke 已提交
452 453 454
    ni_iacls = (*env)->NewGlobalRef(env, ni_iacls);
    ni_iaAddr = (*env)->GetFieldID(env, ni_iacls, "address", "I");

455
    ni_ia4cls = (*env)->FindClass(env, "java/net/Inet4Address");
D
duke 已提交
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
    ni_ia4cls = (*env)->NewGlobalRef(env, ni_ia4cls);
    ni_ia4Ctor = (*env)->GetMethodID(env, ni_ia4cls, "<init>", "()V");

    ni_ia6cls = (*env)->FindClass(env, "java/net/Inet6Address");
    ni_ia6cls = (*env)->NewGlobalRef(env, ni_ia6cls);
    ni_ia6ctrID = (*env)->GetMethodID(env, ni_ia6cls, "<init>", "()V");
    ni_ia6ipaddressID = (*env)->GetFieldID(env, ni_ia6cls, "ipaddress", "[B");

    ni_ibcls = (*env)->FindClass(env, "java/net/InterfaceAddress");
    ni_ibcls = (*env)->NewGlobalRef(env, ni_ibcls);
    ni_ibctrID = (*env)->GetMethodID(env, ni_ibcls, "<init>", "()V");
    ni_ibaddressID = (*env)->GetFieldID(env, ni_ibcls, "address", "Ljava/net/InetAddress;");
    ni_ibbroadcastID = (*env)->GetFieldID(env, ni_ibcls, "broadcast", "Ljava/net/Inet4Address;");
    ni_ibmaskID = (*env)->GetFieldID(env, ni_ibcls, "maskLength", "S");

}

/*
 * Create a NetworkInterface object, populate the name and index, and
 * populate the InetAddress array based on the IP addresses for this
 * interface.
 */
478 479
jobject createNetworkInterface
    (JNIEnv *env, netif *ifs, int netaddrCount, netaddr *netaddrP)
D
duke 已提交
480 481 482 483 484 485 486 487 488 489 490 491 492 493
{
    jobject netifObj;
    jobject name, displayName;
    jobjectArray addrArr, bindsArr, childArr;
    netaddr *addrs;
    jint addr_index;
    jint bind_index;

    /*
     * Create a NetworkInterface object and populate it
     */
    netifObj = (*env)->NewObject(env, ni_class, ni_ctor);
    name = (*env)->NewStringUTF(env, ifs->name);
    if (ifs->dNameIsUnicode) {
494 495
        displayName = (*env)->NewString(env, (PWCHAR)ifs->displayName,
                                       (jsize)wcslen ((PWCHAR)ifs->displayName));
D
duke 已提交
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
    } else {
        displayName = (*env)->NewStringUTF(env, ifs->displayName);
    }
    if (netifObj == NULL || name == NULL || displayName == NULL) {
        return NULL;
    }
    (*env)->SetObjectField(env, netifObj, ni_nameID, name);
    (*env)->SetObjectField(env, netifObj, ni_displayNameID, displayName);
    (*env)->SetIntField(env, netifObj, ni_indexID, ifs->index);

    /*
     * Get the IP addresses for this interface if necessary
     * Note that 0 is a valid number of addresses.
     */
    if (netaddrCount < 0) {
511
        netaddrCount = enumAddresses_win(env, ifs, &netaddrP);
M
michaelm 已提交
512
        if (netaddrCount == -1) {
D
duke 已提交
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 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
            return NULL;
        }
    }
    addrArr = (*env)->NewObjectArray(env, netaddrCount, ni_iacls, NULL);
    if (addrArr == NULL) {
        free_netaddr(netaddrP);
        return NULL;
    }

    bindsArr = (*env)->NewObjectArray(env, netaddrCount, ni_ibcls, NULL);
    if (bindsArr == NULL) {
      free_netaddr(netaddrP);
      return NULL;
    }
    addrs = netaddrP;
    addr_index = 0;
    bind_index = 0;
    while (addrs != NULL) {
        jobject iaObj, ia2Obj;
        jobject ibObj = NULL;
        if (addrs->addr.him.sa_family == AF_INET) {
            iaObj = (*env)->NewObject(env, ni_ia4cls, ni_ia4Ctor);
            if (iaObj == NULL) {
                free_netaddr(netaddrP);
                return NULL;
            }
            /* default ctor will set family to AF_INET */

            (*env)->SetIntField(env, iaObj, ni_iaAddr, ntohl(addrs->addr.him4.sin_addr.s_addr));
            if (addrs->mask != -1) {
              ibObj = (*env)->NewObject(env, ni_ibcls, ni_ibctrID);
              if (ibObj == NULL) {
                free_netaddr(netaddrP);
                return NULL;
              }
              (*env)->SetObjectField(env, ibObj, ni_ibaddressID, iaObj);
              ia2Obj = (*env)->NewObject(env, ni_ia4cls, ni_ia4Ctor);
              if (ia2Obj == NULL) {
                free_netaddr(netaddrP);
                return NULL;
              }
              (*env)->SetIntField(env, ia2Obj, ni_iaAddr,
                                  ntohl(addrs->brdcast.him4.sin_addr.s_addr));
              (*env)->SetObjectField(env, ibObj, ni_ibbroadcastID, ia2Obj);
              (*env)->SetShortField(env, ibObj, ni_ibmaskID, addrs->mask);
              (*env)->SetObjectArrayElement(env, bindsArr, bind_index++, ibObj);
            }
        } else /* AF_INET6 */ {
            int scope;
            iaObj = (*env)->NewObject(env, ni_ia6cls, ni_ia6ctrID);
            if (iaObj) {
                jbyteArray ipaddress = (*env)->NewByteArray(env, 16);
                if (ipaddress == NULL) {
                    return NULL;
                }
                (*env)->SetByteArrayRegion(env, ipaddress, 0, 16,
                    (jbyte *)&(addrs->addr.him6.sin6_addr.s6_addr));
                scope = addrs->addr.him6.sin6_scope_id;
                if (scope != 0) { /* zero is default value, no need to set */
                    (*env)->SetIntField(env, iaObj, ia6_scopeidID, scope);
                    (*env)->SetBooleanField(env, iaObj, ia6_scopeidsetID, JNI_TRUE);
                    (*env)->SetObjectField(env, iaObj, ia6_scopeifnameID, netifObj);
                }
                (*env)->SetObjectField(env, iaObj, ni_ia6ipaddressID, ipaddress);
                ibObj = (*env)->NewObject(env, ni_ibcls, ni_ibctrID);
                if (ibObj == NULL) {
                  free_netaddr(netaddrP);
                  return NULL;
                }
                (*env)->SetObjectField(env, ibObj, ni_ibaddressID, iaObj);
                (*env)->SetShortField(env, ibObj, ni_ibmaskID, addrs->mask);
                (*env)->SetObjectArrayElement(env, bindsArr, bind_index++, ibObj);
            }
        }
        (*env)->SetObjectArrayElement(env, addrArr, addr_index, iaObj);
        addrs = addrs->next;
        addr_index++;
    }
    (*env)->SetObjectField(env, netifObj, ni_addrsID, addrArr);
    (*env)->SetObjectField(env, netifObj, ni_bindsID, bindsArr);

    free_netaddr(netaddrP);

    /*
     * Windows doesn't have virtual interfaces, so child array
     * is always empty.
     */
    childArr = (*env)->NewObjectArray(env, 0, ni_class, NULL);
    if (childArr == NULL) {
      return NULL;
    }
    (*env)->SetObjectField(env, netifObj, ni_childsID, childArr);

    /* return the NetworkInterface */
    return netifObj;
}

/*
 * 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 *ifList, *curr;
    jboolean isCopy;
    const char *name_utf;
    jobject netifObj = NULL;

623 624
    // Retained for now to support IPv4 only stack, java.net.preferIPv4Stack
    if (ipv6_available()) {
D
duke 已提交
625 626 627 628
        return Java_java_net_NetworkInterface_getByName0_XP (env, cls, name);
    }

    /* get the list of interfaces */
629
    if (enumInterfaces(env, &ifList) < 0) {
D
duke 已提交
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
        return NULL;
    }

    /* get the name as a C string */
    name_utf = (*env)->GetStringUTFChars(env, name, &isCopy);

    /* Search by name */
    curr = ifList;
    while (curr != NULL) {
        if (strcmp(name_utf, curr->name) == 0) {
            break;
        }
        curr = curr->next;
    }

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

    /* release the UTF string */
    (*env)->ReleaseStringUTFChars(env, name, name_utf);

    /* release the interface list */
    free_netif(ifList);

    return netifObj;
}

/*
 * Class:     NetworkInterface
661
 * Method:    getByIndex0
D
duke 已提交
662 663
 * Signature: (I)LNetworkInterface;
 */
664
JNIEXPORT jobject JNICALL Java_java_net_NetworkInterface_getByIndex0
D
duke 已提交
665 666 667 668 669
  (JNIEnv *env, jclass cls, jint index)
{
    netif *ifList, *curr;
    jobject netifObj = NULL;

670 671
    // Retained for now to support IPv4 only stack, java.net.preferIPv4Stack
    if (ipv6_available()) {
672
        return Java_java_net_NetworkInterface_getByIndex0_XP (env, cls, index);
D
duke 已提交
673 674 675
    }

    /* get the list of interfaces */
676
    if (enumInterfaces(env, &ifList) < 0) {
D
duke 已提交
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
        return NULL;
    }

    /* search by index */
    curr = ifList;
    while (curr != NULL) {
        if (index == curr->index) {
            break;
        }
        curr = curr->next;
    }

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

    /* release the interface list */
    free_netif(ifList);

    return netifObj;
}

/*
 * 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 *ifList, *curr;
    jint addr = (*env)->GetIntField(env, iaObj, ni_iaAddr);
    jobject netifObj = NULL;

712 713
    // Retained for now to support IPv4 only stack, java.net.preferIPv4Stack
    if (ipv6_available()) {
D
duke 已提交
714 715 716 717
        return Java_java_net_NetworkInterface_getByInetAddress0_XP (env, cls, iaObj);
    }

    /* get the list of interfaces */
718
    if (enumInterfaces(env, &ifList) < 0) {
D
duke 已提交
719 720 721 722 723 724 725 726 727 728 729 730 731 732
        return NULL;
    }

    /*
     * Enumerate the addresses on each interface until we find a
     * matching address.
     */
    curr = ifList;
    while (curr != NULL) {
        int count;
        netaddr *addrList;
        netaddr *addrP;

        /* enumerate the addresses on this interface */
733
        count = enumAddresses_win(env, curr, &addrList);
D
duke 已提交
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
        if (count < 0) {
            free_netif(ifList);
            return NULL;
        }

        /* iterate through each address */
        addrP = addrList;

        while (addrP != NULL) {
            if ((unsigned long)addr == ntohl(addrP->addr.him4.sin_addr.s_addr)) {
                break;
            }
            addrP = addrP->next;
        }

        /*
         * Address matched so create NetworkInterface for this interface
         * and address list.
         */
        if (addrP != NULL) {
            /* createNetworkInterface will free addrList */
            netifObj = createNetworkInterface(env, curr, count, addrList);
            break;
        }

        /* on next interface */
        curr = curr->next;
    }

    /* release the interface list */
    free_netif(ifList);

    return netifObj;
}

/*
 * Class:     java_net_NetworkInterface
 * Method:    getAll
 * Signature: ()[Ljava/net/NetworkInterface;
 */
JNIEXPORT jobjectArray JNICALL Java_java_net_NetworkInterface_getAll
    (JNIEnv *env, jclass cls)
{
    int count;
    netif *ifList, *curr;
    jobjectArray netIFArr;
    jint arr_index;

782 783
    // Retained for now to support IPv4 only stack, java.net.preferIPv4Stack
    if (ipv6_available()) {
D
duke 已提交
784 785 786 787 788 789
        return Java_java_net_NetworkInterface_getAll_XP (env, cls);
    }

    /*
     * Get list of interfaces
     */
790
    count = enumInterfaces(env, &ifList);
D
duke 已提交
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
    if (count < 0) {
        return NULL;
    }

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

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

        netifObj = createNetworkInterface(env, curr, -1, NULL);
        if (netifObj == NULL) {
            return NULL;
        }

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

        curr = curr->next;
    }

    /* release the interface list */
    free_netif(ifList);

    return netIFArr;
}

/*
 * Class:     java_net_NetworkInterface
 * Method:    isUp0
 * Signature: (Ljava/lang/String;)Z
 */
JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_isUp0
    (JNIEnv *env, jclass cls, jstring name, jint index) {
  jboolean ret = JNI_FALSE;

836 837
  // Retained for now to support IPv4 only stack, java.net.preferIPv4Stack
  if (ipv6_available()) {
D
duke 已提交
838 839 840 841 842
    return Java_java_net_NetworkInterface_isUp0_XP(env, cls, name, index);
  } else {
    MIB_IFROW *ifRowP;
    ifRowP = getIF(index);
    if (ifRowP != NULL) {
843 844 845
      ret = ifRowP->dwAdminStatus == 1 &&
            (ifRowP->dwOperStatus == MIB_IF_OPER_STATUS_OPERATIONAL ||
             ifRowP->dwOperStatus == MIB_IF_OPER_STATUS_CONNECTED);
D
duke 已提交
846 847 848 849 850 851 852 853 854 855 856
      free(ifRowP);
    }
  }
    return ret;
}

/*
 * Class:     java_net_NetworkInterface
 * Method:    isP2P0
 * Signature: (Ljava/lang/String;I)Z
 */
857 858
JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_isP2P0
    (JNIEnv *env, jclass cls, jstring name, jint index) {
D
duke 已提交
859 860 861
  MIB_IFROW *ifRowP;
  jboolean ret = JNI_FALSE;

862 863
  // Retained for now to support IPv4 only stack, java.net.preferIPv4Stack
  if (ipv6_available()) {
D
duke 已提交
864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
    return Java_java_net_NetworkInterface_isP2P0_XP(env, cls, name, index);
  } else {
    ifRowP = getIF(index);
    if (ifRowP != NULL) {
      switch(ifRowP->dwType) {
      case MIB_IF_TYPE_PPP:
      case MIB_IF_TYPE_SLIP:
        ret = JNI_TRUE;
        break;
      }
      free(ifRowP);
    }
  }
  return ret;
}

/*
 * 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) {
  MIB_IFROW *ifRowP;
  jboolean ret = JNI_FALSE;

890 891
  // Retained for now to support IPv4 only stack, java.net.preferIPv4Stack
  if (ipv6_available()) {
D
duke 已提交
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
    return Java_java_net_NetworkInterface_isLoopback0_XP(env, cls, name, index);
  } else {
    ifRowP = getIF(index);
    if (ifRowP != NULL) {
      if (ifRowP->dwType == MIB_IF_TYPE_LOOPBACK)
        ret = JNI_TRUE;
      free(ifRowP);
    }
    return ret;
  }
}

/*
 * 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) {
911
    return Java_java_net_NetworkInterface_supportsMulticast0_XP(env, cls,
D
duke 已提交
912 913 914 915 916 917 918 919
                                                               name, index);
}

/*
 * Class:     java_net_NetworkInterface
 * Method:    getMacAddr0
 * Signature: ([bLjava/lang/String;I)[b
 */
920 921
JNIEXPORT jbyteArray JNICALL Java_java_net_NetworkInterface_getMacAddr0
    (JNIEnv *env, jclass class, jbyteArray addrArray, jstring name, jint index) {
D
duke 已提交
922 923 924 925
  jbyteArray ret = NULL;
  int len;
  MIB_IFROW *ifRowP;

926 927
  // Retained for now to support IPv4 only stack, java.net.preferIPv4Stack
  if (ipv6_available()) {
D
duke 已提交
928 929 930 931 932 933 934 935
    return Java_java_net_NetworkInterface_getMacAddr0_XP(env, class, name, index);
  } else {
    ifRowP = getIF(index);
    if (ifRowP != NULL) {
      switch(ifRowP->dwType) {
      case MIB_IF_TYPE_ETHERNET:
      case MIB_IF_TYPE_TOKENRING:
      case MIB_IF_TYPE_FDDI:
936
      case IF_TYPE_IEEE80211:
D
duke 已提交
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
        len = ifRowP->dwPhysAddrLen;
        ret = (*env)->NewByteArray(env, len);
        if (!IS_NULL(ret)) {
          (*env)->SetByteArrayRegion(env, ret, 0, len, (jbyte *) ifRowP->bPhysAddr);
        }
        break;
      }
      free(ifRowP);
    }
    return ret;
  }
}

/*
 * Class:       java_net_NetworkInterface
 * Method:      getMTU0
 * Signature:   ([bLjava/lang/String;I)I
 */
955 956
JNIEXPORT jint JNICALL Java_java_net_NetworkInterface_getMTU0
    (JNIEnv *env, jclass class, jstring name, jint index) {
D
duke 已提交
957 958 959
  jint ret = -1;
  MIB_IFROW *ifRowP;

960 961
  // Retained for now to support IPv4 only stack, java.net.preferIPv4Stack
  if (ipv6_available()) {
D
duke 已提交
962 963 964 965 966 967 968 969 970 971
    return Java_java_net_NetworkInterface_getMTU0_XP(env, class, name, index);
  } else {
    ifRowP = getIF(index);
    if (ifRowP != NULL) {
      ret = ifRowP->dwMtu;
      free(ifRowP);
    }
    return ret;
  }
}