gpt4 book ai didi

java - 如何在 Java 中获取计算机的 WAN IP 地址?

转载 作者:行者123 更新时间:2023-11-29 08:17:02 26 4
gpt4 key购买 nike

如何使用 Java 获取计算机的广域网?我试试这个:

ServerSocket ss = new ServerSocket(port);
System.out.println(ss.getInetAddress().getHostAddress());
//wich return 0.0.0.0

然后我试试这个:

System.out.println(InetAddress.getLocalHost().toString());
//which return keenan-a658368c/192.168.1.100 < yes it is connected to router

如函数所说,它返回我的本地 IP 地址

如何获取 WAN IP 地址?例如 118.137.43.219

最佳答案

你可以从http://whatismyip.com/automation/n09230945.asp得到它.您可以打开此站点的 HttpURLConnection 并解析输出。

这个程序应该有帮助:

import java.net.HttpURLConnection;

public class GetExternalIp {

public static void main(String args[]) {
try {

java.net.URL url = new java.net.URL(
"http://whatismyip.com/automation/n09230945.asp");

java.net.HttpURLConnection con = (HttpURLConnection) url
.openConnection();

java.io.InputStream stream = con.getInputStream();

java.io.InputStreamReader reader = new java.io.InputStreamReader(
stream);

java.io.BufferedReader bReader = new java.io.BufferedReader(reader);

System.out.print("Your IP address is " + bReader.readLine());

} catch (Exception e) {
e.printStackTrace();
}

}

}

引用自:

http://www.daniweb.com/forums/thread192872.html

http://www.coderanch.com/t/411356/java/java/Public-IP-Address-time-limit

关于java - 如何在 Java 中获取计算机的 WAN IP 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3882376/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com