Java 获取公网ip地址或内网地址
public String getIPAddress(){  
    try {  
        URL url = new URL("http://checkip.amazonaws.com/");  
        BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));  
        String ip = br.readLine().trim();  
        System.out.println("Public IP Address: " + ip);  
        return ip;  
    } catch (Exception e) {  
        System.out.println("Error in getting public IP address, trying to get local IP address.");  
        try {  
            String localIP = getLocalIP();  
            System.out.println("Local IP Address: " + localIP);  
        } catch (SocketException se) {  
            System.out.println("Error in getting local IP address: " + se.getMessage());  
        }  
    }  
    return null;  
}  
  
private static String getLocalIP() throws SocketException {  
    Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();  
    while (networkInterfaces.hasMoreElements()) {  
        NetworkInterface networkInterface = networkInterfaces.nextElement();  
        Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();  
        while (inetAddresses.hasMoreElements()) {  
            InetAddress inetAddress = inetAddresses.nextElement();  
            if (inetAddress instanceof Inet4Address && !inetAddress.isLoopbackAddress()) {  
                return inetAddress.getHostAddress();  
            }  
        }  
    }  
    return null;  
}

Pasted image 20240217210709.png

无网络环境则获取内网地址

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