到目前为止,我执行以下操作:
driver.get("http://www.whatismyip.com/");
String myIP = driver.findElement(By.id("greenip")).getText();
System.out.println(myIP);
还有更好的方法吗?
(PS:我试过this solution但是NetworkInterface提供了多个IP,另一方面InetAddress.getLocalHost().getHostAddress()
提供了错误的IP。)
答案 0 :(得分:1)
public static String getIpAddress()
{
URL myIP;
try {
myIP = new URL("http://api.externalip.net/ip/");
BufferedReader in = new BufferedReader(
new InputStreamReader(myIP.openStream())
);
return in.readLine();
} catch (Exception e)
{
try
{
myIP = new URL("http://myip.dnsomatic.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(myIP.openStream())
);
return in.readLine();
} catch (Exception e1)
{
try {
myIP = new URL("http://icanhazip.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(myIP.openStream())
);
return in.readLine();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
return null;
}
现在用这个你可以从互联网上获取你的IP,但这又是你的外部IP