javascriptでプライベートIPを取得する
- 作成日 2019.10.25
- 更新日 2022.05.30
- javascript
- html, javascript

2019/10/25の段階で、 WebRTCがサポートされているブラウザ chromeとfirefoxで取得可能。IEは無理でした
WEBサーバー環境
- OS CentOS Linux release 8.0.1905 (Core)
- WEBサーバー nginx/1.16.1
JS部分
プライベートIPを取得するJSとなります
<script type="text/javascript">
window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
var pc = new RTCPeerConnection({iceServers:[]}), noop = function(){};
var myIP;
pc.createDataChannel('');
pc.createOffer(pc.setLocalDescription.bind(pc), noop);
pc.onicecandidate = function(ice) {
if (ice && ice.candidate && ice.candidate.candidate) {
// 正規表現でIPアドレスを表示する
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;
}
};
</script>
github
取得用ソースコード
nuxt.jsのCSSを利用して、フロントは実装。任意の名称でhtmlと保存して、アップすれば表示されます
<html>
<head>
<title>プライベートIP取得</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<style>
html {
font-family: "Source Sans Pro", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
font-size: 16px;
word-spacing: 1px;
-ms-text-size-adjust: 100%;
-webkit-text-size-adjust: 100%;
-moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
box-sizing: border-box;
}
.container {
min-height: 100vh;
display: -webkit-box;
display: flex;
-webkit-box-pack: center;
justify-content: center;
-webkit-box-align: center;
align-items: center;
text-align: center;
}
.title {
font-family: "Quicksand", "Source Sans Pro", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
/* 1 */
display: block;
font-weight: 300;
font-size: 100px;
color: #35495e;
letter-spa0cing: 1px;
}
</style>
<body>
<div>
<section class="container">
<div>
<h1 id="ip" class="title"></h1>
</div>
</section>
</div>
</body>
<script type="text/javascript">
window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
var pc = new RTCPeerConnection({ iceServers: [] }), noop = function () { };
var myIP;
pc.createDataChannel('');
pc.createOffer(pc.setLocalDescription.bind(pc), noop);
pc.onicecandidate = function (ice) {
if (ice && ice.candidate && ice.candidate.candidate) {
// 正規表現でIPアドレスを表示する
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);
const ip = document.getElementById("ip");
ip.textContent = myIP;
pc.onicecandidate = noop;
}
};
</script>
</html>
-
前の記事
Window10 nuxt.jsを使用してみる 2019.10.25
-
次の記事
CentOs8 Nginx(stable版)をインストール 2019.10.25
コメントを書く