• java中获取本机IP


    1.背景

    2.代码

    package com.XXX.common.util;
    
    import cn.hutool.core.util.StrUtil;
    import lombok.extern.slf4j.Slf4j;
    
    import java.net.Inet4Address;
    import java.net.InetAddress;
    import java.net.NetworkInterface;
    import java.net.SocketException;
    import java.util.ArrayList;
    import java.util.Enumeration;
    import java.util.List;
    
    @Slf4j
    public class HostUtil {
    
        private static String ipAddress = null;
    
        public static String getLocalIp() {
            if (!StrUtil.isEmpty(ipAddress)) {
                return ipAddress;
            }
            try {
                ipAddress = getLocalIpAddress();
            } catch (Exception e) {
                log.error("获取IP异常: ", e);
            }
            return ipAddress;
        }
    
        private static String getLocalIpAddress() throws SocketException {
            List<String> list = new ArrayList<>();
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress address = addresses.nextElement();
                    if (!address.isLinkLocalAddress() && !address.isLoopbackAddress() && address instanceof Inet4Address) {
                        list.add(address.getHostAddress());
                    }
                }
            }
            return String.join(";", list);
        }
    }

    完美!

  • 相关阅读:
    CSU software 新手练习1 解题报告
    HDU 4067 Random Maze
    HDU 1853 Cyclic Tour
    Notepad++搭配MinGW编译运行C,C++程序
    ACM POJ3299-Humidex
    开始正常的做题了=。=
    写在杭电热身赛2之后
    大二了~
    Vim 学习笔记之cvim hot key
    The 10th Zhejiang Provincial Collegiate Programming Contest
  • 原文地址:https://www.cnblogs.com/newAndHui/p/14607067.html
Copyright © 2020-2023  润新知