码迷,mamicode.com
首页 > 编程语言 > 详细

java 获取本机ip及mac地址

时间:2014-05-01 13:59:15      阅读:438      评论:0      收藏:0      [点我收藏+]

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

java 获取本机ip及mac地址

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

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!