内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
下面的IPAddress类只获取机器的本地IP地址。
public class IPAddress { private InetAddress thisIp; private String thisIpAddress; private void setIpAdd() { try { InetAddress thisIp = InetAddress.getLocalHost(); thisIpAddress = thisIp.getHostAddress().toString(); } catch (Exception e) { } } protected String getIpAddress() { setIpAdd(); return thisIpAddress; } }
可以使用Amazon服务。http://checkkip.amazonaws.com
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; public class IpChecker { public static String getIp() throws Exception { URL whatismyip = new URL("http://checkip.amazonaws.com"); BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader( whatismyip.openStream())); String ip = in.readLine(); return ip; } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } }