「Java 开发工具」获取本地网络基础信息工具

71 阅读4分钟

废话不多说系列,直接展示 ~

美女背景图2.png

一、完整源码

核心功能如下:

  1. 获取本机名字;
  2. 获取本机MAC地址;
  3. 获取网卡序列号;
  4. 获取网络地址集合;
  5. IP转integer;
  6. integer 转 IP;
  7. 判断URI是否可达;
  8. ping地址是否可达;
  9. 根据请求获取IP地址;
(1)完整代码工具类,如下所示:
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;

import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * 本地网络基础工具
 * <pre>
 *     1. 获取本机名字;
 *     2. 获取本机MAC地址;
 *     3. 获取网卡序列号;
 *     4. 获取网络地址集合;
 *     5. IP转integer;
 *     6. integer 转 IP;
 *     7. 判断URI是否可达;
 *     8. ping地址是否可达;
 *     9. 根据请求获取IP地址;
 *     。。。
 * </pre>
 *
 * @author drew
 */
public class NativeUtils {

    public static void main(String[] args) throws Exception {
        System.out.println("主机名:" + getLocalHostName());
        System.out.println("MAC地址:" + getMACAddress(InetAddress.getLocalHost()));
        System.out.println("网络地址:" + getNetworkAddress());
        System.out.println("网卡序列号:" + getDUID());

        System.out.println("IP地址是否可达:" + ping("192.168.174.1"));
        System.out.println("IP 转 数字:" + ipToInteger("192.168.174.1"));
        System.out.println("数字 转 IP:" + IntegerToIp(-1062687231));
        System.out.println("URI 是否可达:" + isReachable("www.baidu.com"));
        System.out.println("URI 是否可达:" + isReachable(new URL("http://www.baidu.com")));
    }

    /**
     * 获取本机名字(Windows机器名)
     *
     * @return 名称
     */
    public static String getLocalHostName() {
        String hostName;
        try {
            InetAddress addr = InetAddress.getLocalHost();
            hostName = addr.getHostName();
        } catch (Exception ex) {
            hostName = "";
        }
        return hostName;
    }

    /**
     * 获取本地网络地址
     *
     * @return 网络地址集合(可能有多个网络地址)
     */
    public static List<String> getNetworkAddress() {
        List<String> result = new ArrayList<>();
        Enumeration<NetworkInterface> netInterfaces;
        try {
            netInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip;
            while (netInterfaces.hasMoreElements()) {
                NetworkInterface ni = netInterfaces.nextElement();
                Enumeration<InetAddress> addresses = ni.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    ip = addresses.nextElement();
                    if (!ip.isLoopbackAddress() && ip.getHostAddress().indexOf(':') == -1) {
                        result.add(ip.getHostAddress());
                    }
                }
            }
            return result;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取网卡序列号(Windows 命令)
     *
     * @return 网卡序列号
     */
    public static String getDUID() {
        String address = "";
        String command = "cmd.exe /c ipconfig /all";
        try {
            Process p = Runtime.getRuntime().exec(command);
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ((line = br.readLine()) != null) {
                if (line.indexOf("DUID") > 0) {
                    int index = line.indexOf(":");
                    index += 2;
                    address = line.substring(index);
                    break;
                }
            }
            br.close();
        } catch (IOException ignored) {
        }
        return address;
    }


    /**
     * 获取MAC地址的方法
     *
     * @param ia 网络地址
     * @return MAC地址
     * @throws Exception 异常
     */
    private static String getMACAddress(InetAddress ia) throws Exception {
        // 获得网络接口对象(即网卡),并得到mac地址,mac地址存在于一个byte数组中。
        byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
        // 下面代码是把mac地址拼装成String
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < mac.length; i++) {
            if (i != 0) {
                sb.append("-");
            }
            // mac[i] & 0xFF 是为了把byte转化为正整数
            String s = Integer.toHexString(mac[i] & 0xFF);
            sb.append(s.length() == 1 ? 0 + s : s);
        }
        // 把字符串所有小写字母改为大写成为正规的mac地址并返回
        return sb.toString().toUpperCase();
    }

    /**
     * <p>
     * 获取请求中的 IP
     * </p>
     *
     * @param request 外部请求
     * @return IP地址
     */
    public static String getIpAddress(HttpServletRequest request) {
        String[] ipHeaders = {"x-forwarded-for", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR"};
        String[] localhostIp = {"127.0.0.1", "0:0:0:0:0:0:0:1"};
        String ip = request.getRemoteAddr();
        for (String header : ipHeaders) {
            if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
                break;
            }
            ip = request.getHeader(header);
        }
        for (String local : localhostIp) {
            if (ip != null && ip.equals(local)) {
                try {
                    ip = InetAddress.getLocalHost().getHostAddress();
                } catch (UnknownHostException ignored) {
                }
                break;
            }
        }
        if (ip != null && ip.length() > 15 && ip.contains(",")) {
            ip = ip.substring(0, ip.indexOf(','));
        }
        return ip;
    }

