1. 获取本机内网网ip
public class Test {
public static void main(String[] args) throws IOException {
System.out.println("内外ip:" + getIp());
System.out.println("外网ip:" + getMyIP());
}
/**
* 获取本机内网ip
* @return
* @throws UnknownHostException
*/
private static String getIp() throws UnknownHostException {
String ip = InetAddress.getLocalHost().getHostAddress();
return ip;
}
/**
* 获取本机外网ip
* @return
*/
private static String getMyIP() throws IOException {
String url = "http://ip.chinaz.com/getip.aspx";
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
String msg = sb.toString();
String[] msgs = msg.split(",");
String[] ips = msgs[0].split(":");
return ips[1].substring(1, ips[1].length()-1);
} finally {
is.close();
}
}
}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。