1 /* 2 * Copyright (C) 2008 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package android.core; 18 19 import junit.framework.TestCase; 20 21 import java.net.InetAddress; 22 import java.net.UnknownHostException; 23 import java.util.Random; 24 25 import android.test.suitebuilder.annotation.Suppress; 26 27 /** 28 * Tests InetAddr class by checking methods to resolve domains to IP addresses 29 * and by checking if the class returns correct addresses for local host address 30 * and host name. 31 */ 32 @Suppress 33 public class InetAddrTest extends TestCase { 34 private static final String[] HOSTS = { 35 "localhost", "www.google.com", "www.slashdot.org", "www.wikipedia.org", 36 "www.paypal.com", "www.cnn.com", "www.yahoo.com", "www.amazon.com", 37 "www.ebay.com", "www.android.com" 38 }; 39 40 public void testInetAddr() throws Exception { 41 byte[] raw; 42 43 InetAddress ia = InetAddress.getByName("localhost"); 44 45 raw = ia.getAddress(); 46 47 assertEquals(127, raw[0]); 48 assertEquals(0, raw[1]); 49 assertEquals(0, raw[2]); 50 assertEquals(1, raw[3]); 51 52 ia = InetAddress.getByName("127.0.0.1"); 53 54 raw = ia.getAddress(); 55 56 assertEquals(127, raw[0]); 57 assertEquals(0, raw[1]); 58 assertEquals(0, raw[2]); 59 assertEquals(1, raw[3]); 60 61 ia = InetAddress.getByName(null); 62 63 try { 64 InetAddress.getByName(".0.0.1"); 65 fail("expected ex"); 66 } catch (UnknownHostException ex) { 67 // expected 68 } 69 70 try { 71 InetAddress.getByName("thereisagoodchancethisdomaindoesnotexist.weirdtld"); 72 fail("expected ex"); 73 } catch (UnknownHostException ex) { 74 // expected 75 } 76 77 try { 78 InetAddress.getByName("127.0.0."); 79 fail("expected ex"); 80 } catch (UnknownHostException ex) { 81 // expected 82 } 83 84 Random random = new Random(); 85 int count = 0; 86 for (int i = 0; i < 100; i++) { 87 int index = random.nextInt(HOSTS.length); 88 try { 89 InetAddress.getByName(HOSTS[index]); 90 count++; 91 try { 92 Thread.sleep(50); 93 } catch (InterruptedException ex) { 94 } 95 } catch (UnknownHostException ex) { 96 } 97 } 98 assertEquals("Not all host lookups succeeded", 100, count); 99 } 100 } 101