大家好我想获得eth0接口的ipv6地址,
例如我的eth0接口:
eth0 : Link encap:Ethernet HWaddr 11:11:11:11:11:11
inet addr:11.11.11.11 Bcast:11.11.11.255 Mask:255.255.255.0
inet6 addr: 1111:1111:1111:1111:1111:1111/64 Scope:Link
如何在java中获取inet6地址?
我无法正确使用InetAdress类。它总是返回一个ipv4地址。
答案 0 :(得分:1)
感谢您的建议。我通过以下代码获得了有关接口的所有信息。
此外,InetAddress类在Linux中无法正常工作。 (我尝试在linux中获取硬件地址)但是代码在Windows和Linux上运行正常。
import java.io.*;
import java.net.*;
import java.util.*;
import static java.lang.System.out;
public class GetInfo {
public static void main(String args[]) throws SocketException {
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(nets))
displayInterfaceInformation(netint);
}
static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
out.printf("Display name: %s\n", netint.getDisplayName());
out.printf("Name: %s\n", netint.getName());
Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
for (InetAddress inetAddress : Collections.list(inetAddresses)) {
out.printf("InetAddress: %s\n", inetAddress);
}
out.printf("Up? %s\n", netint.isUp());
out.printf("Loopback? %s\n", netint.isLoopback());
out.printf("PointToPoint? %s\n", netint.isPointToPoint());
out.printf("Supports multicast? %s\n", netint.supportsMulticast());
out.printf("Virtual? %s\n", netint.isVirtual());
out.printf("Hardware address: %s\n",
Arrays.toString(netint.getHardwareAddress()));
out.printf("MTU: %s\n", netint.getMTU());
out.printf("\n");
}
}
问候。
答案 1 :(得分:0)
您可以使用Inet6Address
子类,请参阅http://docs.oracle.com/javase/6/docs/api/java/net/Inet6Address.html
答案 2 :(得分:0)
private static String getIPAddress(boolean v6) throws SocketException {
Enumeration<NetworkInterface> netInts = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netInt : Collections.list(netInts)) {
if (netInt.isUp() && !netInt.isLoopback()) {
for (InetAddress inetAddress : Collections.list(netInt.getInetAddresses())) {
if (inetAddress.isLoopbackAddress()
|| inetAddress.isLinkLocalAddress()
|| inetAddress.isMulticastAddress()) {
continue;
}
if (v6 && inetAddress instanceof Inet6Address) {
return inetAddress.getHostAddress();
}
if (!v6 && inetAddress instanceof InetAddress) {
return inetAddress.getHostAddress();
}
}
}
}
return null;
}