InetAddressTest.java revision 1c039d71d3879f39e3a75b8788e656f7b4f88f08
1/* 2 * Copyright (C) 2011 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 17package libcore.java.net; 18 19import java.net.InetAddress; 20 21public class InetAddressTest extends junit.framework.TestCase { 22 public void test_parseNumericAddress() throws Exception { 23 // Regular IPv4. 24 assertEquals("/1.2.3.4", InetAddress.parseNumericAddress("1.2.3.4").toString()); 25 // Regular IPv6. 26 assertEquals("/2001:4860:800d::68", InetAddress.parseNumericAddress("2001:4860:800d::68").toString()); 27 // Weird IPv4 special cases. 28 assertEquals("/1.2.0.3", InetAddress.parseNumericAddress("1.2.3").toString()); 29 assertEquals("/1.0.0.2", InetAddress.parseNumericAddress("1.2").toString()); 30 assertEquals("/0.0.0.1", InetAddress.parseNumericAddress("1").toString()); 31 assertEquals("/0.0.4.210", InetAddress.parseNumericAddress("1234").toString()); 32 // Optional square brackets around IPv6 addresses, including mapped IPv4. 33 assertEquals("/2001:4860:800d::68", InetAddress.parseNumericAddress("[2001:4860:800d::68]").toString()); 34 assertEquals("/127.0.0.1", InetAddress.parseNumericAddress("[::ffff:127.0.0.1]").toString()); 35 try { 36 // Actual IPv4 addresses may not be surrounded by square brackets. 37 assertEquals("/127.0.0.1", InetAddress.parseNumericAddress("[127.0.0.1]").toString()); 38 fail(); 39 } catch (IllegalArgumentException expected) { 40 } 41 try { 42 // Almost numeric but invalid... 43 InetAddress.parseNumericAddress("1."); 44 fail(); 45 } catch (IllegalArgumentException expected) { 46 } 47 try { 48 // Not even close to numeric... 49 InetAddress.parseNumericAddress("www.google.com"); 50 fail(); 51 } catch (IllegalArgumentException expected) { 52 } 53 // Strange special cases, for compatibility with InetAddress.getByName. 54 assertTrue(InetAddress.parseNumericAddress(null).isLoopbackAddress()); 55 assertTrue(InetAddress.parseNumericAddress("").isLoopbackAddress()); 56 } 57 58 public void test_getLoopbackAddress() throws Exception { 59 assertTrue(InetAddress.getLoopbackAddress().isLoopbackAddress()); 60 } 61 62 public void test_0() throws Exception { 63 // The RI special-cases "0" for legacy IPv4 applications. 64 assertTrue(InetAddress.getByName("0").isAnyLocalAddress()); 65 } 66} 67