Java里面獲取當前服務器的IP地址


java中獲取當前服務器地址主要使用到InetAddress這個類

public static void main(String[] args) {
        try {
            //用 getLocalHost() 方法創建的InetAddress的對象
            InetAddress address = InetAddress.getLocalHost();
            System.out.println(address.getHostName());//主機名
            System.out.println(address.getCanonicalHostName());//主機別名
            System.out.println(address.getHostAddress());//獲取IP地址
            System.out.println("===============");
            
            //用域名創建 InetAddress對象
            InetAddress address1 = InetAddress.getByName("www.wodexiangce.cn");
            //獲取的是該網站的ip地址,如果我們所有的請求都通過nginx的,所以這里獲取到的其實是nginx服務器的IP地址
            System.out.println(address1.getHostName());//www.wodexiangce.cn
            System.out.println(address1.getCanonicalHostName());//124.237.121.122
            System.out.println(address1.getHostAddress());//124.237.121.122
            System.out.println("===============");
            
            //用IP地址創建InetAddress對象
            InetAddress address2 = InetAddress.getByName("220.181.111.188");
            System.out.println(address2.getHostName());//220.181.111.188
            System.out.println(address2.getCanonicalHostName());//220.181.111.188
            System.out.println(address2.getHostAddress());//220.181.111.188
            System.out.println("===============");
            
            //根據主機名返回其可能的所有InetAddress對象
            InetAddress[] addresses = InetAddress.getAllByName("www.baidu.com");
            for (InetAddress addr : addresses) {
                System.out.println(addr);
                //www.baidu.com/220.181.111.188
                //www.baidu.com/220.181.112.244
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

如果使用了反向代理,這種獲取方式顯然是不准確的,我們采用的方法是新建一個java類,里面配的是當前服務器的IP地址(也就是說這個類在每個節點服務器上部署的是不同的),程序里用的話直接獲取這個工具類就可以了,雖然方法有點笨,但是解決問題了。

public class CommonServerIP {
    /**
     * 這個類主要是保存常用的一些固定的服務器IP
     */
     public static String CURRENT_SERVER="124.237.121.46";//當前服務器的ip地址
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM