use of java.net.NetworkInterface in project GNS by MobilityFirst.
the class NetworkUtils method getLocalHostLANAddress.
/**
* Returns an <code>InetAddress</code> object encapsulating what is most likely the machine's LAN IP address.
* Currently ignores IP6 addresses.
* <br>
* This method is intended for use as a replacement of JDK method <code>InetAddress.getLocalHost</code>, because
* that method is ambiguous on Linux systems. Linux systems enumerate the loopback network interface the same
* way as regular LAN network interfaces, but the JDK <code>InetAddress.getLocalHost</code> method does not
* specify the algorithm used to select the address returned under such circumstances, and will often return the
* loopback address, which is not valid for network communication. Details
* <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4665037">here</a>.
* <br>
* This method will scan all IP addresses on all network interfaces on the host machine to determine the IP address
* most likely to be the machine's LAN address. If the machine has multiple IP addresses, this method will prefer
* a site-local IP address (e.g. 192.168.x.x or 10.10.x.x, usually IPv4) if the machine has one (and will return the
* first site-local address if the machine has more than one), but if the machine does not hold a site-local
* address, this method will return simply the first non-loopback address found (IPv4 or IPv6).
* <br>
* If this method cannot find a non-loopback address using this selection algorithm, it will fall back to
* calling and returning the result of JDK method <code>InetAddress.getLocalHost</code>.
* <br>
*
* @return a InetAddress
* @throws UnknownHostException If the LAN address of the machine cannot be found.
*/
public static InetAddress getLocalHostLANAddress() throws UnknownHostException {
try {
InetAddress candidateAddress = null;
// Iterate all NICs (network interface cards)...
for (Enumeration<?> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements(); ) {
NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
// Iterate all IP addresses assigned to each card...
for (Enumeration<?> inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements(); ) {
InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
// filter out IP6 addresses for now
if (!inetAddr.isLoopbackAddress() && isIp4Address(inetAddr.getHostAddress())) {
if (inetAddr.isSiteLocalAddress()) {
// Found non-loopback site-local address. Return it immediately...
return inetAddr;
} else if (candidateAddress == null) {
// Found non-loopback address, but not necessarily site-local.
// Store it as a candidate to be returned if site-local address is not subsequently found...
candidateAddress = inetAddr;
// Note that we don't repeatedly assign non-loopback non-site-local addresses as candidates,
// only the first. For subsequent iterations, candidate will be non-null.
}
}
}
}
if (candidateAddress != null) {
// Return this non-loopback candidate address...
return candidateAddress;
}
// At this point, we did not find a non-loopback address.
// Fall back to returning whatever InetAddress.getLocalHost() returns...
InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
if (jdkSuppliedAddress == null) {
throw new UnknownHostException("The JDK InetAddress.getLocalHost() method unexpectedly returned null.");
}
return jdkSuppliedAddress;
} catch (SocketException | UnknownHostException e) {
UnknownHostException unknownHostException = new UnknownHostException("Failed to determine LAN address: " + e);
unknownHostException.initCause(e);
throw unknownHostException;
}
}
use of java.net.NetworkInterface in project jdk8u_jdk by JetBrains.
the class JdpClient method main.
public static void main(String[] args) {
try {
String discoveryPort = System.getProperty("com.sun.management.jdp.port");
String discoveryAddress = System.getProperty("com.sun.management.jdp.address");
if (discoveryAddress == null || discoveryPort == null) {
System.out.println("Test failed. address and port must be specified");
return;
}
int port = Integer.parseInt(discoveryPort);
InetAddress address = InetAddress.getByName(discoveryAddress);
ProtocolFamily family = (address instanceof Inet6Address) ? StandardProtocolFamily.INET6 : StandardProtocolFamily.INET;
DatagramChannel channel;
channel = DatagramChannel.open(family);
channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
channel.bind(new InetSocketAddress(port));
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface interf : Collections.list(nets)) {
if (interf.supportsMulticast()) {
try {
channel.join(address, interf);
} catch (IOException e) {
// Skip not configured interfaces
}
}
}
PacketListener listener = new PacketListener(channel);
new Thread(listener, "Jdp Client").start();
} catch (RuntimeException e) {
System.out.println("Test failed.");
} catch (Exception e) {
e.printStackTrace();
System.out.println("Test failed. unexpected error " + e);
}
}
use of java.net.NetworkInterface in project jdk8u_jdk by JetBrains.
the class ListenAddress method main.
public static void main(String[] args) throws Exception {
ListeningConnector connector = (ListeningConnector) findConnector("com.sun.jdi.SocketListen");
// check wildcard address
check(connector, (InetAddress) null);
// iterate over all IPv4 addresses and check that binding to
// that address results in the correct result from startListening(Map)
Enumeration nifs = NetworkInterface.getNetworkInterfaces();
while (nifs.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) nifs.nextElement();
Enumeration addrs = ni.getInetAddresses();
while (addrs.hasMoreElements()) {
InetAddress addr = (InetAddress) addrs.nextElement();
// JPDA implementation only currently supports IPv4
if (!(addr instanceof Inet4Address)) {
continue;
}
check(connector, addr);
}
}
if (failures > 0) {
throw new RuntimeException(failures + " test(s) failed - see output for details.");
}
}
use of java.net.NetworkInterface in project jdk8u_jdk by JetBrains.
the class LocalSocketAddress method main.
public static void main(String[] args) throws SocketException {
InetAddress IPv6LoopbackAddr = null;
DatagramSocket soc = null;
try {
List<NetworkInterface> nics = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nic : nics) {
if (!nic.isLoopback())
continue;
List<InetAddress> addrs = Collections.list(nic.getInetAddresses());
for (InetAddress addr : addrs) {
if (addr instanceof Inet6Address) {
IPv6LoopbackAddr = addr;
break;
}
}
}
if (IPv6LoopbackAddr == null) {
System.out.println("IPv6 is not available, exiting test.");
return;
}
soc = new DatagramSocket(0, IPv6LoopbackAddr);
if (!IPv6LoopbackAddr.equals(soc.getLocalAddress())) {
throw new RuntimeException("Bound address is " + soc.getLocalAddress() + ", but should be " + IPv6LoopbackAddr);
}
} finally {
if (soc != null) {
soc.close();
}
}
}
use of java.net.NetworkInterface in project jdk8u_jdk by JetBrains.
the class MockE1000g0Inet6Address method testSerializedLo0Inet6Address.
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();
}
}
Aggregations