?1.公网代码
package com.fan.study.ip;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IPUtil {
public static void main(String[] args) throws IOException {
System.out.println(IPUtil.getIP());
}
/**
* @Param
* @Description 获取IP
* @Date: 2021/5/11
**/
public static String getIP() throws IOException {
String ip = null;
String chinaZ = "http://ip.chinaz.com";
String response = sendGet(chinaZ);
//过滤出响应中外网IP
ip = match(response, "\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>");
if (ip == null) {
String newUrl = match(response, "window.location.href=\"(http://ip.chinaz.com.+)\"");
response = sendGet(newUrl);
ip = match(response, "\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>");
}
return ip;
}
/**
* @Param str
* @Param regex
* @Description 正则过滤
* @Date: 2021/5/11
**/
public static String match(String str, String regex) {
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
if (m.find()) {
return m.group(1);
}
return null;
}
/**
* @Param url
* @Description 发送get请求
* @Date: 2021/5/11
**/
public static String sendGet(String url) throws IOException {
URL urlObject = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlObject.openConnection();
connection.connect();
try (InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
StringBuilder response = new StringBuilder();
String str;
while ((str = reader.readLine()) != null) {
response.append(str);
}
return response.toString();
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}
2.内网
public static String getLocalIP() {
String ip = "";
if (System.getProperty("os.name").toLowerCase().startsWith("windows")) {
InetAddress addr;
try {
addr = InetAddress.getLocalHost();
ip = addr.getHostAddress();
} catch (UnknownHostException e) {
log.error("获取失败",e);
}
return ip;
} else {
try {
Enumeration<?> e1 = (Enumeration<?>) NetworkInterface
.getNetworkInterfaces();
while (e1.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) e1.nextElement();
if (!ni.getName().equals("eth0")) {
continue;
} else {
Enumeration<?> e2 = ni.getInetAddresses();
while (e2.hasMoreElements()) {
InetAddress ia = (InetAddress) e2.nextElement();
if (ia instanceof Inet6Address)
continue;
ip = ia.getHostAddress();
return ip;
}
break;
}
}
} catch (SocketException e) {
log.error("获取失败",e);
}
}
return "";
}
3.根据公网ip地址找城市
1.去腾讯位置服务腾讯位置服务 - 立足生态,连接未来,注册之后右上角控制台,然后”应用管理”创建应用,名字和类型随意,然后选择WebServiceApi,选择“授权ip”,填写ip范围,保存之后拿到key(每个人的key值不一样)值
package com.lingfen.website.blog.utils;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
public class IpToAddressUtil {
//使用腾讯的接口通过ip拿到城市信息
private static final String KEY = "自己的key";
public static String getCityInfo(String ip) {
String s = sendGet(ip, KEY);
Map map = JSONObject.parseObject(s, Map.class);
String message = (String) map.get("message");
if("query ok".equals(message)){
Map result = (Map) map.get("result");
Map addressInfo = (Map) result.get("ad_info");
String nation = (String) addressInfo.get("nation");
String province = (String) addressInfo.get("province");
// String district = (String) addressInfo.get("district");
String city = (String) addressInfo.get("city");
String address = nation + "-" + province + "-" + city;
return address;
}else{
System.out.println(message);
return null;
}
}
//根据在腾讯位置服务上申请的key进行请求操作
public static String sendGet(String ip, String key) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = "https://apis.map.qq.com/ws/location/v1/ip?ip="+ip+"&key="+key;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
// for (Map.Entry entry : map.entrySet()) {
// System.out.println(key + "--->" + entry);
// }
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
}
|