gpt4 book ai didi

java - 使用 InetAddress 获取自己的 IP

转载 作者:行者123 更新时间:2023-11-29 03:36:15 25 4
gpt4 key购买 nike

我有一个问题,如果我尝试 InetAddress.getLocalHost() 甚至 InetAddress.getByName(String host) 它每次都会抛出异常,即使是像 nba.com 这样的知名网站我也有点困惑,仅供引用目标设备是 android 4.1.1 GS3 并且 wifi 和移动网络已打开。代码如下

         try{
InetAddress ownIP=InetAddress.getLocalHost();
System.out.println("IP of my Android := "+ownIP.getHostAddress());
}catch (Exception e){
System.out.println("Exception caught ="+e.getMessage());
String t = e.getMessage() + "yes";
}

下面是System.out

03-12 18:59:52.636: I/System.out(18996): 捕获异常 =null

提前致谢

最佳答案

我使用了一种棘手的方法来获取我自己的 IP。你可以看看它是否对你有帮助

String getIP() {
try {
Socket socket = new Socket("google.com", 80);
return socket.getLocalAddress().getHostAddress();
} catch (Exception e) {

}
}

关于java - 使用 InetAddress 获取自己的 IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15374104/

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