java 获取计算机名称, ip, mac地址

写在前面

通常所说查询本机mac地址是以以太网为准的, 也就是网线那个口..这种描述略捞.

但是通过java的getHostAddress获取ip以及getHardwareAddress()方法获取mac时, 需要将网络适配器中多余的连接禁用.

像我笔记本上这种, 打开网络连接发现有好多连接(安装了虚拟机的原因), 此时若不禁用虚拟机的连接即使插上了网线, 执行程序查询出来的还是虚拟机的ip和mac地址.

通过测试有以下结果:

1.连接无线网, 插上网线, 同时启用虚拟机网络连接时, 查询出来的是无线网的ip和mac

2.断开无线网, 启用虚拟机网络连接, 插上网线, 查询出来的是虚拟机的ip和mac

3.断开无线网, 禁用虚拟机网络连接, 插上网线,, 查询出来的才是以太网 本地连接3的ip和mac

下图是本机的网络连接和通过ipconfig/all命令查询出来的结果(虚拟机连接尚未禁用时的截图)

 测试代码:

package com.ppms.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;

/**
 * Created by liangyadong on 2018/7/26 0026.
 */
public class SystemInfo {
    public static void main(String[] args) {
        System.out.println("Host Name : "+getSystemName());
        System.out.println("Host IP   : "+getIPAddress());
        System.out.println("Host Address : "+getMAC());
    }

    /**
     * Method for get System Name
     * @return  Host name
     */
    private static String getSystemName(){
        try{
            InetAddress inetaddress=InetAddress.getLocalHost(); //Get LocalHost refrence
            String name = inetaddress.getHostName();   //Get Host Name
            return name;   //return Host Name
        }
        catch(Exception E){
            E.printStackTrace();  //print Exception StackTrace
            return null;
        }
    }

    /**
     * method to get Host IP
     * @return Host IP Address
     */
    private static String getIPAddress(){
        try{
            InetAddress inetaddress=InetAddress.getLocalHost();  //Get LocalHost refrence
            String ip = inetaddress.getHostAddress();  // Get Host IP Address
            return ip;   // return IP Address
        }
        catch(Exception E){
            E.printStackTrace();  //print Exception StackTrace
            return null;
        }

    }

    /**
     * method to get Host Mac Address
     * @return  Mac Address
     */
    private static String getMAC(){
        try{
            InetAddress inetaddress=InetAddress.getLocalHost(); //Get LocalHost refrence

            //get Network interface Refrence by InetAddress Refrence
            NetworkInterface network = NetworkInterface.getByInetAddress(inetaddress);
            byte[] macArray = network.getHardwareAddress();  //get Harware address Array
            StringBuilder str = new StringBuilder();

            // Convert Array to String
            for (int i = 0; i < macArray.length; i++) {
                str.append(String.format("%02X%s", macArray[i], (i < macArray.length - 1) ? "-" : ""));
            }
            String macAddress=str.toString();

            return macAddress; //return MAc Address
        }
        catch(Exception E){
            E.printStackTrace();  //print Exception StackTrace
            return null;
        }
    }
}

执行结果:

Host Name : personal
Host IP   : 192.168.1.115
Host Address : F0-1E-34-11-DD-66

 

可以测试一下~

 

posted @ 2018-07-26 16:50  习惯沉淀  阅读(899)  评论(0编辑  收藏  举报