1 /*
   2  * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 #include <errno.h>
  27 #include <sys/time.h>
  28 #include <sys/types.h>
  29 #include <sys/socket.h>
  30 #include <netinet/in_systm.h>
  31 #include <netinet/in.h>
  32 #include <netinet/ip.h>
  33 #include <netinet/ip_icmp.h>
  34 #include <netdb.h>
  35 #include <string.h>
  36 #include <stdlib.h>
  37 #include <ctype.h>
  38 
  39 #ifdef _ALLBSD_SOURCE
  40 #include <unistd.h>
  41 #include <sys/param.h>
  42 #endif
  43 
  44 #include "jvm.h"
  45 #include "jni_util.h"
  46 #include "net_util.h"
  47 
  48 #include "java_net_Inet4AddressImpl.h"
  49 
  50 #if defined(__GLIBC__) || (defined(__FreeBSD__) && (__FreeBSD_version >= 601104))
  51 #define HAS_GLIBC_GETHOSTBY_R   1
  52 #endif
  53 
  54 static jclass ni_iacls;
  55 static jclass ni_ia4cls;
  56 static jmethodID ni_ia4ctrID;
  57 
  58 static void initializeInetClasses(JNIEnv *env)
  59 {
  60     static int initialized = 0;
  61     if (!initialized) {
  62         ni_iacls = (*env)->FindClass(env, "java/net/InetAddress");
  63         ni_iacls = (*env)->NewGlobalRef(env, ni_iacls);
  64         ni_ia4cls = (*env)->FindClass(env, "java/net/Inet4Address");
  65         ni_ia4cls = (*env)->NewGlobalRef(env, ni_ia4cls);
  66         ni_ia4ctrID = (*env)->GetMethodID(env, ni_ia4cls, "<init>", "()V");
  67         initialized = 1;
  68     }
  69 }
  70 
  71 
  72 #if defined(_ALLBSD_SOURCE) && !defined(HAS_GLIBC_GETHOSTBY_R)
  73 extern jobjectArray lookupIfLocalhost(JNIEnv *env, const char *hostname, jboolean includeV6);
  74 
  75 /* Use getaddrinfo(3), which is thread safe */
  76 /************************************************************************
  77  * Inet4AddressImpl
  78  */
  79 
  80 /*
  81  * Class:     java_net_Inet4AddressImpl
  82  * Method:    getLocalHostName
  83  * Signature: ()Ljava/lang/String;
  84  */
  85 JNIEXPORT jstring JNICALL
  86 Java_java_net_Inet4AddressImpl_getLocalHostName(JNIEnv *env, jobject this) {
  87     char hostname[NI_MAXHOST+1];
  88 
  89     hostname[0] = '\0';
  90     if (JVM_GetHostName(hostname, NI_MAXHOST)) {
  91         /* Something went wrong, maybe networking is not setup? */
  92         strcpy(hostname, "localhost");
  93     } else {
  94          struct addrinfo  hints, *res;
  95          int error;
  96 
  97          memset(&hints, 0, sizeof(hints));
  98          hints.ai_flags = AI_CANONNAME;
  99          hints.ai_family = AF_UNSPEC;
 100 
 101          error = getaddrinfo(hostname, NULL, &hints, &res);
 102 
 103          if (error == 0) {
 104              /* host is known to name service */
 105              error = getnameinfo(res->ai_addr,
 106                                  res->ai_addrlen,
 107                                  hostname,
 108                                  NI_MAXHOST,
 109                                  NULL,
 110                                  0,
 111                                  NI_NAMEREQD);
 112 
 113              /* if getnameinfo fails hostname is still the value
 114                 from gethostname */
 115 
 116              freeaddrinfo(res);
 117         }
 118     }
 119     return (*env)->NewStringUTF(env, hostname);
 120 }
 121 
 122 /*
 123  * Find an internet address for a given hostname.  Note that this
 124  * code only works for addresses of type INET. The translation
 125  * of %d.%d.%d.%d to an address (int) occurs in java now, so the
 126  * String "host" shouldn't *ever* be a %d.%d.%d.%d string
 127  *
 128  * Class:     java_net_Inet4AddressImpl
 129  * Method:    lookupAllHostAddr
 130  * Signature: (Ljava/lang/String;)[[B
 131  */
 132 
 133 JNIEXPORT jobjectArray JNICALL
 134 Java_java_net_Inet4AddressImpl_lookupAllHostAddr(JNIEnv *env, jobject this,
 135                                                 jstring host) {
 136     const char *hostname;
 137     jobject name;
 138     jobjectArray ret = 0;
 139     int retLen = 0;
 140 
 141     int error=0;
 142     struct addrinfo hints, *res, *resNew = NULL;
 143 
 144     initializeInetClasses(env);
 145 
 146     if (IS_NULL(host)) {
 147         JNU_ThrowNullPointerException(env, "host is null");
 148         return 0;
 149     }
 150     hostname = JNU_GetStringPlatformChars(env, host, JNI_FALSE);
 151     CHECK_NULL_RETURN(hostname, NULL);
 152 
 153     memset(&hints, 0, sizeof(hints));
 154     hints.ai_flags = AI_CANONNAME;
 155     hints.ai_family = AF_INET;
 156 
 157     /*
 158      * Workaround for Solaris bug 4160367 - if a hostname contains a
 159      * white space then 0.0.0.0 is returned
 160      */
 161     if (isspace((unsigned char)hostname[0])) {
 162         JNU_ThrowByName(env, JNU_JAVANETPKG "UnknownHostException",
 163                         (char *)hostname);
 164         JNU_ReleaseStringPlatformChars(env, host, hostname);
 165         return NULL;
 166     }
 167 
 168 #ifdef MACOSX
 169     /* If we're looking up the local machine, bypass DNS lookups and get
 170      * address from getifaddrs.
 171      */
 172     ret = lookupIfLocalhost(env, hostname, JNI_FALSE);
 173     if (ret != NULL || (*env)->ExceptionCheck(env)) {
 174         JNU_ReleaseStringPlatformChars(env, host, hostname);
 175         return ret;
 176     }
 177 #endif
 178 
 179     error = getaddrinfo(hostname, NULL, &hints, &res);
 180 
 181     if (error) {
 182         /* report error */
 183         ThrowUnknownHostExceptionWithGaiError(env, hostname, error);
 184         JNU_ReleaseStringPlatformChars(env, host, hostname);
 185         return NULL;
 186     } else {
 187         int i = 0;
 188         struct addrinfo *itr, *last = NULL, *iterator = res;
 189         while (iterator != NULL) {
 190             int skip = 0;
 191             itr = resNew;
 192 
 193             while (itr != NULL) {
 194                 struct sockaddr_in *addr1, *addr2;
 195 
 196                 addr1 = (struct sockaddr_in *)iterator->ai_addr;
 197                 addr2 = (struct sockaddr_in *)itr->ai_addr;
 198                 if (addr1->sin_addr.s_addr ==
 199                     addr2->sin_addr.s_addr) {
 200                     skip = 1;
 201                     break;
 202                 }
 203 
 204                 itr = itr->ai_next;
 205             }
 206 
 207             if (!skip) {
 208                 struct addrinfo *next
 209                     = (struct addrinfo*) malloc(sizeof(struct addrinfo));
 210                 if (!next) {
 211                     JNU_ThrowOutOfMemoryError(env, "Native heap allocation failed");
 212                     ret = NULL;
 213                     goto cleanupAndReturn;
 214                 }
 215                 memcpy(next, iterator, sizeof(struct addrinfo));
 216                 next->ai_next = NULL;
 217                 if (resNew == NULL) {
 218                     resNew = next;
 219                 } else {
 220                     last->ai_next = next;
 221                 }
 222                 last = next;
 223                 i++;
 224             }
 225             iterator = iterator->ai_next;
 226         }
 227 
 228         retLen = i;
 229         iterator = resNew;
 230         i = 0;
 231 
 232         name = (*env)->NewStringUTF(env, hostname);
 233         if (IS_NULL(name)) {
 234           goto cleanupAndReturn;
 235         }
 236 
 237         ret = (*env)->NewObjectArray(env, retLen, ni_iacls, NULL);
 238         if (IS_NULL(ret)) {
 239             /* we may have memory to free at the end of this */
 240             goto cleanupAndReturn;
 241         }
 242 
 243         while (iterator != NULL) {
 244             /* We need 4 bytes to store ipv4 address; */
 245             int len = 4;
 246 
 247             jobject iaObj = (*env)->NewObject(env, ni_ia4cls, ni_ia4ctrID);
 248             if (IS_NULL(iaObj)) {
 249                 /* we may have memory to free at the end of this */
 250                 ret = NULL;
 251                 goto cleanupAndReturn;
 252             }
 253             setInetAddress_addr(env, iaObj, ntohl(((struct sockaddr_in*)(iterator->ai_addr))->sin_addr.s_addr));
 254             setInetAddress_hostName(env, iaObj, name);
 255             (*env)->SetObjectArrayElement(env, ret, retLen - i -1, iaObj);
 256             i++;
 257             iterator = iterator->ai_next;
 258         }
 259     }
 260 
 261 cleanupAndReturn:
 262     {
 263         struct addrinfo *iterator, *tmp;
 264         iterator = resNew;
 265         while (iterator != NULL) {
 266             tmp = iterator;
 267             iterator = iterator->ai_next;
 268             free(tmp);
 269         }
 270         JNU_ReleaseStringPlatformChars(env, host, hostname);
 271     }
 272 
 273     freeaddrinfo(res);
 274 
 275     return ret;
 276 
 277 }
 278 
 279 /*
 280  * Class:     java_net_Inet4AddressImpl
 281  * Method:    getHostByAddr
 282  * Signature: (I)Ljava/lang/String;
 283  */
 284 JNIEXPORT jstring JNICALL
 285 Java_java_net_Inet4AddressImpl_getHostByAddr(JNIEnv *env, jobject this,
 286                                             jbyteArray addrArray) {
 287     jstring ret = NULL;
 288 
 289     char host[NI_MAXHOST+1];
 290     jfieldID fid;
 291     int error = 0;
 292     jint family;
 293     struct sockaddr *him ;
 294     int len = 0;
 295     jbyte caddr[4];
 296     jint addr;
 297 
 298     struct sockaddr_in him4;
 299     struct sockaddr *sa;
 300 
 301     /*
 302          * For IPv4 addresses construct a sockaddr_in structure.
 303          */
 304     (*env)->GetByteArrayRegion(env, addrArray, 0, 4, caddr);
 305     addr = ((caddr[0]<<24) & 0xff000000);
 306     addr |= ((caddr[1] <<16) & 0xff0000);
 307     addr |= ((caddr[2] <<8) & 0xff00);
 308     addr |= (caddr[3] & 0xff);
 309     memset((char *) &him4, 0, sizeof(him4));
 310     him4.sin_addr.s_addr = (uint32_t) htonl(addr);
 311     him4.sin_family = AF_INET;
 312     sa = (struct sockaddr *) &him4;
 313     len = sizeof(him4);
 314 
 315     error = getnameinfo(sa, len, host, NI_MAXHOST, NULL, 0,
 316                                NI_NAMEREQD);
 317 
 318     if (!error) {
 319         ret = (*env)->NewStringUTF(env, host);
 320     }
 321 
 322     if (ret == NULL) {
 323         JNU_ThrowByName(env, JNU_JAVANETPKG "UnknownHostException", NULL);
 324     }
 325 
 326     return ret;
 327 
 328 }
 329 
 330 #else /* defined(_ALLBSD_SOURCE) && !defined(HAS_GLIBC_GETHOSTBY_R) */
 331 
 332 /* the initial size of our hostent buffers */
 333 #ifndef NI_MAXHOST
 334 #define NI_MAXHOST 1025
 335 #endif
 336 
 337 /************************************************************************
 338  * Inet4AddressImpl
 339  */
 340 
 341 /*
 342  * Class:     java_net_Inet4AddressImpl
 343  * Method:    getLocalHostName
 344  * Signature: ()Ljava/lang/String;
 345  */
 346 JNIEXPORT jstring JNICALL
 347 Java_java_net_Inet4AddressImpl_getLocalHostName(JNIEnv *env, jobject this) {
 348     char hostname[NI_MAXHOST+1];
 349 
 350     hostname[0] = '\0';
 351     if (JVM_GetHostName(hostname, sizeof(hostname))) {
 352         /* Something went wrong, maybe networking is not setup? */
 353         strcpy(hostname, "localhost");
 354     } else {
 355         struct addrinfo hints, *res;
 356         int error;
 357 
 358         hostname[NI_MAXHOST] = '\0';
 359         memset(&hints, 0, sizeof(hints));
 360         hints.ai_flags = AI_CANONNAME;
 361         hints.ai_family = AF_INET;
 362 
 363         error = getaddrinfo(hostname, NULL, &hints, &res);
 364 
 365         if (error == 0) {/* host is known to name service */
 366             getnameinfo(res->ai_addr,
 367                         res->ai_addrlen,
 368                         hostname,
 369                         NI_MAXHOST,
 370                         NULL,
 371                         0,
 372                         NI_NAMEREQD);
 373 
 374             /* if getnameinfo fails hostname is still the value
 375                from gethostname */
 376 
 377             freeaddrinfo(res);
 378         }
 379     }
 380     return (*env)->NewStringUTF(env, hostname);
 381 }
 382 
 383 /*
 384  * Find an internet address for a given hostname.  Note that this
 385  * code only works for addresses of type INET. The translation
 386  * of %d.%d.%d.%d to an address (int) occurs in java now, so the
 387  * String "host" shouldn't *ever* be a %d.%d.%d.%d string
 388  *
 389  * Class:     java_net_Inet4AddressImpl
 390  * Method:    lookupAllHostAddr
 391  * Signature: (Ljava/lang/String;)[[B
 392  */
 393 
 394 JNIEXPORT jobjectArray JNICALL
 395 Java_java_net_Inet4AddressImpl_lookupAllHostAddr(JNIEnv *env, jobject this,
 396                                                 jstring host) {
 397     const char *hostname;
 398     jobjectArray ret = 0;
 399     int retLen = 0;
 400     int error = 0;
 401     struct addrinfo hints, *res, *resNew = NULL;
 402 
 403     initializeInetClasses(env);
 404 
 405     if (IS_NULL(host)) {
 406         JNU_ThrowNullPointerException(env, "host is null");
 407         return 0;
 408     }
 409     hostname = JNU_GetStringPlatformChars(env, host, JNI_FALSE);
 410     CHECK_NULL_RETURN(hostname, NULL);
 411 
 412     /* Try once, with our static buffer. */
 413     memset(&hints, 0, sizeof(hints));
 414     hints.ai_flags = AI_CANONNAME;
 415     hints.ai_family = AF_INET;
 416 
 417 #ifdef __solaris__
 418     /*
 419      * Workaround for Solaris bug 4160367 - if a hostname contains a
 420      * white space then 0.0.0.0 is returned
 421      */
 422     if (isspace((unsigned char)hostname[0])) {
 423         JNU_ThrowByName(env, JNU_JAVANETPKG "UnknownHostException",
 424                         (char *)hostname);
 425         JNU_ReleaseStringPlatformChars(env, host, hostname);
 426         return NULL;
 427     }
 428 #endif
 429 
 430     error = getaddrinfo(hostname, NULL, &hints, &res);
 431 
 432     if (error) {
 433         /* report error */
 434         ThrowUnknownHostExceptionWithGaiError(env, hostname, error);
 435         JNU_ReleaseStringPlatformChars(env, host, hostname);
 436         return NULL;
 437     } else {
 438         int i = 0;
 439         struct addrinfo *itr, *last = NULL, *iterator = res;
 440 
 441         while (iterator != NULL) {
 442             // remove the duplicate one
 443             int skip = 0;
 444             itr = resNew;
 445             while (itr != NULL) {
 446                 struct sockaddr_in *addr1, *addr2;
 447                 addr1 = (struct sockaddr_in *)iterator->ai_addr;
 448                 addr2 = (struct sockaddr_in *)itr->ai_addr;
 449                 if (addr1->sin_addr.s_addr ==
 450                     addr2->sin_addr.s_addr) {
 451                     skip = 1;
 452                     break;
 453                 }
 454                 itr = itr->ai_next;
 455             }
 456 
 457             if (!skip) {
 458                 struct addrinfo *next
 459                     = (struct addrinfo*) malloc(sizeof(struct addrinfo));
 460                 if (!next) {
 461                     JNU_ThrowOutOfMemoryError(env, "Native heap allocation failed");
 462                     ret = NULL;
 463                     goto cleanupAndReturn;
 464                 }
 465                 memcpy(next, iterator, sizeof(struct addrinfo));
 466                 next->ai_next = NULL;
 467                 if (resNew == NULL) {
 468                     resNew = next;
 469                 } else {
 470                     last->ai_next = next;
 471                 }
 472                 last = next;
 473                 i++;
 474             }
 475             iterator = iterator->ai_next;
 476         }
 477 
 478         retLen = i;
 479         iterator = resNew;
 480 
 481         ret = (*env)->NewObjectArray(env, retLen, ni_iacls, NULL);
 482 
 483         if (IS_NULL(ret)) {
 484             /* we may have memory to free at the end of this */
 485             goto cleanupAndReturn;
 486         }
 487 
 488         i = 0;
 489         while (iterator != NULL) {
 490             jobject iaObj = (*env)->NewObject(env, ni_ia4cls, ni_ia4ctrID);
 491             if (IS_NULL(iaObj)) {
 492                 ret = NULL;
 493                 goto cleanupAndReturn;
 494             }
 495             setInetAddress_addr(env, iaObj, ntohl(((struct sockaddr_in*)iterator->ai_addr)->sin_addr.s_addr));
 496             setInetAddress_hostName(env, iaObj, host);
 497             (*env)->SetObjectArrayElement(env, ret, i++, iaObj);
 498             iterator = iterator->ai_next;
 499         }
 500     }
 501 
 502  cleanupAndReturn:
 503     {
 504         struct addrinfo *iterator, *tmp;
 505         iterator = resNew;
 506         while (iterator != NULL) {
 507             tmp = iterator;
 508             iterator = iterator->ai_next;
 509             free(tmp);
 510         }
 511         JNU_ReleaseStringPlatformChars(env, host, hostname);
 512     }
 513 
 514     freeaddrinfo(res);
 515 
 516     return ret;
 517 }
 518 
 519 /*
 520  * Class:     java_net_Inet4AddressImpl
 521  * Method:    getHostByAddr
 522  * Signature: (I)Ljava/lang/String;
 523  */
 524 JNIEXPORT jstring JNICALL
 525 Java_java_net_Inet4AddressImpl_getHostByAddr(JNIEnv *env, jobject this,
 526                                             jbyteArray addrArray) {
 527     jstring ret = NULL;
 528 
 529     char host[NI_MAXHOST+1];
 530     int error = 0;
 531     int len = 0;
 532     jbyte caddr[4];
 533 
 534     struct sockaddr_in him4;
 535     struct sockaddr *sa;
 536 
 537     jint addr;
 538     (*env)->GetByteArrayRegion(env, addrArray, 0, 4, caddr);
 539     addr = ((caddr[0]<<24) & 0xff000000);
 540     addr |= ((caddr[1] <<16) & 0xff0000);
 541     addr |= ((caddr[2] <<8) & 0xff00);
 542     addr |= (caddr[3] & 0xff);
 543     memset((void *) &him4, 0, sizeof(him4));
 544     him4.sin_addr.s_addr = (uint32_t) htonl(addr);
 545     him4.sin_family = AF_INET;
 546     sa = (struct sockaddr *) &him4;
 547     len = sizeof(him4);
 548 
 549     error = getnameinfo(sa, len, host, NI_MAXHOST, NULL, 0,
 550                         NI_NAMEREQD);
 551 
 552     if (!error) {
 553         ret = (*env)->NewStringUTF(env, host);
 554     }
 555 
 556     if (ret == NULL) {
 557         JNU_ThrowByName(env, JNU_JAVANETPKG "UnknownHostException", NULL);
 558     }
 559 
 560     return ret;
 561 }
 562 
 563 #endif /* _ALLBSD_SOURCE */
 564 
 565 #define SET_NONBLOCKING(fd) {           \
 566         int flags = fcntl(fd, F_GETFL); \
 567         flags |= O_NONBLOCK;            \
 568         fcntl(fd, F_SETFL, flags);      \
 569 }
 570 
 571 /**
 572  * ping implementation.
 573  * Send a ICMP_ECHO_REQUEST packet every second until either the timeout
 574  * expires or a answer is received.
 575  * Returns true is an ECHO_REPLY is received, otherwise, false.
 576  */
 577 static jboolean
 578 ping4(JNIEnv *env, jint fd, struct sockaddr_in* him, jint timeout,
 579       struct sockaddr_in* netif, jint ttl) {
 580     jint size;
 581     jint n, hlen1, icmplen;
 582     socklen_t len;
 583     char sendbuf[1500];
 584     char recvbuf[1500];
 585     struct icmp *icmp;
 586     struct ip *ip;
 587     struct sockaddr_in sa_recv;
 588     jchar pid;
 589     jint tmout2, seq = 1;
 590     struct timeval tv;
 591     size_t plen;
 592 
 593     /* icmp_id is a 16 bit data type, therefore down cast the pid */
 594     pid = (jchar)getpid();
 595     size = 60*1024;
 596     setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size));
 597     /*
 598      * sets the ttl (max number of hops)
 599      */
 600     if (ttl > 0) {
 601       setsockopt(fd, IPPROTO_IP, IP_TTL, &ttl, sizeof(ttl));
 602     }
 603     /*
 604      * a specific interface was specified, so let's bind the socket
 605      * to that interface to ensure the requests are sent only through it.
 606      */
 607     if (netif != NULL) {
 608       if (bind(fd, (struct sockaddr*)netif, sizeof(struct sockaddr_in)) < 0) {
 609         NET_ThrowNew(env, errno, "Can't bind socket");
 610         close(fd);
 611         return JNI_FALSE;
 612       }
 613     }
 614     /*
 615      * Make the socket non blocking so we can use select
 616      */
 617     SET_NONBLOCKING(fd);
 618     do {
 619       /*
 620        * create the ICMP request
 621        */
 622       icmp = (struct icmp *) sendbuf;
 623       icmp->icmp_type = ICMP_ECHO;
 624       icmp->icmp_code = 0;
 625       icmp->icmp_id = htons(pid);
 626       icmp->icmp_seq = htons(seq);
 627       seq++;
 628       gettimeofday(&tv, NULL);
 629       memcpy(icmp->icmp_data, &tv, sizeof(tv));
 630       plen = ICMP_ADVLENMIN + sizeof(tv);
 631       icmp->icmp_cksum = 0;
 632       icmp->icmp_cksum = in_cksum((u_short *)icmp, plen);
 633       /*
 634        * send it
 635        */
 636       n = sendto(fd, sendbuf, plen, 0, (struct sockaddr *)him,
 637                  sizeof(struct sockaddr));
 638       if (n < 0 && errno != EINPROGRESS ) {
 639 #ifdef __linux__
 640         if (errno != EINVAL && errno != EHOSTUNREACH)
 641           /*
 642            * On some Linux versions, when a socket is bound to the loopback
 643            * interface, sendto will fail and errno will be set to
 644            * EINVAL or EHOSTUNREACH. When that happens, don't throw an
 645            * exception, just return false.
 646            */
 647 #endif /*__linux__ */
 648           NET_ThrowNew(env, errno, "Can't send ICMP packet");
 649         close(fd);
 650         return JNI_FALSE;
 651       }
 652 
 653       tmout2 = timeout > 1000 ? 1000 : timeout;
 654       do {
 655         tmout2 = NET_Wait(env, fd, NET_WAIT_READ, tmout2);
 656         if (tmout2 >= 0) {
 657           len = sizeof(sa_recv);
 658           n = recvfrom(fd, recvbuf, sizeof(recvbuf), 0, (struct sockaddr *)&sa_recv, &len);
 659           ip = (struct ip*) recvbuf;
 660           hlen1 = (ip->ip_hl) << 2;
 661           icmp = (struct icmp *) (recvbuf + hlen1);
 662           icmplen = n - hlen1;
 663           /*
 664            * We did receive something, but is it what we were expecting?
 665            * I.E.: A ICMP_ECHOREPLY packet with the proper PID.
 666            */
 667           if (icmplen >= 8 && icmp->icmp_type == ICMP_ECHOREPLY
 668                && (ntohs(icmp->icmp_id) == pid)) {
 669             if ((him->sin_addr.s_addr == sa_recv.sin_addr.s_addr)) {
 670               close(fd);
 671               return JNI_TRUE;
 672             }
 673 
 674             if (him->sin_addr.s_addr == 0) {
 675               close(fd);
 676               return JNI_TRUE;
 677             }
 678          }
 679 
 680         }
 681       } while (tmout2 > 0);
 682       timeout -= 1000;
 683     } while (timeout >0);
 684     close(fd);
 685     return JNI_FALSE;
 686 }
 687 
 688 /*
 689  * Class:     java_net_Inet4AddressImpl
 690  * Method:    isReachable0
 691  * Signature: ([bI[bI)Z
 692  */
 693 JNIEXPORT jboolean JNICALL
 694 Java_java_net_Inet4AddressImpl_isReachable0(JNIEnv *env, jobject this,
 695                                            jbyteArray addrArray,
 696                                            jint timeout,
 697                                            jbyteArray ifArray,
 698                                            jint ttl) {
 699     jint addr;
 700     jbyte caddr[4];
 701     jint fd;
 702     struct sockaddr_in him;
 703     struct sockaddr_in* netif = NULL;
 704     struct sockaddr_in inf;
 705     int len = 0;
 706     int connect_rv = -1;
 707     int sz;
 708 
 709     memset((char *) caddr, 0, sizeof(caddr));
 710     memset((char *) &him, 0, sizeof(him));
 711     memset((char *) &inf, 0, sizeof(inf));
 712     sz = (*env)->GetArrayLength(env, addrArray);
 713     if (sz != 4) {
 714       return JNI_FALSE;
 715     }
 716     (*env)->GetByteArrayRegion(env, addrArray, 0, 4, caddr);
 717     addr = ((caddr[0]<<24) & 0xff000000);
 718     addr |= ((caddr[1] <<16) & 0xff0000);
 719     addr |= ((caddr[2] <<8) & 0xff00);
 720     addr |= (caddr[3] & 0xff);
 721     addr = htonl(addr);
 722     him.sin_addr.s_addr = addr;
 723     him.sin_family = AF_INET;
 724     len = sizeof(him);
 725     /*
 726      * If a network interface was specified, let's create the address
 727      * for it.
 728      */
 729     if (!(IS_NULL(ifArray))) {
 730       memset((char *) caddr, 0, sizeof(caddr));
 731       (*env)->GetByteArrayRegion(env, ifArray, 0, 4, caddr);
 732       addr = ((caddr[0]<<24) & 0xff000000);
 733       addr |= ((caddr[1] <<16) & 0xff0000);
 734       addr |= ((caddr[2] <<8) & 0xff00);
 735       addr |= (caddr[3] & 0xff);
 736       addr = htonl(addr);
 737       inf.sin_addr.s_addr = addr;
 738       inf.sin_family = AF_INET;
 739       inf.sin_port = 0;
 740       netif = &inf;
 741     }
 742 
 743     /*
 744      * Let's try to create a RAW socket to send ICMP packets
 745      * This usually requires "root" privileges, so it's likely to fail.
 746      */
 747     fd = JVM_Socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
 748     if (fd != -1) {
 749       /*
 750        * It didn't fail, so we can use ICMP_ECHO requests.
 751        */
 752       return ping4(env, fd, &him, timeout, netif, ttl);
 753     }
 754 
 755     /*
 756      * Can't create a raw socket, so let's try a TCP socket
 757      */
 758     fd = JVM_Socket(AF_INET, SOCK_STREAM, 0);
 759     if (fd == JVM_IO_ERR) {
 760         /* note: if you run out of fds, you may not be able to load
 761          * the exception class, and get a NoClassDefFoundError
 762          * instead.
 763          */
 764         NET_ThrowNew(env, errno, "Can't create socket");
 765         return JNI_FALSE;
 766     }
 767     if (ttl > 0) {
 768       setsockopt(fd, IPPROTO_IP, IP_TTL, &ttl, sizeof(ttl));
 769     }
 770 
 771     /*
 772      * A network interface was specified, so let's bind to it.
 773      */
 774     if (netif != NULL) {
 775       if (bind(fd, (struct sockaddr*)netif, sizeof(struct sockaddr_in)) < 0) {
 776         NET_ThrowNew(env, errno, "Can't bind socket");
 777         close(fd);
 778         return JNI_FALSE;
 779       }
 780     }
 781 
 782     /*
 783      * Make the socket non blocking so we can use select/poll.
 784      */
 785     SET_NONBLOCKING(fd);
 786 
 787     /* no need to use NET_Connect as non-blocking */
 788     him.sin_port = htons(7);    /* Echo */
 789     connect_rv = JVM_Connect(fd, (struct sockaddr *)&him, len);
 790 
 791     /**
 792      * connection established or refused immediately, either way it means
 793      * we were able to reach the host!
 794      */
 795     if (connect_rv == 0 || errno == ECONNREFUSED) {
 796         close(fd);
 797         return JNI_TRUE;
 798     } else {
 799         int optlen;
 800 
 801         switch (errno) {
 802         case ENETUNREACH: /* Network Unreachable */
 803         case EAFNOSUPPORT: /* Address Family not supported */
 804         case EADDRNOTAVAIL: /* address is not available on  the  remote machine */
 805 #ifdef __linux__
 806         case EINVAL:
 807         case EHOSTUNREACH:
 808           /*
 809            * On some Linux versions, when a socket is bound to the loopback
 810            * interface, connect will fail and errno will be set to EINVAL
 811            * or EHOSTUNREACH.  When that happens, don't throw an exception,
 812            * just return false.
 813            */
 814 #endif /* __linux__ */
 815           close(fd);
 816           return JNI_FALSE;
 817         }
 818 
 819         if (errno != EINPROGRESS) {
 820           NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "ConnectException",
 821                                        "connect failed");
 822           close(fd);
 823           return JNI_FALSE;
 824         }
 825 
 826         timeout = NET_Wait(env, fd, NET_WAIT_CONNECT, timeout);
 827         if (timeout >= 0) {
 828           /* has connection been established? */
 829           optlen = sizeof(connect_rv);
 830           if (JVM_GetSockOpt(fd, SOL_SOCKET, SO_ERROR, (void*)&connect_rv,
 831                              &optlen) <0) {
 832             connect_rv = errno;
 833           }
 834           if (connect_rv == 0 || connect_rv == ECONNREFUSED) {
 835             close(fd);
 836             return JNI_TRUE;
 837           }
 838         }
 839         close(fd);
 840         return JNI_FALSE;
 841     }
 842 }