JS获取客户端公网IP和IP地址

网上解决方案

1.通过搜狐接口

获取方式如下:

//网页端引入脚本
<script type="text/javascript" src="http://pv.sohu.com/cityjson?ie=utf-8"></script>
//JS端直接获取
returnCitySN["cip"]

缺点:目前对于公网IP的地址只精确到省,没有详细的IP信息

2.通过淘宝接口

获取方式不详细介绍,不推荐此解决方案获取
缺点:时不时就挂掉了获取不到,非常不稳定

3.通过腾讯位置API

查看API网址腾讯位置接口

获取方式通过跨域ajax获取:

//JS AJAX
function() {
        var data = { key: "这里填写注册腾讯api时返回的key" };//ip缺省时会自动获取请求端的公网IP,
        var url = "https://apis.map.qq.com/ws/location/v1/ip";
        data.output = "jsonp";
        $.ajax({
            type: "get",
            dataType: 'jsonp',
            data: data,
            jsonp: "callback",
            url: url,
            success: function (json) {
                array = new Array;
                array.push(json.result.ip);//公网IP
                array.push(json.result.ad_info.province + json.result.ad_info.city + json.result.ad_info.district);//省市区
                array.push(json.result.location.lat);//经度
                array.push(json.result.location.lng);//纬度
                return array;
            },
            error: function (err) {
                //业务处理
            }
        });
    }

缺点:需要注册腾讯自己的key,目的在于控制调用腾讯位置接口服务的权限,注册后还会有调用次数限制,个人和企业不同

推荐第三种获取公网IP解决方案

原文地址:https://www.cnblogs.com/ButterflyEffect/p/10789073.html