Java获取本机名称、本机MAC地址、IP地址

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Knight_Key/article/details/82706525

Java获取本机名称、本机MAC地址、IP地址

public class Test {
        public static void main(String[] args) throws Exception {
            InetAddress ia=null;
            try {
                ia=ia.getLocalHost();
                String localname=ia.getHostName();
                String localip=ia.getHostAddress();
                System.out.println("本机名:"+ localname);
                System.out.println("本机ip:"+localip);
            } catch (Exception e) {
                e.printStackTrace();
            }
            InetAddress ia1 = InetAddress.getLocalHost();//获取本地IP对象
            System.out.println("MAC ."+getMACAddress(ia1));
        }
        //获取MAC地址的方法
        private static String getMACAddress(InetAddress ia)throws Exception{
            byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();//获得网络接口对象(即网卡),并得到mac地址,mac地址存在于一个byte数组中。
            StringBuffer sb = new StringBuffer();    //下面代码是把mac地址拼装成String
            for(int i=0;i<mac.length;i++){
                if(i!=0){
                    sb.append("-");
                }
                String s = Integer.toHexString(mac[i] & 0xFF);   //mac[i] & 0xFF 是为了把byte转化为正整数
                System.err.println(s);
                sb.append(s.length()==1?0+s:s);
            }
            return sb.toString().toUpperCase(); //把字符串所有小写字母改为大写成为正规的mac地址并返回
        }
}

猜你喜欢

转载自blog.csdn.net/Knight_Key/article/details/82706525