    /**
     * <p>
     * IP 转 Integer
     * </p>
     *
     * @param ip IP 地址
     * @return 数字
     */
    public static Integer ipToInteger(String ip) {
        String[] ips = ip.split("\\.");
        int ipFour = 0;
        for (String ip4 : ips) {
            Integer ip4a = Integer.parseInt(ip4);
            ipFour = (ipFour << 8) | ip4a;
        }
        return ipFour;
    }

    /**
     * <p>
     * Integer 转 IP
     * </p>
     *
     * @param ip: IP 地址
     * @return IP地址
     */
    public static String IntegerToIp(Integer ip) {
        StringBuilder sb = new StringBuilder();
        for (int i = 3; i >= 0; i--) {
            int ipa = (ip >> (8 * i)) & (0xff);
            sb.append(ipa + ".");
        }
        sb.delete(sb.length() - 1, sb.length());
        return sb.toString();
    }

    /**
     * <p>
     * IP 地址是否可达
     * </p>
     *
     * @param ip IP 地址
     * @return true 可达,false 不可达
     */
    public static boolean isReachable(String ip) {
        InetAddress address;
        try {
            address = InetAddress.getByName(ip);
            if (address.isReachable(5000)) {
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * <p>
     * 根据 url 和请求参数获取 URI
     * </p>
     *
     * @param url    请求地址
     * @param params 请求参数
     * @return URI
     */
    public static URI getURIwithParams(String url, MultiValueMap<String, String> params) {
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url).queryParams(params);
        return builder.build().encode().toUri();
    }

    /**
     * <p>
     * 判断网址是否有效
     * 对于404页面,如果被电信或者联通劫持了,也会返回200的状态,这个是不准确的
     * </p>
     *
     * @param url 请求地址
     * @return true 网址有效
     */
    public static boolean isReachable(URL url) {
        boolean reachable = false;
        HttpURLConnection httpconn = null;
        HttpsURLConnection httpsconn = null;
        int code = 0;

        try {
            if ("https".equals(url.getProtocol())) {
                httpsconn = (HttpsURLConnection) url.openConnection();
                code = httpsconn.getResponseCode();
            } else {
                httpconn = (HttpURLConnection) url.openConnection();
                code = httpconn.getResponseCode();
            }
            if (code == 200) {
                reachable = true;
            }
        } catch (Exception ignored) {
        }

        return reachable;
    }

    /**
     * <p>
     * 实现 Ping 命令
     * Ping 的字符串换行使用 java 的换行符"\n",如果 ping 不同返回 null
     * </p>
     *
     * @param ip IP 地址
     * @return java.lang.String
     */
    public static String ping(String ip) {
        StringBuilder res = new StringBuilder();
        String line;
        try {
            Process pro = Runtime.getRuntime().exec("ping " + ip);
            BufferedReader buf = new BufferedReader(new InputStreamReader(pro.getInputStream(), "GBK"));
            while ((line = buf.readLine()) != null) {
                if (!"".equals(line)) {
                    res.append(line).append("\n");
                }
            }
        } catch (Exception e) {
            return null;
        }
        return res.toString();
    }

}

(2)测试结果
主机名:LAPTOP-KM44ISMS
MAC地址:8C-8C-AA-EC-28-44
网络地址:[192.168.88.1, 172.20.124.79, 192.168.174.1]
网卡序列号:00-01-00-01-27-CE-C0-21-8C-8C-AA-EC-28-44
IP地址是否可达:正在 Ping 192.168.174.1 具有 32 字节的数据:
来自 192.168.174.1 的回复: 字节=32 时间<1ms TTL=128
来自 192.168.174.1 的回复: 字节=32 时间<1ms TTL=128
来自 192.168.174.1 的回复: 字节=32 时间<1ms TTL=128
来自 192.168.174.1 的回复: 字节=32 时间<1ms TTL=128
192.168.174.1 的 Ping 统计信息:
    数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),
往返行程的估计时间(以毫秒为单位):
    最短 = 0ms,最长 = 0ms,平均 = 0ms

IP 转 数字:-1062687231
数字 转 IP:192.168.174.1
URI 是否可达:true
URI 是否可达:true

Process finished with exit code 0

至此,感谢阅读🙏

美女背景图2.png