java获取本机公网IP

来源:互联网 发布:2017金英杰免费网络课 编辑:程序博客网 时间:2024/05/01 03:38
import java.io.BufferedReader;import java.io.InputStreamReader;import java.net.URL;public class Demo2 {public static void main(String[] args) throws Exception {  System.out.println("本机的外网IP是:" + Demo2.getWebIp()); } public static String getWebIp() {  String strUrl = "http://1111.ip138.com/ic.asp";  try {   URL url = new URL(strUrl);   BufferedReader br = new BufferedReader(new InputStreamReader(     url.openStream()));   String s = "";   StringBuffer sb = new StringBuffer("");   String webContent = "";   while ((s = br.readLine()) != null) {    sb.append(s + "rn");   }   br.close();   webContent = sb.toString();   int start = webContent.indexOf("[") + 1;   int end = webContent.indexOf("]");   //System.out.println("webContent=" + webContent);   //System.out.println("start=" + start);   //System.out.println("end=" + end);   if (start < 0 || end < 0) {    return null;   }   webContent = webContent.substring(start, end);   return webContent;  } catch (Exception e) {   e.printStackTrace();   return "error open url:" + strUrl;  } }}

0 0
原创粉丝点击