Java Code Examples for java.net.NetworkInterface#getByName()

The following examples show how to use java.net.NetworkInterface#getByName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NetworkUtils.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
@Description("Returns the IPv4 for the specified network interface name.<br>" +
        "<b>interfaceName</b> - the network interface name, the IP of which will be returned<br>" +
        "Example:<br/>" +
        "#{currentIpAddress(interfaceName)}")
@UtilityMethod
public String currentIpAddress(String interfaceName) {
    try {
        NetworkInterface networkInterface = NetworkInterface.getByName(interfaceName);
        if (networkInterface == null) {
            throw new EPSCommonException("Unknown interface name: " + interfaceName);
        }
        Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
        InetAddress address;
        while (addresses.hasMoreElements()) {
            address = addresses.nextElement();
            if (address instanceof Inet4Address) {
                return address.getHostAddress();
            }
        }
        throw new EPSCommonException(String.format("Network interface %s has not IPv4", interfaceName));
    } catch (Exception e) {
        throw new EPSCommonException(String.format("Can't get interface [%s]", interfaceName), e);
    }
}
 
Example 2
Source File: ProbeIB.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    Scanner s = new Scanner(new File(args[0]));
    try {
        while (s.hasNextLine()) {
            String link = s.nextLine();
            NetworkInterface ni = NetworkInterface.getByName(link);
            if (ni != null) {
                Enumeration<InetAddress> addrs = ni.getInetAddresses();
                while (addrs.hasMoreElements()) {
                    InetAddress addr = addrs.nextElement();
                    System.out.println(addr.getHostAddress());
                }
            }
        }
    } finally {
        s.close();
    }
}
 
Example 3
Source File: ProbeIB.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    Scanner s = new Scanner(new File(args[0]));
    try {
        while (s.hasNextLine()) {
            String link = s.nextLine();
            NetworkInterface ni = NetworkInterface.getByName(link);
            if (ni != null) {
                Enumeration<InetAddress> addrs = ni.getInetAddresses();
                while (addrs.hasMoreElements()) {
                    InetAddress addr = addrs.nextElement();
                    System.out.println(addr.getHostAddress());
                }
            }
        }
    } finally {
        s.close();
    }
}
 
Example 4
Source File: ProbeIB.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    Scanner s = new Scanner(new File(args[0]));
    try {
        while (s.hasNextLine()) {
            String link = s.nextLine();
            NetworkInterface ni = NetworkInterface.getByName(link);
            if (ni != null) {
                Enumeration<InetAddress> addrs = ni.getInetAddresses();
                while (addrs.hasMoreElements()) {
                    InetAddress addr = addrs.nextElement();
                    System.out.println(addr.getHostAddress());
                }
            }
        }
    } finally {
        s.close();
    }
}
 
