1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 获取公网 局域网 以及根据ip地址找城市

获取公网 局域网 以及根据ip地址找城市

时间:2022-07-05 03:43:23

相关推荐

获取公网 局域网 以及根据ip地址找城市

1.公网代码

package com.fan.study.ip;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import .HttpURLConnection;import .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: /5/11**/public static String getIP() throws IOException {String ip = null;String chinaZ = "";String response = sendGet(chinaZ);//过滤出响应中外网IPip = match(response, "\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>");if (ip == null) {String newUrl = match(response, "window.location.href=\"(.+)\"");response = sendGet(newUrl);ip = match(response, "\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>");} return ip;}/*** @Param str* @Param regex* @Description 正则过滤* @Date: /5/11**/public static String match(String str, String regex) {Pattern p = pile(regex);Matcher m = p.matcher(str);if (m.find()) {return m.group(1);}return null;}/*** @Param url* @Description 发送get请求* @Date: /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”需要更改。

<!-- 腾讯位置服务--><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.80</version></dependency>

package com.lingfen.website.blog.utils;import com.alibaba.fastjson.JSONObject;import java.io.BufferedReader;import java.io.InputStreamReader;import .URL;import .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./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;}}

4.封装

如果定义类对象时候,有红色下划线,就用一个config类把获取公网ip的类和找城市的类封装起来

package com.jd.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class IpConfig {@Beanpublic IpToAddressUtil ipToAddressUtil(){return new IpToAddressUtil();}@Beanpublic IPUtil ipUtil(){return new IPUtil();}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。