利用jdk1.6 获取服务器ip和mac

来源:互联网 发布:win7 网络连接 感叹号 编辑:程序博客网 时间:2024/06/07 08:12

刚开始最初的想法是调用系统命令来获取,但是这样的话需要考虑不同的操作系统的差异,不同操作系统执行的命令是不一样的。

1. 获取操作系统

System.getProperty("os.name").toLowerCase();

可能取值:win7 --> windows 7 ; windows ,其他


2. windows 获取ip 和mac 执行命令ipconfig/all

Process process = Runtime.getRuntime().exec("ipconfig /all");
 InputStreamReader ir = new InputStreamReader(process.getInputStream());
 LineNumberReader input = new LineNumberReader(ir);
 String line;
 while ((line = input.readLine()) != null) {//mac地址
if (line.indexOf("Physical Address") > 0) {
     String MACAddr = line.substring(line.indexOf("-") - 2);
   System.out.println("MAC address = [" + MACAddr + "]");
   }

if (line.indexOf(" IP Address") > 0) {//ip地址
     String MACAddr = line.substring(line.indexOf("-") - 2);
   System.out.println("MAC address = [" + MACAddr + "]");
   }

但是此种方法对于win7无法获取

对于linux  process = Runtime.getRuntime().exec("ifconfig bond0");

但是有一个问题,可能我们一台机器上不止一个网卡,有可能有虚拟的网卡,这样子的话用执行命令就不好处理

而jdk1.6其实自带了api来查询ip和mac

    public static String[] getIpAddr() {
        try {
            Enumeration allNetInterfaces = null;
            try {
                allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            } catch (SocketException e) {
                e.printStackTrace();
            }
            InetAddress ip = null;
            byte[] mac;
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                // System.out.println(netInterface.getName());
                Enumeration addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    ip = (InetAddress) addresses.nextElement();
                    if (ip != null && ip.isSiteLocalAddress() && !ip.isLoopbackAddress()
                            && ip.getHostAddress().indexOf(":") == -1)
                        if (ip != null && ip instanceof Inet4Address && ip.getHostAddress().indexOf(".") != -1) {
                            mac = netInterface.getHardwareAddress();
                            String ipStr = ip.getHostAddress();
                            String macStr = changeMac(mac);
                            // System.out.println(ipStr);
                            // System.out.println(macStr);
                            String result[] = new String[2];
                            result[0] = ipStr;
                            result[1] = macStr;
                            return result;
                        }
                }
            }
        } catch (Exception e) {
            return null;
        }
        // }
        return null;
    }