packagecom.ini.ip;importjava.io.IOException;importjava.io.InputStream;importjava.io.PrintWriter;importjava.net.URL;importjava.net.URLConnection;importjava.util.regex.Matcher;importjava.util.regex.Pattern;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;/***@authorKYOXUE*/@WebServlet(name="ip",description="获取本机官网IP",urlPatterns = { "/get"},loadOnStartup=1)public class IpService extendsHttpServlet{private static final long serialVersionUID = 1L;private final static String QUERY_IP_ROOT="http://www.ip138.com/";private final static String CONTENT_ENCODING="GB2312";
String getContent(String action,String content_encoding)throwsException{
URLConnection conn= null;
InputStream is= null;
String ret= "";try{
URL url= newURL(action);
conn=url.openConnection();
is=conn.getInputStream();intlen;byte buf[] = new byte[40];while((len=is.read(buf))!=-1){
ret+= newString(buf,content_encoding);
}
}catch(Exception e) {throwe;
}finally{if (is!=null) {try{
is.close();
}catch(Exception e2) {
}
}
}returnret;
}
@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throwsServletException, IOException {
String result= "";
PrintWriter print= null;try{
print=resp.getWriter();
resp.setContentType("text/html;charset=utf-8");
String rootHtml=getContent(QUERY_IP_ROOT, CONTENT_ENCODING);
String startIndex= "
String endIndex= "\" rel=\"nofollow\" frameborder=\"0\" scrolling=\"no\">
";int start =rootHtml.indexOf(startIndex);int end =rootHtml.indexOf(endIndex);String ipRequest= rootHtml.substring(start+startIndex.length(),end);if (null == ipRequest || ipRequest.length() == 0) {
result="404";return;
}
String ip=getContent(ipRequest, CONTENT_ENCODING);
String regex= "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
Pattern p=Pattern.compile(regex);
Matcher m=p.matcher(ip);if(m.find()){
result=m.group(0);
}else{
result="404";return;
}
}catch(Exception e) {
result="500";
}finally{try{if (print!=null) {
print.print(result);
print.flush();
print.close();
}
}catch(Exception e2) {
}
}
}
@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throwsServletException, IOException {this.doGet(req, resp);
}
}