NetworkInterfaceTest.java revision cc05ad238516f1303687aba4a978e24e57c0c07a
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 tests.api.java.net;
19
20import dalvik.annotation.TestTargetClass;
21import dalvik.annotation.TestTargets;
22import dalvik.annotation.TestLevel;
23import dalvik.annotation.TestTargetNew;
24
25import java.net.InetAddress;
26import java.net.NetworkInterface;
27import java.net.SocketException;
28import java.util.ArrayList;
29import java.util.Enumeration;
30
31@TestTargetClass(NetworkInterface.class)
32public class NetworkInterfaceTest extends junit.framework.TestCase {
33
34    // private member variables used for tests
35    boolean atLeastOneInterface = false;
36
37    boolean atLeastTwoInterfaces = false;
38
39    private NetworkInterface networkInterface1 = null;
40
41    private NetworkInterface sameAsNetworkInterface1 = null;
42
43    private NetworkInterface networkInterface2 = null;
44
45    /**
46     * @tests java.net.NetworkInterface#getName()
47     */
48    @TestTargetNew(
49        level = TestLevel.COMPLETE,
50        notes = "",
51        method = "getName",
52        args = {}
53    )
54    public void test_getName() {
55        if (atLeastOneInterface) {
56            assertNotNull("validate that non null name is returned",
57                    networkInterface1.getName());
58            assertFalse("validate that non-zero length name is generated",
59                    networkInterface1.getName().equals(""));
60        }
61        if (atLeastTwoInterfaces) {
62            assertFalse(
63                    "Validate strings are different for different interfaces",
64                    networkInterface1.getName().equals(
65                            networkInterface2.getName()));
66        }
67    }
68
69    /**
70     * @tests java.net.NetworkInterface#getInetAddresses()
71     */
72    @TestTargetNew(
73        level = TestLevel.COMPLETE,
74        notes = "",
75        method = "getInetAddresses",
76        args = {}
77    )
78    public void test_getInetAddresses() {
79
80        // security manager that allows us to check that we only return the
81        // addresses that we should
82        class mySecurityManager extends SecurityManager {
83
84            ArrayList disallowedNames = null;
85
86            public mySecurityManager(ArrayList addresses) {
87                disallowedNames = new ArrayList();
88                for (int i = 0; i < addresses.size(); i++) {
89                    disallowedNames.add(((InetAddress) addresses.get(i))
90                            .getHostName());
91                    disallowedNames.add(((InetAddress) addresses.get(i))
92                            .getHostAddress());
93                }
94            }
95
96            public void checkConnect(String host, int port) {
97
98                if (host == null) {
99                    throw new NullPointerException("host was null)");
100                }
101
102                for (int i = 0; i < disallowedNames.size(); i++) {
103                    if (((String) disallowedNames.get(i)).equals(host)) {
104                        throw new SecurityException("not allowed");
105                    }
106                }
107            }
108
109        }
110
111        if (atLeastOneInterface) {
112            Enumeration theAddresses = networkInterface1.getInetAddresses();
113            if (theAddresses != null) {
114                while (theAddresses.hasMoreElements()) {
115                    InetAddress theAddress = (InetAddress) theAddresses
116                            .nextElement();
117                    assertTrue("validate that address is not null",
118                            null != theAddress);
119                }
120            }
121        }
122
123        if (atLeastTwoInterfaces) {
124            Enumeration theAddresses = networkInterface2.getInetAddresses();
125            if (theAddresses != null) {
126                while (theAddresses.hasMoreElements()) {
127                    InetAddress theAddress = (InetAddress) theAddresses
128                            .nextElement();
129                    assertTrue("validate that address is not null",
130                            null != theAddress);
131                }
132            }
133        }
134
135        // create the list of ok and not ok addresses to return
136        if (atLeastOneInterface) {
137            ArrayList okAddresses = new ArrayList();
138            Enumeration addresses = networkInterface1.getInetAddresses();
139            int index = 0;
140            ArrayList notOkAddresses = new ArrayList();
141            if (addresses != null) {
142                while (addresses.hasMoreElements()) {
143                    InetAddress theAddress = (InetAddress) addresses
144                            .nextElement();
145                    if (index != 0) {
146                        okAddresses.add(theAddress);
147                    } else {
148                        notOkAddresses.add(theAddress);
149                    }
150                    index++;
151                }
152            }
153
154            // do the same for network interface 2 it it exists
155            if (atLeastTwoInterfaces) {
156                addresses = networkInterface2.getInetAddresses();
157                index = 0;
158                if (addresses != null) {
159                    while (addresses.hasMoreElements()) {
160                        InetAddress theAddress = (InetAddress) addresses
161                                .nextElement();
162                        if (index != 0) {
163                            okAddresses.add(theAddress);
164                        } else {
165                            notOkAddresses.add(theAddress);
166                        }
167                        index++;
168                    }
169                }
170            }
171
172            // set the security manager that will make the first address not
173            // visible
174            System.setSecurityManager(new mySecurityManager(notOkAddresses));
175
176            // validate not ok addresses are not returned
177            for (int i = 0; i < notOkAddresses.size(); i++) {
178                Enumeration reducedAddresses = networkInterface1
179                        .getInetAddresses();
180                if (reducedAddresses != null) {
181                    while (reducedAddresses.hasMoreElements()) {
182                        InetAddress nextAddress = (InetAddress) reducedAddresses
183                                .nextElement();
184                        assertTrue(
185                                "validate that address without permission is not returned",
186                                !nextAddress.equals(notOkAddresses.get(i)));
187                    }
188                }
189                if (atLeastTwoInterfaces) {
190                    reducedAddresses = networkInterface2.getInetAddresses();
191                    if (reducedAddresses != null) {
192                        while (reducedAddresses.hasMoreElements()) {
193                            InetAddress nextAddress = (InetAddress) reducedAddresses
194                                    .nextElement();
195                            assertTrue(
196                                    "validate that address without permission is not returned",
197                                    !nextAddress.equals(notOkAddresses.get(i)));
198                        }
199                    }
200                }
201            }
202
203            // validate that ok addresses are returned
204            for (int i = 0; i < okAddresses.size(); i++) {
205                boolean addressReturned = false;
206                Enumeration reducedAddresses = networkInterface1
207                        .getInetAddresses();
208                if (reducedAddresses != null) {
209                    while (reducedAddresses.hasMoreElements()) {
210                        InetAddress nextAddress = (InetAddress) reducedAddresses
211                                .nextElement();
212                        if (nextAddress.equals(okAddresses.get(i))) {
213                            addressReturned = true;
214                        }
215                    }
216                }
217                if (atLeastTwoInterfaces) {
218                    reducedAddresses = networkInterface2.getInetAddresses();
219                    if (reducedAddresses != null) {
220                        while (reducedAddresses.hasMoreElements()) {
221                            InetAddress nextAddress = (InetAddress) reducedAddresses
222                                    .nextElement();
223                            if (nextAddress.equals(okAddresses.get(i))) {
224                                addressReturned = true;
225                            }
226                        }
227                    }
228                }
229                assertTrue("validate that address with permission is returned",
230                        addressReturned);
231            }
232
233            // validate that we can get the interface by specifying the address.
234            // This is to be compatible
235            for (int i = 0; i < notOkAddresses.size(); i++) {
236                try {
237                    assertNotNull(
238                            "validate we cannot get the NetworkInterface with an address for which we have no privs",
239                            NetworkInterface
240                                    .getByInetAddress((InetAddress) notOkAddresses
241                                            .get(i)));
242                } catch (Exception e) {
243                    fail("get NetworkInterface for address with no perm - exception");
244                }
245            }
246
247            // validate that we can get the network interface for the good
248            // addresses
249            try {
250                for (int i = 0; i < okAddresses.size(); i++) {
251                    assertNotNull(
252                            "validate we cannot get the NetworkInterface with an address fro which we have no privs",
253                            NetworkInterface
254                                    .getByInetAddress((InetAddress) okAddresses
255                                            .get(i)));
256                }
257            } catch (Exception e) {
258                fail("get NetworkInterface for address with perm - exception");
259            }
260
261            System.setSecurityManager(null);
262        }
263    }
264
265    /**
266     * @tests java.net.NetworkInterface#getDisplayName()
267     */
268    @TestTargetNew(
269        level = TestLevel.COMPLETE,
270        notes = "",
271        method = "getDisplayName",
272        args = {}
273    )
274    public void test_getDisplayName() {
275        if (atLeastOneInterface) {
276            assertNotNull("validate that non null display name is returned",
277                    networkInterface1.getDisplayName());
278            assertFalse(
279                    "validate that non-zero lengtj display name is generated",
280                    networkInterface1.getDisplayName().equals(""));
281        }
282        if (atLeastTwoInterfaces) {
283            assertFalse(
284                    "Validate strings are different for different interfaces",
285                    networkInterface1.getDisplayName().equals(
286                            networkInterface2.getDisplayName()));
287        }
288    }
289
290    /**
291     * @tests java.net.NetworkInterface#getByName(java.lang.String)
292     */
293    @TestTargetNew(
294        level = TestLevel.SUFFICIENT,
295        notes = "SocketException checking missed.",
296        method = "getByName",
297        args = {java.lang.String.class}
298    )
299    public void test_getByNameLjava_lang_String() {
300        try {
301            assertNull("validate null handled ok",
302                                   NetworkInterface.getByName(null));
303            fail("getByName did not throw NullPointerException for null argument");
304        } catch (NullPointerException e) {
305        } catch (Exception e) {
306            fail("getByName, null inetAddress - raised exception : "
307                    + e.getMessage());
308        }
309
310        try {
311            assertNull("validate handled ok if we ask for name not associated with any interface",
312                                   NetworkInterface.getByName("8not a name4"));
313        } catch (Exception e) {
314            fail("getByName, unknown inetAddress - raised exception : "
315                    + e.getMessage());
316        }
317
318        // for each address in an interface validate that we get the right
319        // interface for that name
320        if (atLeastOneInterface) {
321            String theName = networkInterface1.getName();
322            if (theName != null) {
323                try {
324                    assertTrue(
325                            "validate that Interface can be obtained with its name",
326                            NetworkInterface.getByName(theName).equals(
327                                    networkInterface1));
328                } catch (Exception e) {
329                    fail("validate to get network interface using name - socket exception");
330                }
331            }
332            try {
333                NetworkInterface.getByName(null);
334                fail("NullPointerException was not thrown.");
335            } catch(NullPointerException npe) {
336                //expected
337            } catch (SocketException e) {
338                fail("SocketException was thrown.");
339            }
340        }
341
342        // validate that we get the right interface with the second interface as
343        // well (ie we just don't always get the first interface
344        if (atLeastTwoInterfaces) {
345            String theName = networkInterface2.getName();
346            if (theName != null) {
347                try {
348                    assertTrue(
349                            "validate that Interface can be obtained with its name",
350                            NetworkInterface.getByName(theName).equals(
351                                    networkInterface2));
352                } catch (Exception e) {
353                    fail("validate to get network interface using name - socket exception");
354                }
355            }
356        }
357    }
358
359    /**
360     * @tests java.net.NetworkInterface#getByInetAddress(java.net.InetAddress)
361     */
362    @TestTargetNew(
363        level = TestLevel.SUFFICIENT,
364        notes = "SocketException checking missed.",
365        method = "getByInetAddress",
366        args = {java.net.InetAddress.class}
367    )
368    public void test_getByInetAddressLjava_net_InetAddress() {
369
370        byte addressBytes[] = new byte[4];
371        addressBytes[0] = 0;
372        addressBytes[1] = 0;
373        addressBytes[2] = 0;
374        addressBytes[3] = 0;
375
376        try {
377            assertNull("validate null handled ok",
378                                   NetworkInterface.getByInetAddress(null));
379            fail("should not get here if getByInetAddress throws "
380                    + "NullPointerException if null passed in");
381        } catch (NullPointerException e) {
382        } catch (Exception e) {
383            fail("getByInetAddress, null inetAddress should have raised NPE"
384                    + " but instead threw a : " + e.getMessage());
385        }
386
387        try {
388            assertNull("validate handled ok if we ask for address not associated with any interface",
389                                   NetworkInterface.getByInetAddress(InetAddress
390                            .getByAddress(addressBytes)));
391        } catch (Exception e) {
392            fail("getByInetAddress, unknown inetAddress threw exception : " + e);
393        }
394
395        // for each address in an interface validate that we get the right
396        // interface for that address
397        if (atLeastOneInterface) {
398            Enumeration addresses = networkInterface1.getInetAddresses();
399            if (addresses != null) {
400                while (addresses.hasMoreElements()) {
401                    InetAddress theAddress = (InetAddress) addresses
402                            .nextElement();
403                    try {
404                        assertTrue(
405                                "validate that Interface can be obtained with any one of its addresses",
406                                NetworkInterface.getByInetAddress(theAddress)
407                                        .equals(networkInterface1));
408                    } catch (Exception e) {
409                        fail("validate to get address using inetAddress " +
410                                "threw exception : " + e);
411                    }
412                }
413            }
414
415            try {
416                NetworkInterface.getByInetAddress(null);
417                fail("NullPointerException should be thrown.");
418            } catch(NullPointerException npe) {
419                //expected
420            } catch (SocketException e) {
421                fail("SocketException was thrown.");
422            }
423        }
424
425        // validate that we get the right interface with the second interface as
426        // well (ie we just don't always get the first interface
427        if (atLeastTwoInterfaces) {
428            Enumeration addresses = networkInterface2.getInetAddresses();
429            if (addresses != null) {
430                while (addresses.hasMoreElements()) {
431                    InetAddress theAddress = (InetAddress) addresses
432                            .nextElement();
433                    try {
434                        assertTrue(
435                                "validate that Interface can be obtained with any one of its addresses",
436                                NetworkInterface.getByInetAddress(theAddress)
437                                        .equals(networkInterface2));
438                    } catch (Exception e) {
439                        fail("validate to get address using inetAddress "
440                                + "threw exception : " + e);
441                    }
442                }
443            }
444        }
445    }
446
447    /**
448     * @tests java.net.NetworkInterface#getNetworkInterfaces()
449     */
450    @TestTargetNew(
451        level = TestLevel.SUFFICIENT,
452        notes = "SocketException checking missed.",
453        method = "getNetworkInterfaces",
454        args = {}
455    )
456    public void test_getNetworkInterfaces() {
457
458        // really this is tested by all of the other calls but just make sure we
459        // can call it and get a list of interfaces if they exist
460        try {
461            Enumeration theInterfaces = NetworkInterface.getNetworkInterfaces();
462        } catch (Exception e) {
463            fail("get Network Interfaces - raised exception : "
464                    + e.getMessage());
465        }
466    }
467
468    /**
469     * @tests java.net.NetworkInterface#equals(java.lang.Object)
470     */
471    @TestTargetNew(
472        level = TestLevel.COMPLETE,
473        notes = "",
474        method = "equals",
475        args = {java.lang.Object.class}
476    )
477    public void test_equalsLjava_lang_Object() {
478        // Test for method boolean
479        // java.net.SocketPermission.equals(java.lang.Object)
480        if (atLeastOneInterface) {
481            assertTrue("If objects are the same true is returned",
482                    networkInterface1.equals(sameAsNetworkInterface1));
483            assertFalse("Validate Null handled ok", networkInterface1
484                    .equals(null));
485        }
486        if (atLeastTwoInterfaces) {
487            assertFalse("If objects are different false is returned",
488                    networkInterface1.equals(networkInterface2));
489        }
490    }
491
492    /**
493     * @tests java.net.NetworkInterface#hashCode()
494     */
495    @TestTargetNew(
496        level = TestLevel.COMPLETE,
497        notes = "",
498        method = "hashCode",
499        args = {}
500    )
501    public void test_hashCode() {
502
503        if (atLeastOneInterface) {
504            assertTrue(
505                    "validate that hash codes are the same for two calls on the same object",
506                    networkInterface1.hashCode() == networkInterface1
507                            .hashCode());
508            assertTrue(
509                    "validate that hash codes are the same for two objects for which equals is true",
510                    networkInterface1.hashCode() == sameAsNetworkInterface1
511                            .hashCode());
512        }
513    }
514
515    /**
516     * @tests java.net.NetworkInterface#toString()
517     */
518    @TestTargetNew(
519        level = TestLevel.COMPLETE,
520        notes = "",
521        method = "toString",
522        args = {}
523    )
524    public void test_toString() {
525        if (atLeastOneInterface) {
526            assertNotNull("validate that non null string is generated",
527                    networkInterface1.toString());
528            assertFalse("validate that non-zero length string is generated",
529                    networkInterface1.toString().equals(""));
530        }
531        if (atLeastTwoInterfaces) {
532            assertFalse(
533                    "Validate strings are different for different interfaces",
534                    networkInterface1.toString().equals(
535                            networkInterface2.toString()));
536        }
537    }
538
539    protected void setUp() {
540
541        Enumeration theInterfaces = null;
542        try {
543            theInterfaces = NetworkInterface.getNetworkInterfaces();
544        } catch (Exception e) {
545            fail("Exception occurred getting network interfaces : " + e);
546        }
547
548        // Set up NetworkInterface instance members. Note that because the call
549        // to NetworkInterface.getNetworkInterfaces() returns *all* of the
550        // interfaces on the test machine it is possible that one or more of
551        // them will not currently be bound to an InetAddress. e.g. a laptop
552        // running connected by a wire to the local network may also have a
553        // wireless interface that is not active and so has no InetAddress
554        // bound to it. For these tests only work with NetworkInterface objects
555        // that are bound to an InetAddress.
556        if ((theInterfaces != null) && (theInterfaces.hasMoreElements())) {
557            while ((theInterfaces.hasMoreElements())
558                    && (atLeastOneInterface == false)) {
559                NetworkInterface theInterface = (NetworkInterface) theInterfaces
560                        .nextElement();
561                if (theInterface.getInetAddresses() != null) {
562                    // Ensure that the current NetworkInterface has at least
563                    // one InetAddress bound to it.
564                    Enumeration addrs = theInterface.getInetAddresses();
565                    if ((addrs != null) && (addrs.hasMoreElements())) {
566                        atLeastOneInterface = true;
567                        networkInterface1 = theInterface;
568                    }// end if
569                }
570            }
571
572            while ((theInterfaces.hasMoreElements())
573                    && (atLeastTwoInterfaces == false)) {
574                NetworkInterface theInterface = (NetworkInterface) theInterfaces
575                        .nextElement();
576                if (theInterface.getInetAddresses() != null) {
577                    // Ensure that the current NetworkInterface has at least
578                    // one InetAddress bound to it.
579                    Enumeration addrs = theInterface.getInetAddresses();
580                    if ((addrs != null) && (addrs.hasMoreElements())) {
581                        atLeastTwoInterfaces = true;
582                        networkInterface2 = theInterface;
583                    }// end if
584                }
585            }
586
587            // Only set sameAsNetworkInterface1 if we succeeded in finding
588            // at least one good NetworkInterface
589            if (atLeastOneInterface) {
590                Enumeration addresses = networkInterface1.getInetAddresses();
591                if (addresses != null) {
592                    try {
593                        if (addresses.hasMoreElements()) {
594                            sameAsNetworkInterface1 = NetworkInterface
595                            .getByInetAddress((InetAddress) addresses
596                                    .nextElement());
597                        }
598                    } catch (SocketException e) {
599                        fail("SocketException occurred : " + e);
600                    }
601                }
602            }// end if atLeastOneInterface
603        }
604    }
605
606    protected void tearDown() {
607        System.setSecurityManager(null);
608    }
609}
610