1/*
2 *  Licensed to the Apache Software Foundation (ASF) under one or more
3 *  contributor license agreements.  See the NOTICE file distributed with
4 *  this work for additional information regarding copyright ownership.
5 *  The ASF licenses this file to You under the Apache License, Version 2.0
6 *  (the "License"); you may not use this file except in compliance with
7 *  the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *  Unless required by applicable law or agreed to in writing, software
12 *  distributed under the License is distributed on an "AS IS" BASIS,
13 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *  See the License for the specific language governing permissions and
15 *  limitations under the License.
16 */
17
18package org.apache.harmony.luni.tests.java.net;
19
20import dalvik.annotation.BrokenTest;
21import dalvik.annotation.TestTargetClass;
22import dalvik.annotation.TestTargets;
23import dalvik.annotation.TestLevel;
24import dalvik.annotation.TestTargetNew;
25
26import java.io.IOException;
27import java.io.Serializable;
28import java.net.DatagramSocket;
29import java.net.Inet4Address;
30import java.net.Inet6Address;
31import java.net.InetAddress;
32import java.net.NetworkInterface;
33import java.net.UnknownHostException;
34import java.security.Permission;
35import java.util.ArrayList;
36import java.util.Enumeration;
37
38import org.apache.harmony.testframework.serialization.SerializationTest;
39import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
40
41import tests.support.Support_Configuration;
42import tests.util.TestEnvironment;
43
44@TestTargetClass(InetAddress.class)
45public class InetAddressTest extends junit.framework.TestCase {
46
47    private static boolean someoneDone[] = new boolean[2];
48
49    protected static boolean threadedTestSucceeded;
50
51    protected static String threadedTestErrorString;
52
53    @Override protected void setUp() throws Exception {
54        super.setUp();
55        TestEnvironment.reset();
56    }
57
58    @Override protected void tearDown() throws Exception {
59        TestEnvironment.reset();
60        super.tearDown();
61    }
62
63    /**
64     * This class is used to test inet_ntoa, gethostbyaddr and gethostbyname
65     * functions in the VM to make sure they're threadsafe. getByName will cause
66     * the gethostbyname function to be called. getHostName will cause the
67     * gethostbyaddr to be called. getHostAddress will cause inet_ntoa to be
68     * called.
69     */
70    static class threadsafeTestThread extends Thread {
71        private String lookupName;
72
73        private InetAddress testAddress;
74
75        private int testType;
76
77        /*
78         * REP_NUM can be adjusted if desired. Since this error is
79         * non-deterministic it may not always occur. Setting REP_NUM higher,
80         * increases the chances of an error being detected, but causes the test
81         * to take longer. Because the Java threads spend a lot of time
82         * performing operations other than running the native code that may not
83         * be threadsafe, it is quite likely that several thousand iterations
84         * will elapse before the first error is detected.
85         */
86        private static final int REP_NUM = 20000;
87
88        public threadsafeTestThread(String name, String lookupName,
89                InetAddress testAddress, int type) {
90            super(name);
91            this.lookupName = lookupName;
92            this.testAddress = testAddress;
93            testType = type;
94        }
95
96        public void run() {
97            try {
98                String correctName = testAddress.getHostName();
99                String correctAddress = testAddress.getHostAddress();
100                long startTime = System.currentTimeMillis();
101
102                synchronized (someoneDone) {
103                }
104
105                for (int i = 0; i < REP_NUM; i++) {
106                    if (someoneDone[testType]) {
107                        break;
108                    } else if ((i % 25) == 0
109                            && System.currentTimeMillis() - startTime > 240000) {
110                        System.out
111                                .println("Exiting due to time limitation after "
112                                        + i + " iterations");
113                        break;
114                    }
115
116                    InetAddress ia = InetAddress.getByName(lookupName);
117                    String hostName = ia.getHostName();
118                    String hostAddress = ia.getHostAddress();
119
120                    // Intentionally not looking for exact name match so that
121                    // the test works across different platforms that may or
122                    // may not include a domain suffix on the hostname
123                    if (!hostName.startsWith(correctName)) {
124                        threadedTestSucceeded = false;
125                        threadedTestErrorString = (testType == 0 ? "gethostbyname"
126                                : "gethostbyaddr")
127                                + ": getHostName() returned "
128                                + hostName
129                                + " instead of " + correctName;
130                        break;
131                    }
132                    // IP addresses should match exactly
133                    if (!correctAddress.equals(hostAddress)) {
134                        threadedTestSucceeded = false;
135                        threadedTestErrorString = (testType == 0 ? "gethostbyname"
136                                : "gethostbyaddr")
137                                + ": getHostName() returned "
138                                + hostAddress
139                                + " instead of " + correctAddress;
140                        break;
141                    }
142
143                }
144                someoneDone[testType] = true;
145            } catch (Exception e) {
146                threadedTestSucceeded = false;
147                threadedTestErrorString = e.toString();
148            }
149        }
150    }
151
152    /**
153     * @tests java.net.InetAddress#equals(java.lang.Object)
154     */
155    @TestTargetNew(
156        level = TestLevel.COMPLETE,
157        notes = "",
158        method = "equals",
159        args = {java.lang.Object.class}
160    )
161    public void test_equalsLjava_lang_Object() {
162        // Test for method boolean java.net.InetAddress.equals(java.lang.Object)
163        try {
164            InetAddress ia1 = InetAddress
165                    .getByName(Support_Configuration.InetTestAddress);
166            InetAddress ia2 = InetAddress
167                    .getByName(Support_Configuration.InetTestIP);
168            assertTrue("Equals returned incorrect result - " + ia1 + " != "
169                    + ia2, ia1.equals(ia2));
170        } catch (Exception e) {
171            fail("Exception during equals test : " + e.getMessage());
172        }
173    }
174
175    /**
176     * @tests java.net.InetAddress#getAddress()
177     */
178    @TestTargetNew(
179        level = TestLevel.COMPLETE,
180        notes = "",
181        method = "getAddress",
182        args = {}
183    )
184    public void test_getAddress() {
185        // Test for method byte [] java.net.InetAddress.getAddress()
186        try {
187            InetAddress ia = InetAddress
188                    .getByName(Support_Configuration.InetTestIP);
189            // BEGIN android-changed
190            // using different address. The old one was { 9, 26, -56, -111 }
191            // this lead to a crash, also in RI.
192            byte[] caddr = Support_Configuration.InetTestAddr;
193            // END android-changed
194            byte[] addr = ia.getAddress();
195            for (int i = 0; i < addr.length; i++)
196                assertTrue("Incorrect address returned", caddr[i] == addr[i]);
197        } catch (java.net.UnknownHostException e) {
198        }
199    }
200
201    /**
202     * @tests java.net.InetAddress#getAllByName(java.lang.String)
203     */
204    @TestTargetNew(
205        level = TestLevel.COMPLETE,
206        notes = "",
207        method = "getAllByName",
208        args = {java.lang.String.class}
209    )
210    public void test_getAllByNameLjava_lang_String() throws Exception {
211        // Test for method java.net.InetAddress []
212        // java.net.InetAddress.getAllByName(java.lang.String)
213        InetAddress[] all = InetAddress
214                .getAllByName(Support_Configuration.SpecialInetTestAddress);
215        assertNotNull(all);
216        // Number of aliases depends on individual test machine
217        assertTrue(all.length >= 1);
218        for (InetAddress alias : all) {
219            // Check that each alias has the same hostname. Intentionally not
220            // checking for exact string match.
221            assertTrue(alias.getHostName().startsWith(
222                    Support_Configuration.SpecialInetTestAddress));
223        }// end for all aliases
224
225        // check the getByName if there is a security manager.
226        SecurityManager oldman = System.getSecurityManager();
227        System.setSecurityManager(new MockSecurityManager());
228        try {
229            boolean exception = false;
230            try {
231                InetAddress.getByName("3d.com");
232            } catch (SecurityException ex) {
233                exception = true;
234            } catch (Exception ex) {
235                fail("getByName threw wrong exception : " + ex.getMessage());
236            }
237            assertTrue("expected SecurityException", exception);
238        } finally {
239            System.setSecurityManager(oldman);
240        }
241
242        // Regression for HARMONY-56
243        InetAddress[] addresses = InetAddress.getAllByName(null);
244        assertTrue("getAllByName(null): no results", addresses.length > 0);
245        for (int i = 0; i < addresses.length; i++) {
246            InetAddress address = addresses[i];
247            assertTrue("Assert 1: getAllByName(null): " + address +
248                    " is not loopback", address.isLoopbackAddress());
249        }
250
251        try {
252            InetAddress.getAllByName("unknown.host");
253            fail("UnknownHostException was not thrown.");
254        } catch(UnknownHostException uhe) {
255            //expected
256        }
257    }
258
259    /**
260     * @tests java.net.InetAddress#getByName(java.lang.String)
261     */
262    @TestTargetNew(
263        level = TestLevel.PARTIAL_COMPLETE,
264        notes = "",
265        method = "getByName",
266        args = {java.lang.String.class}
267    )
268    public void test_getByNameLjava_lang_String() throws Exception {
269        // Test for method java.net.InetAddress
270        // java.net.InetAddress.getByName(java.lang.String)
271        InetAddress ia2 = InetAddress
272                .getByName(Support_Configuration.InetTestIP);
273
274        // Intentionally not testing for exact string match
275        /* FIXME: comment the assertion below because it is platform/configuration dependent
276         * Please refer to HARMONY-1664 (https://issues.apache.org/jira/browse/HARMONY-1664)
277         * for details
278         */
279//        assertTrue(
280//        "Expected " + Support_Configuration.InetTestAddress + "*",
281//            ia2.getHostName().startsWith(Support_Configuration.InetTestAddress));
282
283        // TODO : Test to ensure all the address formats are recognized
284        InetAddress i = InetAddress.getByName("1.2.3");
285        assertEquals("1.2.0.3",i.getHostAddress());
286        i = InetAddress.getByName("1.2");
287        assertEquals("1.0.0.2",i.getHostAddress());
288        i = InetAddress.getByName(String.valueOf(0xffffffffL));
289        assertEquals("255.255.255.255",i.getHostAddress());
290        // BEGIN android-removed
291        // This test checks a bug in the RI that allows any number of '.' after
292        // a valid ipv4 address. This bug doesn't exist in this implementation.
293        // String s = "222.222.222.222....";
294        // i = InetAddress.getByName(s);
295        // assertEquals("222.222.222.222",i.getHostAddress());
296        // END android-removed
297
298        class MockSecurityManager extends SecurityManager {
299            public void checkPermission(Permission permission) {
300                if (permission.getName().equals("setSecurityManager")){
301                    return;
302                }
303                if (permission.getName().equals("3d.com")){
304                    throw new SecurityException();
305                }
306                super.checkPermission(permission);
307            }
308
309            public void checkConnect(String host, int port) {
310                if(host.equals("google.com")) {
311                    throw new SecurityException();
312                }
313            }
314        }
315        SecurityManager oldman = System.getSecurityManager();
316        System.setSecurityManager(new MockSecurityManager());
317        try {
318            boolean exception = false;
319            try {
320                InetAddress.getByName("google.com");
321                fail("SecurityException was not thrown.");
322            } catch (SecurityException ex) {
323                //expected
324            } catch (Exception ex) {
325                fail("getByName threw wrong exception : " + ex.getMessage());
326            }
327        } finally {
328            System.setSecurityManager(oldman);
329        }
330
331        try {
332            InetAddress.getByName("0.0.0.0.0");
333            fail("UnknownHostException was not thrown.");
334        } catch(UnknownHostException ue) {
335            //expected
336        }
337    }
338
339    /**
340     * @tests java.net.InetAddress#getHostAddress()
341     */
342    @TestTargetNew(
343        level = TestLevel.COMPLETE,
344        notes = "",
345        method = "getHostAddress",
346        args = {}
347    )
348    public void test_getHostAddress() {
349        // Test for method java.lang.String
350        // java.net.InetAddress.getHostAddress()
351        try {
352            InetAddress ia2 = InetAddress
353                    .getByName(Support_Configuration.InetTestAddress);
354            assertTrue("getHostAddress returned incorrect result: "
355                    + ia2.getHostAddress() + " != "
356                    + Support_Configuration.InetTestIP, ia2.getHostAddress()
357                    .equals(Support_Configuration.InetTestIP));
358        } catch (Exception e) {
359            fail("Exception during getHostAddress test : " + e.getMessage());
360        }
361    }
362
363    /**
364     * @tests java.net.InetAddress#getHostName()
365     */
366    @TestTargetNew(
367        level = TestLevel.COMPLETE,
368        notes = "",
369        method = "getHostName",
370        args = {}
371    )
372    public void test_getHostName() throws Exception {
373        // Test for method java.lang.String java.net.InetAddress.getHostName()
374        InetAddress ia = InetAddress
375                .getByName(Support_Configuration.InetTestIP);
376
377        // Intentionally not testing for exact string match
378        /* FIXME: comment the assertion below because it is platform/configuration dependent
379         * Please refer to HARMONY-1664 (https://issues.apache.org/jira/browse/HARMONY-1664)
380         * for details
381         */
382//        assertTrue(
383//        "Expected " + Support_Configuration.InetTestAddress + "*",
384//        ia.getHostName().startsWith(Support_Configuration.InetTestAddress));
385
386        // Test for any of the host lookups, where the default SecurityManager
387        // is installed.
388
389        SecurityManager oldman = System.getSecurityManager();
390        try {
391            String exp = Support_Configuration.InetTestIP;
392            System.setSecurityManager(new MockSecurityManager());
393            ia = InetAddress.getByName(exp);
394            String ans = ia.getHostName();
395        /* FIXME: comment the assertion below because it is platform/configuration dependent
396         * Please refer to HARMONY-1664 (https://issues.apache.org/jira/browse/HARMONY-1664)
397         * for details
398         */
399        //    assertEquals(Support_Configuration.InetTestIP, ans);
400        } finally {
401            System.setSecurityManager(oldman);
402        }
403
404        // Make sure there is no caching
405        System.setProperty("networkaddress.cache.ttl", "0");
406
407        // Test for threadsafety
408        InetAddress lookup1 = InetAddress
409                .getByName(Support_Configuration.InetTestAddress);
410        assertTrue(lookup1 + " expected "
411                + Support_Configuration.InetTestIP,
412                Support_Configuration.InetTestIP.equals(lookup1
413                        .getHostAddress()));
414        InetAddress lookup2 = InetAddress
415                .getByName(Support_Configuration.InetTestAddress2);
416        assertTrue(lookup2 + " expected "
417                + Support_Configuration.InetTestIP2,
418                Support_Configuration.InetTestIP2.equals(lookup2
419                        .getHostAddress()));
420        threadsafeTestThread thread1 = new threadsafeTestThread("1",
421                lookup1.getHostName(), lookup1, 0);
422        threadsafeTestThread thread2 = new threadsafeTestThread("2",
423                lookup2.getHostName(), lookup2, 0);
424        threadsafeTestThread thread3 = new threadsafeTestThread("3",
425                lookup1.getHostAddress(), lookup1, 1);
426        threadsafeTestThread thread4 = new threadsafeTestThread("4",
427                lookup2.getHostAddress(), lookup2, 1);
428
429        // initialize the flags
430        threadedTestSucceeded = true;
431        synchronized (someoneDone) {
432            thread1.start();
433            thread2.start();
434            thread3.start();
435            thread4.start();
436        }
437        thread1.join();
438        thread2.join();
439        thread3.join();
440        thread4.join();
441        /* FIXME: comment the assertion below because it is platform/configuration dependent
442        * Please refer to HARMONY-1664 (https://issues.apache.org/jira/browse/HARMONY-1664)
443        * for details
444        */
445//            assertTrue(threadedTestErrorString, threadedTestSucceeded);
446    }
447
448    /**
449     * @tests java.net.InetAddress#getLocalHost()
450     */
451    @TestTargetNew(
452        level = TestLevel.SUFFICIENT,
453        notes = "UnknownHostException should be thrown if no IP address for the host could be found.",
454        method = "getLocalHost",
455        args = {}
456    )
457    public void test_getLocalHost() {
458        // Test for method java.net.InetAddress
459        // java.net.InetAddress.getLocalHost()
460        try {
461            // We don't know the host name or ip of the machine
462            // running the test, so we can't build our own address
463            DatagramSocket dg = new DatagramSocket(0, InetAddress
464                    .getLocalHost());
465            assertTrue("Incorrect host returned", InetAddress.getLocalHost()
466                    .equals(dg.getLocalAddress()));
467            dg.close();
468        } catch (Exception e) {
469            fail("Exception during getLocalHost test : " + e.getMessage());
470        }
471    }
472
473    /**
474     * @tests java.net.InetAddress#hashCode()
475     */
476    @TestTargetNew(
477        level = TestLevel.COMPLETE,
478        notes = "",
479        method = "hashCode",
480        args = {}
481    )
482    int getHashCode(String literal) {
483        InetAddress host = null;
484        try {
485            host = InetAddress.getByName(literal);
486        } catch(UnknownHostException e) {
487            fail("Exception during hashCode test : " + e.getMessage());
488        }
489        return host.hashCode();
490    }
491
492    public void test_hashCode() {
493        int hashCode = getHashCode(Support_Configuration.InetTestIP);
494        int ip6HashCode = getHashCode(Support_Configuration.InetTestIP6);
495        int ip6LOHashCode = getHashCode(Support_Configuration.InetTestIP6LO);
496        assertFalse("Hash collision", hashCode == ip6HashCode);
497        assertFalse("Hash collision", ip6HashCode == ip6LOHashCode);
498        assertFalse("Hash collision", hashCode == ip6LOHashCode);
499        assertFalse("Hash collision", ip6LOHashCode == 0);
500        assertFalse("Hash collision", ip6LOHashCode == 1);
501    }
502
503    /**
504     * @tests java.net.InetAddress#isMulticastAddress()
505     */
506    @TestTargetNew(
507        level = TestLevel.COMPLETE,
508        notes = "",
509        method = "isMulticastAddress",
510        args = {}
511    )
512    public void test_isMulticastAddress() {
513        // Test for method boolean java.net.InetAddress.isMulticastAddress()
514        try {
515            InetAddress ia1 = InetAddress.getByName("ff02::1");
516            assertTrue("isMulticastAddress returned incorrect result", ia1
517                    .isMulticastAddress());
518            InetAddress ia2 = InetAddress.getByName("239.255.255.255");
519            assertTrue("isMulticastAddress returned incorrect result", ia2
520                    .isMulticastAddress());
521            InetAddress ia3 = InetAddress.getByName("fefb::");
522            assertFalse("isMulticastAddress returned incorrect result", ia3
523                    .isMulticastAddress());
524            InetAddress ia4 = InetAddress.getByName("10.0.0.1");
525            assertFalse("isMulticastAddress returned incorrect result", ia4
526                    .isMulticastAddress());
527        } catch (Exception e) {
528            fail("Exception during isMulticastAddress test : " + e.getMessage());
529        }
530    }
531
532    /**
533     * @tests java.net.InetAddress#toString()
534     */
535    @TestTargetNew(
536        level = TestLevel.COMPLETE,
537        notes = "",
538        method = "toString",
539        args = {}
540    )
541    public void test_toString() throws Exception {
542        // Test for method java.lang.String java.net.InetAddress.toString()
543        InetAddress ia2 = InetAddress
544                .getByName(Support_Configuration.InetTestIP);
545        assertEquals("/" + Support_Configuration.InetTestIP, ia2.toString());
546        // Regression for HARMONY-84
547        InetAddress addr = InetAddress.getByName("localhost");
548        assertEquals("Assert 0: wrong string from name", "localhost/127.0.0.1", addr.toString());
549        InetAddress addr2 = InetAddress.getByAddress(new byte[]{127, 0, 0, 1});
550        assertEquals("Assert 1: wrong string from address", "/127.0.0.1", addr2.toString());
551    }
552
553    /**
554     * @tests java.net.InetAddress#getByAddress(java.lang.String, byte[])
555     */
556    @TestTargetNew(
557        level = TestLevel.COMPLETE,
558        notes = "",
559        method = "getByAddress",
560        args = {java.lang.String.class, byte[].class}
561    )
562    public void test_getByAddressLjava_lang_String$B() {
563        // Check an IPv4 address with an IPv6 hostname
564        byte ipAddress[] = { 127, 0, 0, 1 };
565        String addressStr = "::1";
566        try {
567            InetAddress addr = InetAddress.getByAddress(addressStr, ipAddress);
568            addr = InetAddress.getByAddress(ipAddress);
569        } catch (UnknownHostException e) {
570            fail("Unexpected problem creating IP Address "
571                    + ipAddress.length);
572        }
573
574        byte ipAddress2[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, 127, 0, 0,
575                1 };
576        addressStr = "::1";
577        try {
578            InetAddress addr = InetAddress.getByAddress(addressStr, ipAddress2);
579            addr = InetAddress.getByAddress(ipAddress);
580        } catch (UnknownHostException e) {
581            fail("Unexpected problem creating IP Address "
582                    + ipAddress.length);
583        }
584
585        try {
586            InetAddress addr = InetAddress.getByAddress(addressStr,
587                    new byte [] {0, 0, 0, 0, 0});
588            fail("UnknownHostException was thrown.");
589        } catch(UnknownHostException uhe) {
590            //expected
591        }
592    }
593
594    /**
595     * @tests java.net.InetAddress#getCanonicalHostName()
596     */
597    @TestTargetNew(
598        level = TestLevel.COMPLETE,
599        notes = "",
600        method = "getCanonicalHostName",
601        args = {}
602    )
603    public void test_getCanonicalHostName() throws Exception {
604        InetAddress theAddress = null;
605        theAddress = InetAddress.getLocalHost();
606        assertTrue("getCanonicalHostName returned a zero length string ",
607                theAddress.getCanonicalHostName().length() != 0);
608        assertTrue("getCanonicalHostName returned an empty string ",
609                !theAddress.equals(""));
610
611        // test against an expected value
612        InetAddress ia = InetAddress
613                .getByName(Support_Configuration.InetTestIP);
614
615        // Intentionally not testing for exact string match
616        /* FIXME: comment the assertion below because it is platform/configuration dependent
617         * Please refer to HARMONY-1664 (https://issues.apache.org/jira/browse/HARMONY-1664)
618         * for details
619         */
620//        assertTrue(
621//           "Expected " + Support_Configuration.InetTestAddress + "*",
622//           ia.getCanonicalHostName().startsWith(Support_Configuration.InetTestAddress));
623    }
624
625    /**
626     * @tests java.net.InetAddress#isReachableI
627     */
628    @TestTargetNew(
629        level = TestLevel.SUFFICIENT,
630        notes = "IOException checking missed (if network error occurs).",
631        method = "isReachable",
632        args = {int.class}
633    )
634    public void test_isReachableI() throws Exception {
635        InetAddress ia = Inet4Address.getByName("127.0.0.1");
636        assertTrue(ia.isReachable(10000));
637        ia = Inet4Address.getByName("127.0.0.1");
638        try {
639            ia.isReachable(-1);
640            fail("Should throw IllegalArgumentException");
641        } catch (IllegalArgumentException e) {
642            // correct
643        }
644    }
645
646    /**
647     * @tests java.net.InetAddress#isReachableLjava_net_NetworkInterfaceII
648     */
649    @TestTargetNew(
650        level = TestLevel.SUFFICIENT,
651        notes = "IOException checking missed (if network error occurs).",
652        method = "isReachable",
653        args = {java.net.NetworkInterface.class, int.class, int.class}
654    )
655    @BrokenTest("Depends on external network address and shows different" +
656            "behavior with WLAN and 3G networks")
657    public void test_isReachableLjava_net_NetworkInterfaceII() throws Exception {
658        // tests local address
659        InetAddress ia = Inet4Address.getByName("127.0.0.1");
660        assertTrue(ia.isReachable(null, 0, 10000));
661        ia = Inet4Address.getByName("127.0.0.1");
662        try {
663            ia.isReachable(null, -1, 10000);
664            fail("Should throw IllegalArgumentException");
665        } catch (IllegalArgumentException e) {
666            // correct
667        }
668        try {
669            ia.isReachable(null, 0, -1);
670            fail("Should throw IllegalArgumentException");
671        } catch (IllegalArgumentException e) {
672            // correct
673        }
674        try {
675            ia.isReachable(null, -1, -1);
676            fail("Should throw IllegalArgumentException");
677        } catch (IllegalArgumentException e) {
678            // correct
679        }
680        // tests nowhere
681        ia = Inet4Address.getByName("1.1.1.1");
682        assertFalse(ia.isReachable(1000));
683        assertFalse(ia.isReachable(null, 0, 1000));
684
685        // Regression test for HARMONY-1842.
686        ia = InetAddress.getByName("localhost"); //$NON-NLS-1$
687        Enumeration<NetworkInterface> nif = NetworkInterface.getNetworkInterfaces();
688        NetworkInterface netif;
689        while(nif.hasMoreElements()) {
690            netif = nif.nextElement();
691            ia.isReachable(netif, 10, 1000);
692        }
693    }
694
695    // comparator for InetAddress objects
696    private static final SerializableAssert COMPARATOR = new SerializableAssert() {
697        public void assertDeserialized(Serializable initial,
698                Serializable deserialized) {
699
700            InetAddress initAddr = (InetAddress) initial;
701            InetAddress desrAddr = (InetAddress) deserialized;
702
703            byte[] iaAddresss = initAddr.getAddress();
704            byte[] deIAAddresss = desrAddr.getAddress();
705            for (int i = 0; i < iaAddresss.length; i++) {
706                assertEquals(iaAddresss[i], deIAAddresss[i]);
707            }
708            assertEquals(initAddr.getHostName(), desrAddr.getHostName());
709        }
710    };
711
712    // Regression Test for Harmony-2290
713    @TestTargetNew(
714        level = TestLevel.ADDITIONAL,
715        notes = "Regeression test. Functional test.",
716        method = "isReachable",
717        args = {java.net.NetworkInterface.class, int.class, int.class}
718    )
719    public void test_isReachableLjava_net_NetworkInterfaceII_loopbackInterface() throws IOException {
720        final int TTL = 20;
721        final int TIME_OUT = 3000;
722
723        NetworkInterface loopbackInterface = null;
724        ArrayList<InetAddress> localAddresses = new ArrayList<InetAddress>();
725        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
726                .getNetworkInterfaces();
727        while (networkInterfaces.hasMoreElements()) {
728            NetworkInterface networkInterface = networkInterfaces.nextElement();
729            Enumeration<InetAddress> addresses = networkInterface
730                    .getInetAddresses();
731            while (addresses.hasMoreElements()) {
732                InetAddress address = addresses.nextElement();
733                if (address.isLoopbackAddress()) {
734                    loopbackInterface = networkInterface;
735                } else {
736                    localAddresses.add(address);
737                }
738            }
739        }
740
741        //loopbackInterface can reach local address
742        if (null != loopbackInterface) {
743            for (InetAddress destAddress : localAddresses) {
744                assertTrue(destAddress.isReachable(loopbackInterface, TTL, TIME_OUT));
745            }
746        }
747
748        //loopback Interface cannot reach outside address
749        InetAddress destAddress = InetAddress.getByName("www.google.com");
750        assertFalse(destAddress.isReachable(loopbackInterface, TTL, TIME_OUT));
751    }
752
753    /**
754     * @tests serialization/deserialization compatibility.
755     */
756    @TestTargetNew(
757        level = TestLevel.COMPLETE,
758        notes = "Checks serialization.",
759        method = "!SerializationSelf",
760        args = {}
761    )
762    public void testSerializationSelf() throws Exception {
763
764        SerializationTest.verifySelf(InetAddress.getByName("localhost"),
765                COMPARATOR);
766    }
767
768    /**
769     * @tests serialization/deserialization compatibility with RI.
770     */
771    @TestTargetNew(
772        level = TestLevel.COMPLETE,
773        notes = "Checks serialization.",
774        method = "!SerializationGolden",
775        args = {}
776    )
777    public void testSerializationCompatibility() throws Exception {
778
779        SerializationTest.verifyGolden(this,
780                InetAddress.getByName("localhost"), COMPARATOR);
781    }
782
783    /**
784     * @tests java.net.InetAddress#getByAddress(byte[])
785     */
786    @TestTargetNew(
787        level = TestLevel.COMPLETE,
788        notes = "",
789        method = "getByAddress",
790        args = {byte[].class}
791    )
792    public void test_getByAddress() {
793        byte ipAddress[] = { 127, 0, 0, 1 };
794        try {
795            InetAddress.getByAddress(ipAddress);
796        } catch (UnknownHostException e) {
797            fail("Unexpected problem creating IP Address "
798                    + ipAddress.length);
799        }
800
801        byte ipAddress2[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, 127, 0, 0,
802                1 };
803        try {
804            InetAddress.getByAddress(ipAddress2);
805        } catch (UnknownHostException e) {
806            fail("Unexpected problem creating IP Address "
807                    + ipAddress.length);
808        }
809
810        // Regression for HARMONY-61
811        try {
812            InetAddress.getByAddress(null);
813            fail("Assert 0: UnknownHostException must be thrown");
814        } catch (UnknownHostException e) {
815            // Expected
816        }
817
818        try {
819            byte [] byteArray = new byte[] {};
820            InetAddress.getByAddress(byteArray);
821            fail("Assert 1: UnknownHostException must be thrown");
822        } catch (UnknownHostException e) {
823            // Expected
824        }
825    }
826
827    @TestTargetNew(
828        level = TestLevel.COMPLETE,
829        notes = "",
830        method = "isAnyLocalAddress",
831        args = {}
832    )
833    public void test_isAnyLocalAddress() throws Exception {
834        byte [] ipAddress1 = { 127, 42, 42, 42 };
835        InetAddress ia1 = InetAddress.getByAddress(ipAddress1);
836        assertFalse(ia1.isAnyLocalAddress());
837
838        byte [] ipAddress2 = { 0, 0, 0, 0 };
839        InetAddress ia2 = InetAddress.getByAddress(ipAddress2);
840        assertTrue(ia2.isAnyLocalAddress());
841    }
842
843    @TestTargetNew(
844        level = TestLevel.COMPLETE,
845        notes = "",
846        method = "isLinkLocalAddress",
847        args = {}
848    )
849    public void test_isLinkLocalAddress() throws Exception {
850        String addrName = "FE80::0";
851        InetAddress addr = InetAddress.getByName(addrName);
852        assertTrue(
853                "IPv6 link local address " + addrName + " not detected.",
854                addr.isLinkLocalAddress());
855
856        addrName = "FEBF::FFFF:FFFF:FFFF:FFFF";
857        addr = Inet6Address.getByName(addrName);
858        assertTrue(
859                "IPv6 link local address " + addrName + " not detected.",
860                addr.isLinkLocalAddress());
861
862        addrName = "FEC0::1";
863        addr = Inet6Address.getByName(addrName);
864        assertTrue("IPv6 address " + addrName
865                + " detected incorrectly as a link local address.", !addr
866                .isLinkLocalAddress());
867
868        addrName = "42.42.42.42";
869        addr = Inet4Address.getByName(addrName);
870        assertTrue("IPv4 address " + addrName
871                + " incorrectly reporting as a link local address.", !addr
872                .isLinkLocalAddress());
873    }
874
875    @TestTargetNew(
876        level = TestLevel.COMPLETE,
877        notes = "",
878        method = "isLoopbackAddress",
879        args = {}
880    )
881    public void test_isLoopbackAddress() throws Exception {
882        String addrName = "127.0.0.0";
883        InetAddress addr = InetAddress.getByName(addrName);
884        assertTrue("Loopback address " + addrName + " not detected.", addr
885                .isLoopbackAddress());
886
887        addrName = "127.42.42.42";
888        addr = InetAddress.getByName(addrName);
889        assertTrue("Loopback address " + addrName + " not detected.", addr
890                .isLoopbackAddress());
891
892        addrName = "42.42.42.42";
893        addr = Inet4Address.getByName(addrName);
894        assertTrue("Address incorrectly " + addrName
895                + " detected as a loopback address.", !addr
896                .isLoopbackAddress());
897
898
899        addrName = "::FFFF:127.42.42.42";
900        addr = InetAddress.getByName(addrName);
901        assertTrue("IPv4-compatible IPv6 loopback address " + addrName
902                + " not detected.", addr.isLoopbackAddress());
903
904        addrName = "::FFFF:42.42.42.42";
905        addr = InetAddress.getByName(addrName);
906        assertTrue("IPv4-compatible IPv6 address incorrectly " + addrName
907                + " detected as a loopback address.", !addr
908                .isLoopbackAddress());
909    }
910
911    @TestTargetNew(
912        level = TestLevel.COMPLETE,
913        notes = "",
914        method = "isMCGlobal",
915        args = {}
916    )
917    public void test_isMCGlobal() throws Exception {
918        String addrName = "224.0.0.255";
919        InetAddress addr = InetAddress.getByName(addrName);
920        assertTrue("IPv4 link-local multicast address " + addrName
921                + " incorrectly identified as a global multicast address.",
922                !addr.isMCGlobal());
923
924        addrName = "224.0.1.0"; // a multicast addr 1110
925        addr = Inet4Address.getByName(addrName);
926        assertTrue("IPv4 global multicast address " + addrName
927                + " not identified as a global multicast address.", addr
928                .isMCGlobal());
929
930        addrName = "FFFE:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
931        addr = InetAddress.getByName(addrName);
932        assertTrue("IPv6 global multicast address " + addrName
933                + " not detected.", addr.isMCGlobal());
934
935        addrName = "FF08:42:42:42:42:42:42:42";
936        addr = InetAddress.getByName(addrName);
937        assertTrue("IPv6 mulitcast organizational " + addrName
938                + " incorrectly indicated as a global address.", !addr
939                .isMCGlobal());
940    }
941
942    @TestTargetNew(
943        level = TestLevel.COMPLETE,
944        notes = "",
945        method = "isMCLinkLocal",
946        args = {}
947    )
948    public void test_isMCLinkLocal() throws Exception {
949        String addrName = "224.0.0.255";
950        InetAddress addr = InetAddress.getByName(addrName);
951        assertTrue("IPv4 link-local multicast address " + addrName
952                + " not identified as a link-local multicast address.",
953                addr.isMCLinkLocal());
954
955        addrName = "224.0.1.0";
956        addr = InetAddress.getByName(addrName);
957        assertTrue(
958                "IPv4 global multicast address "
959                        + addrName
960                        + " incorrectly identified as a link-local " +
961                                "multicast address.",
962                !addr.isMCLinkLocal());
963
964        addrName = "FFF2:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
965        addr = InetAddress.getByName(addrName);
966        assertTrue("IPv6 link local multicast address " + addrName
967                + " not detected.", addr.isMCLinkLocal());
968
969        addrName = "FF08:42:42:42:42:42:42:42";
970        addr = InetAddress.getByName(addrName);
971        assertTrue(
972                "IPv6 organization multicast address "
973                        + addrName
974                        + " incorrectly indicated as a link-local " +
975                                "mulitcast address.",
976                !addr.isMCLinkLocal());
977    }
978
979    @TestTargetNew(
980        level = TestLevel.COMPLETE,
981        notes = "",
982        method = "isMCNodeLocal",
983        args = {}
984    )
985    public void test_isMCNodeLocal() throws Exception {
986        String addrName = "224.42.42.42";
987        InetAddress addr = InetAddress.getByName(addrName);
988        assertTrue(
989                "IPv4 multicast address "
990                        + addrName
991                        + " incorrectly identified as a node-local " +
992                                "multicast address.",
993                !addr.isMCNodeLocal());
994
995        addrName = "FFF1:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
996        addr = InetAddress.getByName(addrName);
997        assertTrue("IPv6 node-local multicast address " + addrName
998                + " not detected.", addr.isMCNodeLocal());
999
1000        addrName = "FF08:42:42:42:42:42:42:42";
1001        addr = InetAddress.getByName(addrName);
1002        assertTrue("IPv6 mulitcast organizational address " + addrName
1003                + " incorrectly indicated as a node-local address.", !addr
1004                .isMCNodeLocal());
1005    }
1006
1007    @TestTargetNew(
1008        level = TestLevel.COMPLETE,
1009        notes = "",
1010        method = "isMCOrgLocal",
1011        args = {}
1012    )
1013    public void test_isMCOrgLocal() throws Exception {
1014        String addrName = "239.252.0.0"; // a multicast addr 1110
1015        InetAddress addr = InetAddress.getByName(addrName);
1016        assertTrue(
1017                "IPv4 site-local multicast address "
1018                        + addrName
1019                        + " incorrectly identified as a org-local multicast address.",
1020                !addr.isMCOrgLocal());
1021
1022        addrName = "239.192.0.0"; // a multicast addr 1110
1023        addr = InetAddress.getByName(addrName);
1024        assertTrue("IPv4 org-local multicast address " + addrName
1025                + " not identified as a org-local multicast address.", addr
1026                .isMCOrgLocal());
1027
1028        addrName = "FFF8:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
1029        addr = InetAddress.getByName(addrName);
1030        assertTrue("IPv6 organization-local multicast address " + addrName
1031                + " not detected.", addr.isMCOrgLocal());
1032
1033        addrName = "FF0E:42:42:42:42:42:42:42";
1034        addr = InetAddress.getByName(addrName);
1035        assertTrue(
1036                "IPv6 global multicast address "
1037                        + addrName
1038                        + " incorrectly indicated as an organization-local mulitcast address.",
1039                !addr.isMCOrgLocal());
1040    }
1041
1042    @TestTargetNew(
1043        level = TestLevel.COMPLETE,
1044        notes = "",
1045        method = "isMCSiteLocal",
1046        args = {}
1047    )
1048    public void test_isMCSiteLocal() throws Exception {
1049        String addrName = "FFF5:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
1050        InetAddress addr = InetAddress.getByName(addrName);
1051        assertTrue("IPv6 site-local multicast address " + addrName
1052                + " not detected.", addr.isMCSiteLocal());
1053
1054        // a sample MC organizational address
1055        addrName = "FF08:42:42:42:42:42:42:42";
1056        addr = Inet6Address.getByName(addrName);
1057        assertTrue(
1058                "IPv6 organization multicast address "
1059                        + addrName
1060                        + " incorrectly indicated as a site-local " +
1061                                "mulitcast address.",
1062                !addr.isMCSiteLocal());
1063
1064        addrName = "239.0.0.0";
1065        addr = Inet4Address.getByName(addrName);
1066        assertTrue(
1067                "IPv4 reserved multicast address "
1068                        + addrName
1069                        + " incorrectly identified as a site-local " +
1070                                "multicast address.",
1071                !addr.isMCSiteLocal());
1072
1073        addrName = "239.255.0.0";
1074        addr = Inet4Address.getByName(addrName);
1075        assertTrue("IPv4 site-local multicast address " + addrName
1076                + " not identified as a site-local multicast address.",
1077                addr.isMCSiteLocal());
1078    }
1079
1080    @TestTargetNew(
1081        level = TestLevel.COMPLETE,
1082        notes = "",
1083        method = "isSiteLocalAddress",
1084        args = {}
1085    )
1086    public void test_isSiteLocalAddress() throws Exception {
1087        String addrName = "42.42.42.42";
1088        InetAddress addr = InetAddress.getByName(addrName);
1089        assertTrue("IPv4 address " + addrName
1090                + " incorrectly reporting as a site local address.", !addr
1091                .isSiteLocalAddress());
1092
1093        addrName = "FEFF::FFFF:FFFF:FFFF:FFFF:FFFF";
1094        addr = InetAddress.getByName(addrName);
1095        assertTrue(
1096                "IPv6 site local address " + addrName + " not detected.",
1097                addr.isSiteLocalAddress());
1098
1099        addrName = "FEBF::FFFF:FFFF:FFFF:FFFF:FFFF";
1100        addr = InetAddress.getByName(addrName);
1101        assertTrue("IPv6 address " + addrName
1102                + " detected incorrectly as a site local address.", !addr
1103                .isSiteLocalAddress());
1104    }
1105
1106    class MockSecurityManager extends SecurityManager {
1107        public void checkPermission(Permission permission) {
1108            if (permission.getName().equals("setSecurityManager")){
1109                return;
1110            }
1111            if (permission.getName().equals("3d.com")){
1112                throw new SecurityException();
1113            }
1114            super.checkPermission(permission);
1115        }
1116    }
1117}
1118