javascriptでプライベートIPを取得する
- 2019.10.25
- 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となります
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<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と保存して、アップすれば表示されます
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
<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
コメントを書く