获取本地IP与网络Ip及Mac地址

由于项目上的原因,需要获取本地IP与网络Ip及Mac地址,弄了好半天,才明白过程,于是给大家分享一下。

不说了,直接上代码。

public class GetIpAndMacAddress {

/** 
     * 获取本机IP 
* @throws UnknownHostException 
     */ 
public static String getLocalHostIP() throws UnknownHostException {  
InetAddress addr = InetAddress.getLocalHost();
String ip=addr.getHostAddress().toString();//获得本机IP
String address=addr.getHostName().toString();//获得本机名称
        return address+":"+ip;  
    }  
    /**
     * 获取链接网络时分配的IP
     * @throws SocketException 
     */
public static String getIntentIp() throws SocketException{
    Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
    InetAddress inetAddress;
    String ip = null;
    while (networkInterfaces.hasMoreElements()) {
    Enumeration<InetAddress> inetAddresses = networkInterfaces.nextElement().getInetAddresses();
        while (inetAddresses.hasMoreElements()) {
             inetAddress = inetAddresses.nextElement();
             if (inetAddress.isSiteLocalAddress() &&inetAddress != null && inetAddress instanceof Inet4Address) { 
                 ip = inetAddress.getHostAddress();
                 break;
             }
        }
    }    
return ip;
}
/**
* 根据网络Ip地址获取Mac地址
* @param host
* @return
* @throws UnknownHostException 
* @throws SocketException 
*/
    public static String getMacAddress(String host) throws IOException {  
        String macStr = "";  
        StringBuffer sb = new StringBuffer();  
        NetworkInterface ni = NetworkInterface.getByInetAddress(InetAddress.getByName(host));  
        byte[] macs = ni.getHardwareAddress();  
        for (int i = 0; i < macs.length; i++) {  
            macStr = Integer.toHexString(macs[i] & 0xFF);  
            if (macStr.length() == 1) {  
            macStr = '0' + macStr;  
            }   
            sb.append(macStr + "-");  
        }  
        macStr = sb.toString();  
        macStr = macStr.substring(0, macStr.length() - 1);   
        return macStr;  
    }  
  
    public static void main(String[] args) throws UnknownHostException, IOException {  
    System.out.println("IP--:"+GetIpAndMacAddress.getIntentIp());
    System.out.println("Mac--:"+GetIpAndMacAddress.getMacAddress(getIntentIp()));
    }  
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值