1. 获取内网ip

public static String getLocalAddress(){
    String ip = "";
    try {
        ip = InetAddress.getLocalHost().getHostAddress();
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return ip;
}

2. 获取外网ip

方法一:
public static String getV4IP(){
    String ip = "";
    String chinaz = "http://ip.chinaz.com";
    
    StringBuilder inputLine = new StringBuilder();
    String read = "";
    URL url = null;
    HttpURLConnection urlConnection = null;
    BufferedReader in = null;
    try {
        url = new URL(chinaz);
        urlConnection = (HttpURLConnection) url.openConnection();
        in = new BufferedReader( new InputStreamReader(urlConnection.getInputStream(),"UTF-8"));
        while((read=in.readLine())!=null){
            inputLine.append(read+"\r\n");
        }
        //System.out.println(inputLine.toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally{
        if(in!=null){
            try {
                in.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    
    
    Pattern p = Pattern.compile("\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>");
    Matcher m = p.matcher(inputLine.toString());
    if(m.find()){
        String ipstr = m.group(1);
        ip = ipstr;
        //System.out.println(ipstr);
    }
    return ip;
}
方法二:
    public static String getIP()  {
        String ip = "http://pv.sohu.com/cityjson?ie=utf-8";
        String inputLine = "";
        String read = "";
        String toIp="";
        try {
            URL url = new URL(ip);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            while ((read = in.readLine()) != null) {
                inputLine += read;
            }
            String ObjJson=inputLine.substring(inputLine.indexOf("=")+1,inputLine.length()-1);
            System.out.println(ObjJson);
            //toIp = ObjJson;
            JSONObject jsonObj= JSON.parseObject(ObjJson);
            toIp=jsonObj.getString("cip");
//            throw new Exception();
        } catch (Exception e) {
            toIp="";
        }
        return toIp;
    }
分类: 技术 标签: 暂无标签

评论

暂无评论数据

暂无评论数据

目录