001/**
002 * Copyright (c) 2015-2022, Michael Yang 杨福海 (fuhai999@gmail.com).
003 * <p>
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 * <p>
008 * http://www.apache.org/licenses/LICENSE-2.0
009 * <p>
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package io.jboot.utils;
017
018import java.net.InetAddress;
019import java.net.NetworkInterface;
020import java.util.Enumeration;
021
022public class NetUtil {
023
024    public static String getLocalIpAddress() {
025        String hostIpAddress = null;
026        String siteLocalIpAddress = null;// 外网IP
027        try {
028            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
029            InetAddress address = null;
030            boolean findSiteLocalIpAddress = false;// 是否找到外网IP
031            while (networkInterfaces.hasMoreElements() && !findSiteLocalIpAddress) {
032                NetworkInterface ni = networkInterfaces.nextElement();
033                Enumeration<InetAddress> addresses = ni.getInetAddresses();
034                while (addresses.hasMoreElements()) {
035                    address = addresses.nextElement();
036
037                    if (!address.isSiteLocalAddress() && !address.isLoopbackAddress()
038                            && !address.getHostAddress().contains(":")) { // 外网IP
039                        siteLocalIpAddress = address.getHostAddress();
040                        findSiteLocalIpAddress = true;
041                        break;
042                    } else if (address.isSiteLocalAddress()
043                            && !address.isLoopbackAddress()
044                            && !address.getHostAddress().contains(":")) { // 内网IP
045                        hostIpAddress = address.getHostAddress();
046                    }
047                }
048            }
049        } catch (Exception e) {
050            e.printStackTrace();
051        }
052
053        // 优先使用配置的外网IP地址
054        return StrUtil.isNotBlank(siteLocalIpAddress) ? siteLocalIpAddress : hostIpAddress;
055    }
056
057}