Example 5
Source File: NetworkHelper.java    From orWall with GNU General Public License v3.0 6 votes vote down vote up
public static String getMask(String intf){
    try {
        NetworkInterface ntwrk = NetworkInterface.getByName(intf);
        Iterator<InterfaceAddress> addrList = ntwrk.getInterfaceAddresses().iterator();
        while (addrList.hasNext()) {
            InterfaceAddress addr = addrList.next();
            InetAddress ip = addr.getAddress();
            if (ip instanceof Inet4Address) {
                String mask = ip.getHostAddress() + "/" +
                        addr.getNetworkPrefixLength();
                return mask;
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 6
Source File: MiscUtils.java    From RISE-V2G with MIT License 6 votes vote down vote up
public static byte[] getMacAddress() {
	String networkInterfaceConfig = getPropertyValue("network.interface").toString();
	NetworkInterface nif = null;
	byte[] macAddress = null;
	
	try {
		if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
			nif = NetworkInterface.getByIndex(Integer.parseInt(networkInterfaceConfig));
		} else {
			nif = NetworkInterface.getByName(networkInterfaceConfig);
		}
		macAddress = nif.getHardwareAddress();
	} catch (SocketException e) {
		getLogger().error("Failed to retrieve local mac address (SocketException)", e);
	}
	
	return macAddress;
}
 
Example 7
Source File: ResourceSchedulerUtils.java    From twister2 with Apache License 2.0 6 votes vote down vote up
/**
 * get ipv4 address of first matching network interface in the given list
 * network interface can not be loop back and it has to be up
 * @param interfaceNames
 * @return
 */
public static String getLocalIPFromNetworkInterfaces(List<String> interfaceNames) {

  try {
    for (String nwInterfaceName: interfaceNames) {
      NetworkInterface networkInterface = NetworkInterface.getByName(nwInterfaceName);
      if (networkInterface != null
          && !networkInterface.isLoopback()
          && networkInterface.isUp()) {
        List<InterfaceAddress> addressList = networkInterface.getInterfaceAddresses();
        for (InterfaceAddress adress: addressList) {
          if (isValidIPv4(adress.getAddress().getHostAddress())) {
            return adress.getAddress().getHostAddress();
          }
        }
      }
    }

  } catch (SocketException e) {
    LOG.log(Level.SEVERE, "Error retrieving network interface list", e);
  }

  return null;
}
 
Example 8
Source File: ProbeIB.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    Scanner s = new Scanner(new File(args[0]));
    try {
        while (s.hasNextLine()) {
            String link = s.nextLine();
            NetworkInterface ni = NetworkInterface.getByName(link);
            if (ni != null) {
                Enumeration<InetAddress> addrs = ni.getInetAddresses();
                while (addrs.hasMoreElements()) {
                    InetAddress addr = addrs.nextElement();
                    System.out.println(addr.getHostAddress());
                }
            }
        }
    } finally {
        s.close();
    }
}
 
Example 9
Source File: ProbeIB.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    Scanner s = new Scanner(new File(args[0]));
    try {
        while (s.hasNextLine()) {
            String link = s.nextLine();
            NetworkInterface ni = NetworkInterface.getByName(link);
            if (ni != null) {
                Enumeration<InetAddress> addrs = ni.getInetAddresses();
                while (addrs.hasMoreElements()) {
                    InetAddress addr = addrs.nextElement();
                    System.out.println(addr.getHostAddress());
                }
            }
        }
    } finally {
        s.close();
    }
}
 
Example 10
Source File: StorageUtils.java    From incubator-crail with Apache License 2.0 6 votes vote down vote up
public static InetSocketAddress getDataNodeAddress(String ifname, int port) throws IOException {
	NetworkInterface netif = NetworkInterface.getByName(ifname);
	if (netif == null){
		throw new IOException("Cannot find network interface with name " + ifname);
	}
	List<InterfaceAddress> addresses = netif.getInterfaceAddresses();
	InetAddress addr = null;
	for (InterfaceAddress address: addresses){
		if (address.getBroadcast() != null){
			InetAddress _addr = address.getAddress();
			addr = _addr;
		}
	}

	if (addr == null){
		throw new IOException("Network interface with name " + ifname + " has no valid IP address");
	}
	InetSocketAddress inetAddr = new InetSocketAddress(addr, port);
	return inetAddr;
}
 
Example 11
Source File: NetUtils.java    From cosmic with Apache License 2.0 5 votes vote down vote up
public static String[] getNicParams(final String nicName) {
    try {
        final NetworkInterface nic = NetworkInterface.getByName(nicName);
        return getNetworkParams(nic);
    } catch (final SocketException e) {
        return null;
    }
}
 
Example 12
Source File: TP.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param s
 * @return List of NetworkInterface
 */
private java.util.List parseInterfaceList(String s) throws Exception {
    java.util.List interfaces=new ArrayList(10);
    if(s == null)
        return null;

    StringTokenizer tok=new StringTokenizer(s, ",");
    String interface_name;
    NetworkInterface intf;

    while(tok.hasMoreTokens()) {
        interface_name=tok.nextToken();

        // try by name first (e.g. (eth0")
        intf=NetworkInterface.getByName(interface_name);

        // next try by IP address or symbolic name
        if(intf == null)
            intf=NetworkInterface.getByInetAddress(InetAddress.getByName(interface_name));

        if(intf == null)
            throw new Exception("interface " + interface_name + " not found");
        if(interfaces.contains(intf)) {
            log.warn("did not add interface " + interface_name + " (already present in " + print(interfaces) + ")");
        }
        else {
            interfaces.add(intf);
        }
    }
    return interfaces;
}
 
Example 13
Source File: AbstractServerConfigurationBean.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Parse an adapter name string and return the matching address
 * 
 * @param adapter String
 * @return InetAddress
 * @exception InvalidConfigurationException
 */
protected final InetAddress parseAdapterName(String adapter)
  throws InvalidConfigurationException {

  NetworkInterface ni = null;
  
  try {
    ni = NetworkInterface.getByName( adapter);
  }
  catch (SocketException ex) {
    throw new InvalidConfigurationException( "Invalid adapter name, " + adapter);
  }
  
  if ( ni == null)
    throw new InvalidConfigurationException( "Invalid network adapter name, " + adapter);
  
  // Get the IP address for the adapter

  InetAddress adapAddr = null;
  Enumeration<InetAddress> addrEnum = ni.getInetAddresses();
  
  while ( addrEnum.hasMoreElements() && adapAddr == null) {
    
    // Get the current address
    
    InetAddress addr = addrEnum.nextElement();
    if ( IPAddress.isNumericAddress( addr.getHostAddress()))
      adapAddr = addr;
  }
  
  // Check if we found the IP address to bind to
  
  if ( adapAddr == null)
    throw new InvalidConfigurationException( "Adapter " + adapter + " does not have a valid IP address");

  // Return the adapter address
  
  return adapAddr;
}
 
Example 14
Source File: NetworkUtils.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/** Returns addresses for the given interface (it must be marked up) */
static InetAddress[] getAddressesForInterface(String name) throws SocketException {
    NetworkInterface intf = NetworkInterface.getByName(name);
    if (intf == null) {
        throw new IllegalArgumentException("No interface named '" + name + "' found, got " + getInterfaces());
    }
    if (!intf.isUp()) {
        throw new IllegalArgumentException("Interface '" + name + "' is not up and running");
    }
    List<InetAddress> list = Collections.list(intf.getInetAddresses());
    if (list.isEmpty()) {
        throw new IllegalArgumentException("Interface '" + name + "' has no internet addresses");
    }
    return list.toArray(new InetAddress[list.size()]);
}
 
Example 15
Source File: NacosDiscoveryProperties.java    From spring-cloud-alibaba with Apache License 2.0 4 votes vote down vote up
@PostConstruct
public void init() throws SocketException {
	namingService = null;

	metadata.put(PreservedMetadataKeys.REGISTER_SOURCE, "SPRING_CLOUD");
	if (secure) {
		metadata.put("secure", "true");
	}

	serverAddr = Objects.toString(serverAddr, "");
	if (serverAddr.endsWith("/")) {
		serverAddr = serverAddr.substring(0, serverAddr.length() - 1);
	}
	endpoint = Objects.toString(endpoint, "");
	namespace = Objects.toString(namespace, "");
	logName = Objects.toString(logName, "");

	if (StringUtils.isEmpty(ip)) {
		// traversing network interfaces if didn't specify a interface
		if (StringUtils.isEmpty(networkInterface)) {
			ip = inetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
		}
		else {
			NetworkInterface netInterface = NetworkInterface
					.getByName(networkInterface);
			if (null == netInterface) {
				throw new IllegalArgumentException(
						"no such interface " + networkInterface);
			}

			Enumeration<InetAddress> inetAddress = netInterface.getInetAddresses();
			while (inetAddress.hasMoreElements()) {
				InetAddress currentAddress = inetAddress.nextElement();
				if (currentAddress instanceof Inet4Address
						&& !currentAddress.isLoopbackAddress()) {
					ip = currentAddress.getHostAddress();
					break;
				}
			}

			if (StringUtils.isEmpty(ip)) {
				throw new RuntimeException("cannot find available ip from"
						+ " network interface " + networkInterface);
			}

		}
	}

	this.overrideFromEnv(environment);
}
 
Example 16
Source File: Inet6AddressSerializationTest.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
static void testSerializedLo0Inet6Address() throws IOException {
    System.err.println("\n testSerializedLo0Inet6Address:  enter \n");
    boolean testWithNetIf = true;
    boolean useMockInet6Address = false;

    NetworkInterface testNetIf = NetworkInterface.getByName(NETWORK_IF_LO0);
    Inet6Address expectedInet6Address = null;
    if (testNetIf != null) {
        System.err
                .println("\n testSerializedLo0Inet6Address:  using netif \n");
        try {
            expectedInet6Address = Inet6Address.getByAddress(LOCALHOSTNAME,
                    LOOPBACKIPV6ADDRESS, testNetIf);
        } catch (UnknownHostException ukhEx) {
            ukhEx.printStackTrace();
            testWithNetIf = true;
            useMockInet6Address = true;
        }
    } else {
        System.err
                .println("\n testSerializedLo0Inet6Address:  using index \n");
        try {
            expectedInet6Address = Inet6Address.getByAddress(LOCALHOSTNAME,
                    LOOPBACKIPV6ADDRESS, SCOPE_ID_ZERO);
        } catch (UnknownHostException ukhEx1) {
            ukhEx1.printStackTrace();
            useMockInet6Address = true;
        }
        testWithNetIf = false;
    }

    // displayExpectedInet6Address(expectedInet6Address);

    byte[] serializedAddress = SerialData_ifname_lo0;

    try (ByteArrayInputStream bis = new ByteArrayInputStream(
            serializedAddress);
            ObjectInputStream oin = new ObjectInputStream(bis)) {
        Inet6Address deserializedIPV6Addr = (Inet6Address) oin.readObject();
        System.err.println("Deserialized Inet6Address "
                + deserializedIPV6Addr);
        if (!useMockInet6Address) {
            assertHostNameEqual(expectedInet6Address.getHostName(),
                    deserializedIPV6Addr.getHostName());
            if (testWithNetIf) {
                assertHostAddressEqual(
                        expectedInet6Address.getHostAddress(),
                        deserializedIPV6Addr.getHostAddress());
            } else {
                assertHostAddressEqual(
                        MockLo0Inet6Address.getBareHostAddress(),
                        deserializedIPV6Addr.getHostAddress());
            }
            assertAddressEqual(expectedInet6Address.getAddress(),
                    deserializedIPV6Addr.getAddress());
            assertScopeIdEqual(expectedInet6Address.getScopeId(),
                    deserializedIPV6Addr.getScopeId());
            if (testWithNetIf) {
                assertNetworkInterfaceEqual(
                        expectedInet6Address.getScopedInterface(),
                        deserializedIPV6Addr.getScopedInterface());
            } else {
                assertNetworkInterfaceEqual(null,
                        deserializedIPV6Addr.getScopedInterface());
            }
        } else { // use MockLo0Inet6Address
            assertHostNameEqual(MockLo0Inet6Address.getHostName(),
                    deserializedIPV6Addr.getHostName());
            if (testWithNetIf) {
                assertHostAddressEqual(
                        MockLo0Inet6Address.getHostAddress(),
                        deserializedIPV6Addr.getHostAddress());
            } else {
                assertHostAddressEqual(
                        MockLo0Inet6Address.getHostAddressWithIndex(),
                        deserializedIPV6Addr.getHostAddress());
            }
            assertAddressEqual(MockLo0Inet6Address.getAddress(),
                    deserializedIPV6Addr.getAddress());
            if (testWithNetIf) {
            assertScopeIdEqual(MockLo0Inet6Address.getScopeId(),
                    deserializedIPV6Addr.getScopeId());
            } else {
                assertScopeIdEqual(MockLo0Inet6Address.getScopeZero(),
                        deserializedIPV6Addr.getScopeId());
            }
            assertNetworkInterfaceNameEqual(
                    MockLo0Inet6Address.getScopeIfName(),
                    deserializedIPV6Addr.getScopedInterface());
        }
    } catch (Exception e) {
        System.err.println("Exception caught during deserialization");
        failed = true;
        e.printStackTrace();
    }
}
 
Example 17
Source File: Inet6AddressSerializationTest.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
static void testSerializedE1000gInet6Address() throws IOException {
    System.err.println("\n testSerializedE1000gInet6Address:  enter \n");
    boolean testWithNetIf = true;
    boolean useMockInet6Address = false;

    NetworkInterface testNetIf = NetworkInterface
            .getByName(NETWORK_IF_E1000G0);
    Inet6Address expectedInet6Address = null;
    if (testNetIf != null) {
        System.err
                .println("\n testSerializedE1000gInet6Address:  using netif \n");
        try {
            expectedInet6Address = Inet6Address.getByAddress(
                    E1000G0HOSTNAME, E1000G0IPV6ADDRESS, testNetIf);
        } catch (UnknownHostException ukhEx) {
            ukhEx.printStackTrace();
            testWithNetIf = true;
            useMockInet6Address = true;
        }
    } else {
        System.err
                .println("\n testSerializedE1000gInet6Address:  using index \n");
        try {
            expectedInet6Address = Inet6Address.getByAddress(
                    E1000G0HOSTNAME, E1000G0IPV6ADDRESS, SCOPE_ID_ZERO);
        } catch (UnknownHostException ukhEx1) {
            ukhEx1.printStackTrace();
            useMockInet6Address = true;
        }
        testWithNetIf = false;
    }

    byte[] serializedAddress = SerialData_ifname_e1000g0;

    // displayExpectedInet6Address(expectedInet6Address);

    try (ByteArrayInputStream bis = new ByteArrayInputStream(
            serializedAddress);
            ObjectInputStream oin = new ObjectInputStream(bis)) {
        Inet6Address deserializedIPV6Addr = (Inet6Address) oin.readObject();
        System.err.println("Deserialized Inet6Address "
                + deserializedIPV6Addr);

        if (!useMockInet6Address) {
            assertHostNameEqual(expectedInet6Address.getHostName(),
                    deserializedIPV6Addr.getHostName());
            if (testWithNetIf) {
                assertHostAddressEqual(
                        expectedInet6Address.getHostAddress(),
                        deserializedIPV6Addr.getHostAddress());
            } else {
                assertHostAddressEqual(
                        MockE1000g0Inet6Address.getBareHostAddress(),
                        deserializedIPV6Addr.getHostAddress());
            }
            assertAddressEqual(expectedInet6Address.getAddress(),
                    deserializedIPV6Addr.getAddress());
            assertScopeIdEqual(expectedInet6Address.getScopeId(),
                    deserializedIPV6Addr.getScopeId());
            if (testWithNetIf) {
                assertNetworkInterfaceEqual(
                        expectedInet6Address.getScopedInterface(),
                        deserializedIPV6Addr.getScopedInterface());
            } else {
                assertNetworkInterfaceEqual(null,
                        deserializedIPV6Addr.getScopedInterface());
            }
        } else { // use MockLo0Inet6Address
            assertHostNameEqual(MockE1000g0Inet6Address.getHostName(),
                    deserializedIPV6Addr.getHostName());
            if (testWithNetIf) {
                assertHostAddressEqual(
                        MockE1000g0Inet6Address.getHostAddress(),
                        deserializedIPV6Addr.getHostAddress());
            } else {
                assertHostAddressEqual(
                        MockE1000g0Inet6Address.getHostAddressWithIndex(),
                        deserializedIPV6Addr.getHostAddress());
            }
            assertAddressEqual(MockE1000g0Inet6Address.getAddress(),
                    deserializedIPV6Addr.getAddress());
            if (testWithNetIf) {
            assertScopeIdEqual(MockE1000g0Inet6Address.getScopeId(),
                    deserializedIPV6Addr.getScopeId());
            } else {
                assertScopeIdEqual(MockE1000g0Inet6Address.getScopeZero(),
                        deserializedIPV6Addr.getScopeId());
            }
            assertNetworkInterfaceNameEqual(
                    MockE1000g0Inet6Address.getScopeIfName(),
                    deserializedIPV6Addr.getScopedInterface());
        }
    } catch (Exception e) {
        System.err.println("Exception caught during deserialization");
        failed = true;
        e.printStackTrace();
    }
}
 
Example 18
Source File: NicUtil.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Method that searches for and returns the network interface having
 * the specified <code>name</code>.
 *
 * @param name <code>String</code> referencing the name of the 
 *             network interface to return (for example, typical
 *             values for this parameter might be, "eth0", "eth1",
 *             "hme01", "lo", etc., depending on how the underlying
 *             platform is configured).
 *
 * @return an instance of <code>NetworkInterface</code> that represents
 *         the network interface corresponding to the given 
 *         <code>name</code>, or <code>null</code> if there is no
 *         network interface with that name value.
 *
 * @throws SocketException if there is an error in the underlying
 *         I/O subsystem and/or protocol.
 *
 * @throws NullPointerException if <code>null</code> is input for
 *         <code>name</code>.
 */
public static NetworkInterface getNetworkInterface(String name) 
                                                  throws SocketException
{
    NetworkInterface nic = NetworkInterface.getByName(name);
    if (nic == null) {
        // try by IP address
        InetAddress targetIp = null;
        try {
            targetIp = InetAddress.getByName(name);
            nic = NetworkInterface.getByInetAddress(targetIp);
        } catch (UnknownHostException uhe) {
            // ignore, return null
        }
    }
    return nic;
}
 
Example 19
Source File: Inet6AddressSerializationTest.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
static void testSerializedLo0Inet6Address() throws IOException {
    System.err.println("\n testSerializedLo0Inet6Address:  enter \n");
    boolean testWithNetIf = true;
    boolean useMockInet6Address = false;

    NetworkInterface testNetIf = NetworkInterface.getByName(NETWORK_IF_LO0);
    Inet6Address expectedInet6Address = null;
    if (testNetIf != null) {
        System.err
                .println("\n testSerializedLo0Inet6Address:  using netif \n");
        try {
            expectedInet6Address = Inet6Address.getByAddress(LOCALHOSTNAME,
                    LOOPBACKIPV6ADDRESS, testNetIf);
        } catch (UnknownHostException ukhEx) {
            ukhEx.printStackTrace();
            testWithNetIf = true;
            useMockInet6Address = true;
        }
    } else {
        System.err
                .println("\n testSerializedLo0Inet6Address:  using index \n");
        try {
            expectedInet6Address = Inet6Address.getByAddress(LOCALHOSTNAME,
                    LOOPBACKIPV6ADDRESS, SCOPE_ID_ZERO);
        } catch (UnknownHostException ukhEx1) {
            ukhEx1.printStackTrace();
            useMockInet6Address = true;
        }
        testWithNetIf = false;
    }

    // displayExpectedInet6Address(expectedInet6Address);

    byte[] serializedAddress = SerialData_ifname_lo0;

    try (ByteArrayInputStream bis = new ByteArrayInputStream(
            serializedAddress);
            ObjectInputStream oin = new ObjectInputStream(bis)) {
        Inet6Address deserializedIPV6Addr = (Inet6Address) oin.readObject();
        System.err.println("Deserialized Inet6Address "
                + deserializedIPV6Addr);
        if (!useMockInet6Address) {
            assertHostNameEqual(expectedInet6Address.getHostName(),
                    deserializedIPV6Addr.getHostName());
            if (testWithNetIf) {
                assertHostAddressEqual(
                        expectedInet6Address.getHostAddress(),
                        deserializedIPV6Addr.getHostAddress());
            } else {
                assertHostAddressEqual(
                        MockLo0Inet6Address.getBareHostAddress(),
                        deserializedIPV6Addr.getHostAddress());
            }
            assertAddressEqual(expectedInet6Address.getAddress(),
                    deserializedIPV6Addr.getAddress());
            assertScopeIdEqual(expectedInet6Address.getScopeId(),
                    deserializedIPV6Addr.getScopeId());
            if (testWithNetIf) {
                assertNetworkInterfaceEqual(
                        expectedInet6Address.getScopedInterface(),
                        deserializedIPV6Addr.getScopedInterface());
            } else {
                assertNetworkInterfaceEqual(null,
                        deserializedIPV6Addr.getScopedInterface());
            }
        } else { // use MockLo0Inet6Address
            assertHostNameEqual(MockLo0Inet6Address.getHostName(),
                    deserializedIPV6Addr.getHostName());
            if (testWithNetIf) {
                assertHostAddressEqual(
                        MockLo0Inet6Address.getHostAddress(),
                        deserializedIPV6Addr.getHostAddress());
            } else {
                assertHostAddressEqual(
                        MockLo0Inet6Address.getHostAddressWithIndex(),
                        deserializedIPV6Addr.getHostAddress());
            }
            assertAddressEqual(MockLo0Inet6Address.getAddress(),
                    deserializedIPV6Addr.getAddress());
            if (testWithNetIf) {
            assertScopeIdEqual(MockLo0Inet6Address.getScopeId(),
                    deserializedIPV6Addr.getScopeId());
            } else {
                assertScopeIdEqual(MockLo0Inet6Address.getScopeZero(),
                        deserializedIPV6Addr.getScopeId());
            }
            assertNetworkInterfaceNameEqual(
                    MockLo0Inet6Address.getScopeIfName(),
                    deserializedIPV6Addr.getScopedInterface());
        }
    } catch (Exception e) {
        System.err.println("Exception caught during deserialization");
        failed = true;
        e.printStackTrace();
    }
}
 
Example 20
Source File: Inet6AddressSerializationTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
static void testSerializedLo0Inet6Address() throws IOException {
    System.err.println("\n testSerializedLo0Inet6Address:  enter \n");
    boolean testWithNetIf = true;
    boolean useMockInet6Address = false;

    NetworkInterface testNetIf = NetworkInterface.getByName(NETWORK_IF_LO0);
    Inet6Address expectedInet6Address = null;
    if (testNetIf != null) {
        System.err
                .println("\n testSerializedLo0Inet6Address:  using netif \n");
        try {
            expectedInet6Address = Inet6Address.getByAddress(LOCALHOSTNAME,
                    LOOPBACKIPV6ADDRESS, testNetIf);
        } catch (UnknownHostException ukhEx) {
            ukhEx.printStackTrace();
            testWithNetIf = true;
            useMockInet6Address = true;
        }
    } else {
        System.err
                .println("\n testSerializedLo0Inet6Address:  using index \n");
        try {
            expectedInet6Address = Inet6Address.getByAddress(LOCALHOSTNAME,
                    LOOPBACKIPV6ADDRESS, SCOPE_ID_ZERO);
        } catch (UnknownHostException ukhEx1) {
            ukhEx1.printStackTrace();
            useMockInet6Address = true;
        }
        testWithNetIf = false;
    }

    // displayExpectedInet6Address(expectedInet6Address);

    byte[] serializedAddress = SerialData_ifname_lo0;

    try (ByteArrayInputStream bis = new ByteArrayInputStream(
            serializedAddress);
            ObjectInputStream oin = new ObjectInputStream(bis)) {
        Inet6Address deserializedIPV6Addr = (Inet6Address) oin.readObject();
        System.err.println("Deserialized Inet6Address "
                + deserializedIPV6Addr);
        if (!useMockInet6Address) {
            assertHostNameEqual(expectedInet6Address.getHostName(),
                    deserializedIPV6Addr.getHostName());
            if (testWithNetIf) {
                assertHostAddressEqual(
                        expectedInet6Address.getHostAddress(),
                        deserializedIPV6Addr.getHostAddress());
            } else {
                assertHostAddressEqual(
                        MockLo0Inet6Address.getBareHostAddress(),
                        deserializedIPV6Addr.getHostAddress());
            }
            assertAddressEqual(expectedInet6Address.getAddress(),
                    deserializedIPV6Addr.getAddress());
            assertScopeIdEqual(expectedInet6Address.getScopeId(),
                    deserializedIPV6Addr.getScopeId());
            if (testWithNetIf) {
                assertNetworkInterfaceEqual(
                        expectedInet6Address.getScopedInterface(),
                        deserializedIPV6Addr.getScopedInterface());
            } else {
                assertNetworkInterfaceEqual(null,
                        deserializedIPV6Addr.getScopedInterface());
            }
        } else { // use MockLo0Inet6Address
            assertHostNameEqual(MockLo0Inet6Address.getHostName(),
                    deserializedIPV6Addr.getHostName());
            if (testWithNetIf) {
                assertHostAddressEqual(
                        MockLo0Inet6Address.getHostAddress(),
                        deserializedIPV6Addr.getHostAddress());
            } else {
                assertHostAddressEqual(
                        MockLo0Inet6Address.getHostAddressWithIndex(),
                        deserializedIPV6Addr.getHostAddress());
            }
            assertAddressEqual(MockLo0Inet6Address.getAddress(),
                    deserializedIPV6Addr.getAddress());
            if (testWithNetIf) {
            assertScopeIdEqual(MockLo0Inet6Address.getScopeId(),
                    deserializedIPV6Addr.getScopeId());
            } else {
                assertScopeIdEqual(MockLo0Inet6Address.getScopeZero(),
                        deserializedIPV6Addr.getScopeId());
            }
            assertNetworkInterfaceNameEqual(
                    MockLo0Inet6Address.getScopeIfName(),
                    deserializedIPV6Addr.getScopedInterface());
        }
    } catch (Exception e) {
        System.err.println("Exception caught during deserialization");
        failed = true;
        e.printStackTrace();
    }
}