import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class IpUtils {
public static void main(String[] args) {
String localIp =
"";
try {
localIp = getFirstNonLoopbackAddress(
true,
false);
}
catch (SocketException e) {
System.out.println(
"获取的ip失败!");
e.printStackTrace();
}
System.out.println(
"获取的ip:" + localIp);
}
/**
* 取得本机一个非回环地址IPv4 IP
*
* @param isIpv4
* @param isIPv6
* @return
* @throws SocketException
*/
public static String
getFirstNonLoopbackAddress(
boolean isIpv4,
boolean isIPv6)
throws SocketException {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface nif = networkInterfaces.nextElement();
Enumeration<InetAddress> addresses = nif.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
if (!addr.isLoopbackAddress()) {
if (addr
instanceof Inet4Address) {
if (isIPv6) {
continue;
}
return addr.getHostAddress();
}
if (addr
instanceof Inet6Address) {
if (isIpv4) {
continue;
}
return addr.getHostAddress();
}
}
}
}
return null;
}
}
转载请注明原文地址: https://ju.6miu.com/read-200261.html