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 @   雨后观山色  阅读(1131)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2019-04-19 javaweb Servlet接收Android请求,并返回json数据
2019-04-19 Hibernate 工具类
2019-04-19 JDBC 工具类
点击右上角即可分享
微信分享提示