1/* 2 * Copyright (C) 2015 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 android.net; 18 19import android.net.NetworkUtils; 20import android.test.suitebuilder.annotation.SmallTest; 21 22import java.net.Inet4Address; 23import java.net.InetAddress; 24 25import junit.framework.TestCase; 26 27public class NetworkUtilsTest extends TestCase { 28 29 private InetAddress Address(String addr) { 30 return InetAddress.parseNumericAddress(addr); 31 } 32 33 private Inet4Address IPv4Address(String addr) { 34 return (Inet4Address) Address(addr); 35 } 36 37 @SmallTest 38 public void testGetImplicitNetmask() { 39 assertEquals(8, NetworkUtils.getImplicitNetmask(IPv4Address("4.2.2.2"))); 40 assertEquals(8, NetworkUtils.getImplicitNetmask(IPv4Address("10.5.6.7"))); 41 assertEquals(16, NetworkUtils.getImplicitNetmask(IPv4Address("173.194.72.105"))); 42 assertEquals(16, NetworkUtils.getImplicitNetmask(IPv4Address("172.23.68.145"))); 43 assertEquals(24, NetworkUtils.getImplicitNetmask(IPv4Address("192.0.2.1"))); 44 assertEquals(24, NetworkUtils.getImplicitNetmask(IPv4Address("192.168.5.1"))); 45 assertEquals(32, NetworkUtils.getImplicitNetmask(IPv4Address("224.0.0.1"))); 46 assertEquals(32, NetworkUtils.getImplicitNetmask(IPv4Address("255.6.7.8"))); 47 } 48 49 private void assertInvalidNetworkMask(Inet4Address addr) { 50 try { 51 NetworkUtils.netmaskToPrefixLength(addr); 52 fail("Invalid netmask " + addr.getHostAddress() + " did not cause exception"); 53 } catch (IllegalArgumentException expected) { 54 } 55 } 56 57 @SmallTest 58 public void testNetmaskToPrefixLength() { 59 assertEquals(0, NetworkUtils.netmaskToPrefixLength(IPv4Address("0.0.0.0"))); 60 assertEquals(9, NetworkUtils.netmaskToPrefixLength(IPv4Address("255.128.0.0"))); 61 assertEquals(17, NetworkUtils.netmaskToPrefixLength(IPv4Address("255.255.128.0"))); 62 assertEquals(23, NetworkUtils.netmaskToPrefixLength(IPv4Address("255.255.254.0"))); 63 assertEquals(31, NetworkUtils.netmaskToPrefixLength(IPv4Address("255.255.255.254"))); 64 assertEquals(32, NetworkUtils.netmaskToPrefixLength(IPv4Address("255.255.255.255"))); 65 66 assertInvalidNetworkMask(IPv4Address("0.0.0.1")); 67 assertInvalidNetworkMask(IPv4Address("255.255.255.253")); 68 assertInvalidNetworkMask(IPv4Address("255.255.0.255")); 69 } 70} 71