获取上网IP
这两天在做一个根据IP地址来定位城市的功能。两个方案:1.自己解析纯真IP库,2.用网上现成的IP查询接口获取IP。这两个方案都做了,但是觉得第一个方案实在是太操蛋了,qqwry.dat文件就8M,再加上我的程序,这个文件就太大了,装好就有7M左右,实在是恐怖。所以就执行了第二个方案。移动互联网嘛,不互联怎么和世界沟通??呵呵……接下来的问题就来了,我怎么获取我自己的IP呢?
网上有这个方法:
public class IPNetUtils {private static final String IP_URL = "http://www.ip138.com/ip2city.asp";private static final String CHARTSET = "UTF-8";/** * 获得IP * * @return */public static String getIPInfo() {URL urlInUse = null;URLConnection conn = null;ArrayList<String> list = new ArrayList<String>();String temp = "";try {urlInUse = new URL(IP_URL);conn = urlInUse.openConnection();InputStream in = conn.getInputStream();BufferedReader bf = new BufferedReader(new InputStreamReader(in,CHARTSET));String line = "";while ((line = bf.readLine()) != null) {list.add(line.trim());}if (list != null) {temp = list.get(5);}} catch (MalformedURLException e) {e.printStackTrace();} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return getIP(temp);}/** * 截取IP * * @param str * @return */private static String getIP(String str) {return str.substring(str.indexOf('[') + 1, str.indexOf(']'));}}