java 获取本机ip及mac地址

2020-11-22 18:31

阅读:543

标签:class   java   ext   get   string   int   com   .net   name   res   amp   

package com.achun.test;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class HelloWorld {

public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("HelloWorld");
String ip = getHostAddress(false,true);
System.out.println(ip);

}

private static String getHostAddress(boolean ipv6, boolean connectTest)
{
Enumeration netInterfaces = null;
InetAddress address = null;
try {
netInterfaces = NetworkInterface.getNetworkInterfaces();
while (netInterfaces.hasMoreElements())
{
NetworkInterface ni = (NetworkInterface)netInterfaces.nextElement();

if ((ni.isUp()) && (!ni.isLoopback()) && (!ni.isVirtual())) {
address = getInetAddress(ni, ipv6);
if (address != null)
if (connectTest) {
if (address.isReachable(3000))
return address.getHostAddress();
}
else return address.getHostAddress();
}
}
}
catch (Exception e) {
}
return "";
}

private static InetAddress getInetAddress(NetworkInterface ni, boolean ipv6)
{
Enumeration enumeration = ni.getInetAddresses();
InetAddress address = null;
while (enumeration.hasMoreElements()) {
address = (InetAddress)enumeration.nextElement();
if ((!ipv6) && ((address instanceof Inet4Address)))
return address;
if ((ipv6) && ((address instanceof Inet6Address)))
return address;
}
return null;
}

public static boolean isReachable(String ip)
{
try
{
return InetAddress.getByName(ip).isReachable(3000); } catch (Exception e) {
}
return false;
}

}

java 获取本机ip及mac地址,搜素材,soscw.com

java 获取本机ip及mac地址

标签:class   java   ext   get   string   int   com   .net   name   res   amp   

原文地址:http://www.cnblogs.com/charlie-badegg/p/3700881.html


评论


亲,登录后才可以留言!