//获取客户端IP地址
function getCusIpAdress(){
    var data;
    let xmlHttpRequest;
    if(window.ActiveXObject){
        xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }else if(window.XMLHttpRequest){
        xmlHttpRequest = new XMLHttpRequest();
    }
    xmlHttpRequest.onreadystatechange=function(){
        if(xmlHttpRequest.readyState == 4){
            if(xmlHttpRequest.status == 200) {
                data=xmlHttpRequest .responseText;
            } else {
                alert("error:HTTP状态码为:"+xmlHttpRequest.status);
            }
        }
    };
    var date = new Date();
	var year = date.getFullYear();
    xmlHttpRequest.open("get", "https://"+year+".ip138.com", false);
    xmlHttpRequest.send(null);
    var datalist = data.split("\n");
    var patt = [/[0-9]+.[0-9]+.[0-9]+.[0-9]+/, /来自/, []];
    for (var i in datalist){
        if (patt[0].test(datalist[i]) && patt[1].test(datalist[i])){
            patt[2].push(patt[0].exec(datalist[i])[0]);
            patt[2].push(datalist[i].substr(patt[1].exec(datalist[i]).index+3));
        }
    }
    return patt[2];
}


// 调用
console.log(getCusIpAdress());
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