Springcloud学习笔记45--Java中获取当前服务器的Ip地址

1.  获取本地(Windows)的Ip地址

 获取本地的Ip地址:

InetAddress.getLocalHost().getHostAddress()在windows下没问题,在linux下是根据主机名在hosts文件对应的ip来获取IP地址的

如果是默认情况下/etc/hosts文件中配置是

127.0.0.1   localhost localhost.localdomain

通过hostname指令可以获取主机名,会发现是localhost.localdomain

通过hostname -i可以看到对应的IP是127.0.0.1

    public static void main(String[] args) throws UnknownHostException {
        InetAddress address = InetAddress.getLocalHost();
        String hostAddress = address.getHostAddress();
        System.out.println(hostAddress);
    }

2.获取服务器的Ip地址

package com.ttbank.flep.util;

import java.net.*;
import java.util.Enumeration;

/**
 * @Author lucky
 * @Date 2022/4/19 17:51
 */
public class IPUtil {
    public static String getIp(){
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip;
            while(networkInterfaces.hasMoreElements()){
                Enumeration<InetAddress> inetAddresses = networkInterfaces.nextElement().getInetAddresses();
                while(inetAddresses.hasMoreElements()){
                    ip=inetAddresses.nextElement();
                    if((ip!=null&& ip instanceof Inet4Address)&& !ip.getHostAddress().equals("127.0.0.1")){
                        return ip.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static void main(String[] args) throws UnknownHostException {
        String ip = getIp();
        System.out.println(ip);
    }
}

控制台输出:

192.168.88.1

 

posted @ 2022-04-19 18:43  雨后观山色  阅读(1129)  评论(0编辑  收藏  举报