开发者社区> 问答> 正文

Java 获取本机的外网ip

Java 获取本机的外网ip. 本机为linux系统 快解救一下我吧

展开
收起
云栖技术 2016-06-06 10:59:49 5304 0
1 条回答
写回答
取消 提交回答
  • 社区爱好者,专为云栖社区服务!
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.URL;
    
    
    public class Listip {
    
    
    public static void main(String[] args) throws Exception {
    System.out.println("本机的外网IP是:"
    + Listip.getWebIp("http://iframe.ip138.com/ic.asp"));
    }
    
    
    public static String getWebIp(String strUrl) {
    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 + "\r\n");
    }
    
    
    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;
    
    
    }
    }
    2019-07-17 19:27:54
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载