/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package libcore.java.net;
import junit.framework.TestCase;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class NetworkInterfaceTest extends TestCase {
public void testIPv6() throws Exception {
NetworkInterface lo = NetworkInterface.getByName("lo0");
Set<InetAddress> actual = new HashSet<InetAddress>(Collections.list(lo.getInetAddresses()));
assertFalse(actual.isEmpty());
}
public void testLoopback() throws Exception {
// We know lo shouldn't have a hardware address.
NetworkInterface lo = NetworkInterface.getByName("lo0");
assertNull(lo.getHardwareAddress());
// But eth0, if it exists, should...
NetworkInterface eth0 = NetworkInterface.getByName("eth0");
if (eth0 != null) {
assertEquals(6, eth0.getHardwareAddress().length);
for (InterfaceAddress ia : eth0.getInterfaceAddresses()) {
if (ia.getAddress() instanceof Inet4Address) {
assertNotNull(ia.getBroadcast());
}
}
}
}
public void testDumpAll() throws Exception {
Set<String> allNames = new HashSet<String>();
Set<Integer> allIndexes = new HashSet<Integer>();
// Log output isn't checked here, as just calling toString() on these
// objects ensures their internal state has been initialized.
PrintWriter out = new PrintWriter(new StringWriter());
for (NetworkInterface nif : Collections.list(NetworkInterface.getNetworkInterfaces())) {
out.println(nif);
out.println(nif.getInterfaceAddresses());
String flags = nif.isUp() ? "UP" : "DOWN";
if (nif.isLoopback()) {
flags += " LOOPBACK";
}
if (nif.isPointToPoint()) {
flags += " PTP";
}
if (nif.isVirtual()) {
flags += " VIRTUAL";
}
if (nif.supportsMulticast()) {
flags += " MULTICAST";
}
flags += " MTU=" + nif.getMTU();
byte[] mac = nif.getHardwareAddress();
if (mac != null) {
flags += " HWADDR=";
for (int i = 0; i < mac.length; ++i) {
if (i > 0) {
flags += ":";
}
flags += String.format("%02x", mac[i]);
}
}
out.println(flags);
out.println("-");
assertFalse(allNames.contains(nif.getName()));
allNames.add(nif.getName());
assertFalse(allIndexes.contains(nif.getIndex()));
allIndexes.add(nif.getIndex());
}
}
}