package cn.ksource.core.util;
|
|
import java.net.Inet4Address;
|
import java.net.InetAddress;
|
import java.net.NetworkInterface;
|
import java.net.SocketException;
|
import java.util.ArrayList;
|
import java.util.Enumeration;
|
import java.util.HashMap;
|
import java.util.List;
|
import java.util.Map;
|
|
import java.lang.Object;
|
|
public class InetAddrUtil {
|
|
@SuppressWarnings("rawtypes")
|
public List<Map> getIpAddrList(){
|
List<Map> list = new ArrayList<Map>();
|
try {
|
Enumeration<NetworkInterface> enumNet = NetworkInterface.getNetworkInterfaces();
|
while(enumNet.hasMoreElements()){
|
NetworkInterface networkInterface = enumNet.nextElement();
|
if(networkInterface.isLoopback()||networkInterface.isVirtual()){
|
continue;
|
}else if(networkInterface.isUp()){
|
byte[] macbyte = networkInterface.getHardwareAddress();
|
if(macbyte!=null){
|
Map<String,Object> mac = new HashMap<String, Object>();
|
Enumeration<InetAddress> enumNetAddr = networkInterface.getInetAddresses();
|
StringBuffer sb = new StringBuffer();
|
for(int i=0;i<macbyte.length;i++){
|
sb.append(String.format("%02X%s", macbyte[i],(i<macbyte.length-1)?"-":""));
|
}
|
if(sb.length()>0){
|
mac.put("mac",sb.toString());
|
List<String> iplist = new ArrayList<String>();
|
while(enumNetAddr.hasMoreElements()){
|
InetAddress netaddress = enumNetAddr.nextElement();
|
iplist.add(enumNetAddr.nextElement().getHostAddress());
|
}
|
mac.put("ips",iplist);
|
}
|
list.add(mac);
|
}
|
}
|
}
|
} catch (SocketException e) {
|
e.printStackTrace();
|
}
|
return list;
|
}
|
|
public String getLocIp() throws Exception{
|
String ip = "";
|
InetAddress ia = InetAddress.getLocalHost();
|
ip = ia.getHostAddress();
|
return ip;
|
}
|
|
|
public String getLocalMacByIp(InetAddress ia) throws SocketException {
|
// TODO Auto-generated method stub
|
// 获取网卡,获取地址
|
byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
|
//System.out.println("mac数组长度:" + mac.length);
|
StringBuffer sb = new StringBuffer("");
|
for (int i = 0; i < mac.length; i++) {
|
if (i != 0) {
|
sb.append("-");
|
}
|
// 字节转换为整数
|
int temp = mac[i] & 0xff;
|
String str = Integer.toHexString(temp);
|
//System.out.println("每8位:" + str);
|
if (str.length() == 1) {
|
sb.append("0" + str);
|
} else {
|
sb.append(str);
|
}
|
}
|
return sb.toString().toUpperCase();
|
|
}
|
|
|
}
|