broadcast and prefix length with IPv6
Mark Thornton
mthornton at optrak.co.uk
Mon Dec 14 08:27:23 PST 2009
On Vista, if you try to find the broadcast address and net prefix length
associated with an IPv4 address (InterfaceAddress.getBroadcast(),
InterfaceAddress.getNetworkPrefixLength()), you get nonsense unless IPv6
is disabled. Bug 6707289 describes the prefix length case.
Workaround: -Djava.net.preferIPv4Stack=true
Without that option, the result on my machine is
/192.168.0.7, broadcast=/255.255.255.255, prefixLength=128
With -Djava.net.preferIPv4Stack=true
/192.168.0.7, broadcast=/192.168.0.255, prefixLength=24
Regards,
Mark Thornton
public class TestNetworkInterfaces
{
/**
* Must use -Djava.net.preferIPv4Stack=true to get expected results
for broadcast address and
* prefix length
* @throws SocketException
*/
@Test public void enumerateInterfaces() throws SocketException
{
for (Enumeration<NetworkInterface> interfaces =
NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements();)
{
NetworkInterface ni = interfaces.nextElement();
if (ni.isUp() && !ni.isVirtual())
reportInterface(ni, "");
}
}
private void reportInterface(NetworkInterface ni, String indent)
throws SocketException
{
if (ni.getInterfaceAddresses().isEmpty() &&
!ni.getSubInterfaces().hasMoreElements())
return; // has no addresses or child interfaces
System.out.print(indent);
System.out.print("\"");
System.out.print(ni.getDisplayName());
System.out.print("\"");
if (ni.isLoopback())
{
System.out.print(" [loopback]");
}
if (ni.isPointToPoint())
{
System.out.print(" [ptp]");
}
byte[] mac = ni.getHardwareAddress();
if (mac != null && mac.length > 0)
{
System.out.print(", hardware=");
for (byte b: mac)
{
System.out.print(':');
System.out.print(Integer.toHexString(b&255));
}
}
System.out.println();
indent = indent+" ";
for (InterfaceAddress addr: ni.getInterfaceAddresses())
{
System.out.print(indent);
System.out.print(addr.getAddress());
if (addr.getAddress().isLoopbackAddress())
System.out.print(" [loopback]");
System.out.print(", broadcast=");
System.out.print(addr.getBroadcast());
System.out.print(", prefixLength=");
System.out.print(addr.getNetworkPrefixLength());
//System.out.print(", searchedBroadcast=");
//System.out.print(BroadcastAddress.instance().getBroadcastAddress(addr.getAddress()));
try
{
String name = addr.getAddress().getCanonicalHostName();
if (name != null)
{
System.out.print(", host=");
System.out.print(name);
}
}
catch (Exception e)
{
}
System.out.println();
}
for (Enumeration<NetworkInterface>
interfaces=ni.getSubInterfaces(); interfaces.hasMoreElements();)
{
NetworkInterface child = interfaces.nextElement();
if (child.isUp())
{
reportInterface(child, indent);
}
}
}
}
More information about the net-dev
mailing list