java 获取本机ip及mac地址

时间:2014-05-01 13:59:15   收藏:0   阅读:438

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地址,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!