Java 获取本机的IP与MAC地址实现详解
Java获取本机的IP与MAC地址
有些机器有许多虚拟的网卡,获取IP地址时会出现一些意外,所以需要一些验证:
//获取mac地址
publicstaticStringgetMacAddress(){
try{
Enumeration<NetworkInterface>allNetInterfaces=NetworkInterface.getNetworkInterfaces();
byte[]mac=null;
while(allNetInterfaces.hasMoreElements()){
NetworkInterfacenetInterface=(NetworkInterface)allNetInterfaces.nextElement();
if(netInterface.isLoopback()||netInterface.isVirtual()||!netInterface.isUp()){
continue;
}else{
mac=netInterface.getHardwareAddress();
if(mac!=null){
StringBuildersb=newStringBuilder();
for(inti=0;i<mac.length;i++){
sb.append(String.format("%02X%s",mac[i],(i<mac.length-1)?"-":""));
}
if(sb.length()>0){
returnsb.toString();
}
}
}
}
}catch(Exceptione){
_logger.error("MAC地址获取失败",e);
}
return"";
}
//获取ip地址
publicstaticStringgetIpAddress(){
try{
Enumeration<NetworkInterface>allNetInterfaces=NetworkInterface.getNetworkInterfaces();
InetAddressip=null;
while(allNetInterfaces.hasMoreElements()){
NetworkInterfacenetInterface=(NetworkInterface)allNetInterfaces.nextElement();
if(netInterface.isLoopback()||netInterface.isVirtual()||!netInterface.isUp()){
continue;
}else{
Enumeration<InetAddress>addresses=netInterface.getInetAddresses();
while(addresses.hasMoreElements()){
ip=addresses.nextElement();
if(ip!=null&&ipinstanceofInet4Address){
returnip.getHostAddress();
}
}
}
}
}catch(Exceptione){
_logger.error("IP地址获取失败",e);
}
return"";
}
以上的代码中
netInterface.isLoopback()||netInterface.isVirtual()||!netInterface.isUp()
能很好地把一些非物理网卡或无用网上过滤掉,然后再取网上的IPV4地址即可。
说到这里,还有一些常用的:
1、获取当前机器的操作系统
publicfinalstaticStringWIN_OS="WINDOWS";
publicfinalstaticStringMAC_OS="MAC";
publicfinalstaticStringLINUX_OS="LINUX";
publicfinalstaticStringOTHER_OS="OTHER";
publicstaticStringgetOS(){
if(SystemUtils.IS_OS_WINDOWS){
returnWIN_OS;
}
if(SystemUtils.IS_OS_MAC||SystemUtils.IS_OS_MAC_OSX){
returnMAC_OS;
}
if(SystemUtils.IS_OS_UNIX){
returnLINUX_OS;
}
returnOTHER_OS;
}
2、设置HTTP访问代理
/**
*设置http代理
*/
publicstaticvoidsetHttpProxy(){
Propertiesprop=System.getProperties();
//设置http访问要使用的代理服务器的地址
prop.setProperty("http.proxyHost",HTTP_PROXY_HOST);
//设置http访问要使用的代理服务器的端口
prop.setProperty("http.proxyPort",HTTP_PROXY_PORT);
//设置不需要通过代理服务器访问的主机,可以使用*通配符,多个地址用|分隔
prop.setProperty("http.nonProxyHosts",RemoteConfig.PROXT_FILTER_DOMAIN);
}
/**
*移除http代理
*/
publicstaticvoidremoveHttpProxy(){
Propertiesprop=System.getProperties();
prop.remove("http.proxyHost");
prop.remove("http.proxyPort");
prop.remove("http.nonProxyHosts");
}
在应用启动时,访问HTTP请求前,设置好就行。当然,http.nonProxyHosts可以不用设置,表示所有的HTTP请求都走代理。
至于HTTPS代理,类似可以这样设置:
System.setProperty("https.proxyHost","HTTP_PROXY_HOST");
System.setProperty("https.proxyPort","HTTP_PROXY_PORT");
以上就是Java获取本机IP和 MAC的实例,有需要的朋友可以参考下,谢谢大家对本站的支持!