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

本文展示了如何使用Java从公网获取IP地址并利用腾讯位置服务API解析IP找到对应的城市信息。首先通过HTTP请求获取公网IP,然后使用正则表达式过滤出IP。接着,利用腾讯的位置服务API结合申请的key获取城市信息。
摘要由CSDN通过智能技术生成

 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”需要更改

 <!-- 腾讯位置服务-->
        <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 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;
    }

}

 4.封装

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

package com.jd.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class IpConfig {

    @Bean
    public  IpToAddressUtil ipToAddressUtil(){
        return  new IpToAddressUtil();
    }

    @Bean
    public IPUtil ipUtil(){
        return new IPUtil();
    }


}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值