ウェブ家の備忘録

ウェブデザイナーの備忘録

JavaScriptで自分のPrivate IPアドレスを取得


// Vender Prefixありバージョンの場合も考慮
window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
// RTCPeerConnectionコネクションを作成。NAT越えは不要なのでiceServersは未指定
var pc = new RTCPeerConnection({iceServers:[]}), noop = function(){};      
// データチャンネルを作成
pc.createDataChannel('');
// Offer送信
pc.createOffer(pc.setLocalDescription.bind(pc), noop);
pc.onicecandidate = function(ice) {
  if (ice && ice.candidate && ice.candidate.candidate) {
            console.log(ice.candidate.candidate);
      // 正規表現を使ってIPアドレスだけ抜き出す。
      var myIP = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/.exec(ice.candidate.candidate)[1];
      console.log(myIP);
      pc.onicecandidate = noop;
  }
};

https://qiita.com/nightyknite/items/26090efff7d2f0a66300