您的位置:

前端如何获取IP地址

一、利用JavaScript获取IP地址

1、通过向第三方服务器发送请求获取IP


function getIP(callback) {
  const xhr = new XMLHttpRequest();
  xhr.open("GET", "https://api.ipify.org", true);
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        callback(xhr.responseText);
    }
  };
  xhr.send();
}
getIP(function(ip){
  console.log(ip);
})

2、通过WebSocket获取IP


const socket = new WebSocket("wss://echo.websocket.org");
socket.onopen = function(event) {
  socket.send("getIP");
};
socket.onmessage = function(event) {
  const ip = event.data;
  console.log(ip);
  socket.close();
};

二、利用WebRTC技术获取IP地址

1、获取局域网IP


function getIPAddresses() {
  const rtcp = new RTCPeerConnection({iceServers:[]});
  const addrs = {};
  rtcp.createDataChannel('', {reliable:false});
  rtcp.onicecandidate = function(evt) {
    if (evt.candidate) {
      const addr = /[0-9]+(?:\.[0-9]+){3}/.exec(evt.candidate.candidate)[0];
      addrs[addr] = true;
      console.log(Object.keys(addrs));
    }
  };
  setTimeout(function() { rtcp.close(); }, 500);
}
getIPAddresses();

2、获取公网IP


let gettingIPInfo = new Promise((resolve, reject)=> {
  window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
  if (!window.RTCPeerConnection) {
    reject("WebRTC not supported");
  }
  let pc = new RTCPeerConnection();
  let ips = [];
  pc.createDataChannel("");
  pc.createOffer((result)=>{
      let sdp = result.sdp;
      let lines = sdp.split("\n");
      lines.forEach ((line,index)=>{
          if(line.indexOf("candidate") !== -1) {
              let regex = /(?<=ip\s)(\d+\.)+\d+/g;
              let ip = regex.exec(lines[index])[0];
              ips.push(ip);
          }
      });
      resolve(ips);
  });
});

gettingIPInfo.then((ips)=>{
  console.log(ips);
});

三、利用第三方服务获取IP地址

1、通过ip138.com获取IP


$.ajax({
  url: 'https://api.ip138.com/ip/?ip=&datatype=jsonp&token=您申请的Token',
  type: 'get',
  dataType: 'jsonp',
  success: function (data) {
      console.log(data);
  }
});

2、通过ipify.org获取IP


$.getJSON("https://api.ipify.org?format=json", function(data){
    console.log(data.ip);
});

四、利用后端服务获取IP地址

1、通过Node.js获取IP


const http = require('http');
const server = http.createServer((req, res) => {
  const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
  res.end(ip);
});
server.listen(3000);

2、通过PHP获取IP


echo $_SERVER['REMOTE_ADDR'];

3、通过Java获取IP


String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  ip = request.getRemoteAddr();
}
return ip;