zoukankan      html  css  js  c++  java
  • 获取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();
        }
    }
  • 相关阅读:
    elasticsearch 基础
    docker 安装ElasticSearch的中文分词器IK
    Netty的编解码,粘包拆包,心跳检测机制
    Spring IOC 常用的注解
    @JsonView的使用
    lombok的使用以及其中的坑
    Zuul的高级使用
    SpringBoot 整合 ActiveMq
    转:Maven <resource>标签
    码农经常读错的单词
  • 原文地址:https://www.cnblogs.com/ELMND/p/4627183.html
Copyright © 2011-2022 走看看