package com.example.common;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import net.sf.json.JSONObject;
public class IpAddressDemo {
/**
* 本地IP地址
* @return
*/
public static void getLocalIP() {
InetAddress addr;
try {
addr = InetAddress.getLocalHost();
System.out.println("Local HostAddress: "+addr.getHostAddress()); String
hostname = addr.getHostName();
System.out.println("Local host name: "+hostname);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
/*
* 获得本机公网ip
*/
public static String getIP() {
String ip = "http://pv.sohu.com/cityjson?ie=utf-8";
String inputLine = "";
String read = "";
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;
}
} catch (Exception e) {
e.printStackTrace();
}
String[] split = inputLine.replace(";", "").split("=");
JSONObject json = JSONObject.fromObject(split[1]);
String ipstr = json.get("cip").toString();
return ipstr;
}
/**
* 调用百度api返回ip地址的定位
* @return
* @throws IOException
*/
public static String getAddrName() throws IOException{
//这里调用百度的ip定位api服务 详见 http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm
JSONObject json = readJsonFromUrl("http://api.map.baidu.com/location/ip?ak=oBbSaFZqmC0i1CNg8rYwaSkGlmdYHbAO&ip="+getIP());
/* 获取到的json对象:
* {"address":"CN|河北|保定|None|UNICOM|0|0",
* "content":{"address_detail":{"province":"河北省","city":"保定市","street":"","district":"","street_number":"","city_code":307},
* "address":"河北省保定市","point":{"x":"12856963.35","y":"4678360.5"}},
* "status":0}
*/
//这里我们可以输出json看一下具体格式
System.out.println(json.toString());
JSONObject content=json.getJSONObject("content"); //获取json对象里的content对象
JSONObject addr_detail=content.getJSONObject("address_detail");//从content对象里获取address_detail
String city=addr_detail.get("city").toString(); //获取市名,可以根据具体需求更改,如果需要获取省份的名字,可以把“city”改成“province”...
return city;
}
public static JSONObject readJsonFromUrl(String url) throws IOException {
InputStream is = null;
try {
is = new URL(url).openStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = JSONObject.fromObject(jsonText);
return json;
} finally {
//关闭输入流
is.close();
}
}
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static void main(String[] args) throws IOException {
System.out.println(getAddrName());
System.out.println(getIP());
}
}