获取IP、mac等信息

  主要是通过NetworkInterface类实现。现在一个机器,一般会有多个IP,多个网卡

  其次,Runtime.getRuntime().exec可以用来调用系统命令。

  下面贴个代码:

package networkInterface;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * 获取ip & mac 地址
 * 
 * <br>===============</br> <br>
 * 
 * @author emmerich@126.com</br>
 * @createDate 2015年7月7日</br> 
 * <br>================</br>
 */
public class NetworkInterfaceTest {

    private static void windowsCommand() throws Exception {
        String command = "ipconfig /all";
        Process p = Runtime.getRuntime().exec(command);

        BufferedReader inn = new BufferedReader(new InputStreamReader(p.getInputStream()));
        // Pattern pattern = Pattern.compile(".*Physical Addres.*: (.*)");

        StringBuilder sb = new StringBuilder();
        while (true) {
            String line = inn.readLine();
            System.out.println(line);
            if (line == null) {
                break;
            }
            sb.append(line+"
");

            /*
             * Matcher mm = pattern.matcher(line); if (mm.matches()) { System.out.println(mm.group(1)); }
             */
        }
        System.out.println(sb.toString());
    }

    private static void ip() throws Exception {
        InetAddress ip = InetAddress.getLocalHost();
        System.out.println("Current IP address : " + ip.getHostAddress());
    }

    private static void interfaces() throws Exception {
        Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
        while (networks.hasMoreElements()) {
            NetworkInterface network = networks.nextElement();
            byte[] mac = network.getHardwareAddress();

            if (mac != null) {
                System.out.print("Current MAC address : ");

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < mac.length; i++) {
                    sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
                }
                System.out.println(sb.toString());
            }
        }
    }

    public static void main(String[] args) throws Exception {
        ip();
        interfaces();

        windowsCommand();
    }
}
原文地址:https://www.cnblogs.com/ELMND/p/4627183.html