java 获取本机ip及mac地址

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;
}

}

posted on 2014-04-30 11:07  a_badegg  阅读(292)  评论(0编辑  收藏  举报

导航