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