• Springcloud学习笔记45Java中获取当前服务器的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
  • 相关阅读:
    [UE4]虚幻引擎的C++环境安装
    [UE4]Drop,扔物品
    [UE4]Grab抓取
    [UE4]抓取准备
    [UE4]用Format Text进行调试
    [UE4]Overlap Event 碰撞事件
    [UE4]Skeletal Mesh的碰撞体
    [UE4]模拟物理
    [UE4]Static Mesh的碰撞体
    [UE4]镜像
  • 原文地址:https://www.cnblogs.com/luckyplj/p/16166805.html
Copyright © 2020-2023  润新知