如何通过Java代码准确获取并查询当前设备的IP地址?
- 内容介绍
- 文章标签
- 相关推荐
本文共计202个文字,预计阅读时间需要1分钟。
java获取公网IP地址:private static String getMyIP() throws IOException { InputStream ins=null; try { URL url=new URL(http://www.ip138.com/ip2city.asp); HttpURLConnection con=url.openConnection(); ins=con.getInputStream(); // 读取输入流中的内容 // ... } finally { if (ins !=null) { ins.close(); } } return null;}
获取公网ip/** * 获取公网ip * return String * */ private static String getMyIP() throws IOException { InputStream ins = null; try { URL url = new URL("www.ip138.com/ip2city.asp"); URLConnection con = url.openConnection(); ins = con.getInputStream(); InputStreamReader isReader = new InputStreamReader(ins, "GB2312"); BufferedReader bReader = new BufferedReader(isReader); StringBuffer webContent = new StringBuffer(); String str = null; while ((str = bReader.readLine()) != null) { webContent.append(str); } int start = webContent.indexOf("[") + 1; int end = webContent.indexOf("]"); return webContent.substring(start, end); } finally { if (ins != null) { ins.close(); } } } 获取本地ip
private static String getMyIPLocal() throws IOException { InetAddress ia = InetAddress.getLocalHost(); return ia.getHostAddress(); } 测试
public static void main(String[] args) { try { long beginTime = System.currentTimeMillis(); System.out.println("公网ip:"+getMyIP()); System.out.println("局域网ip:"+getMyIPLocal()); long endTime = System.currentTimeMillis(); System.out.println(endTime-beginTime); } catch (IOException e) { e.printStackTrace(); } } TIM截图20171009163741.jpg
本文共计202个文字,预计阅读时间需要1分钟。
java获取公网IP地址:private static String getMyIP() throws IOException { InputStream ins=null; try { URL url=new URL(http://www.ip138.com/ip2city.asp); HttpURLConnection con=url.openConnection(); ins=con.getInputStream(); // 读取输入流中的内容 // ... } finally { if (ins !=null) { ins.close(); } } return null;}
获取公网ip/** * 获取公网ip * return String * */ private static String getMyIP() throws IOException { InputStream ins = null; try { URL url = new URL("www.ip138.com/ip2city.asp"); URLConnection con = url.openConnection(); ins = con.getInputStream(); InputStreamReader isReader = new InputStreamReader(ins, "GB2312"); BufferedReader bReader = new BufferedReader(isReader); StringBuffer webContent = new StringBuffer(); String str = null; while ((str = bReader.readLine()) != null) { webContent.append(str); } int start = webContent.indexOf("[") + 1; int end = webContent.indexOf("]"); return webContent.substring(start, end); } finally { if (ins != null) { ins.close(); } } } 获取本地ip
private static String getMyIPLocal() throws IOException { InetAddress ia = InetAddress.getLocalHost(); return ia.getHostAddress(); } 测试
public static void main(String[] args) { try { long beginTime = System.currentTimeMillis(); System.out.println("公网ip:"+getMyIP()); System.out.println("局域网ip:"+getMyIPLocal()); long endTime = System.currentTimeMillis(); System.out.println(endTime-beginTime); } catch (IOException e) { e.printStackTrace(); } } TIM截图20171009163741.jpg

