2017-01-18 45 views
0

私はクライアントのIPアドレスを取得しようとしています。これはこれまでの私のコードです。 提案がありますか?JavaScriptでクライアントのIPアドレスを取得する方法は?

<script type="application/javascript"> 
 
    function getIP(json) { 
 
    document.write("My public IP address is: ", json.ip); 
 
    } 
 
</script> 
 
<script type="application/javascript" src="http://ipinfo.io/?format=jsonp&callback=getIP"></script>

+1

あなたのコードは完全に罰金です。 (あなたはSOのスニペットを間違って使用していました。あなたのコードは "JavaScript"になっていましたが、 "HTML"にする必要があったので、修正しました) – Amadan

+0

ありがとうございました。ありがとう – Naam

+0

JavaScriptでクライアントのIPアドレスを取得するにはどうすればいいですか?(https://stackoverflow.com/questions/391979/how-to-get-clients-ip-address-using-javascript-only) –

答えて

1

コードの下にしてみてください。 -

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> 
 

 
</head> 
 
<body> 
 
Ip Address:=<h3 class='ipAdd'><h3> 
 
    </body> 
 

 
<script> 
 
$(document).ready(function ubsrt() 
 
{ 
 
    \t window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; 
 
\t var pc = new RTCPeerConnection({iceServers:[]}), 
 
\t noop = function(){}; 
 
     
 
    \t pc.createDataChannel(""); 
 
\t pc.createOffer(pc.setLocalDescription.bind(pc), noop); 
 
    \t pc.onicecandidate = function(ice){ 
 
    \t if(!ice || !ice.candidate || !ice.candidate.candidate) return; 
 

 
     \t 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]; 
 

 
     
 
\t $('.ipAdd').text(myIP); 
 
    
 
     \t pc.onicecandidate = noop; 
 
    
 
\t }; 
 
}); 
 
     
 
</script> 
 
</html>

0

あなたにThis.Littleビットのヘルプを試してみてください。

document.write("My public IP address is: ", json.ip + " " +json.city + " "+json.region); 
+0

こんにちは。ありがとうsanjay。それは働いている。ありがとう – Naam

+0

お願いします.. –

0

返されるJSON変数は、javascriptのオブジェクトのようにナビゲートできます。

 <textarea id="text" style="width:100%;height:120px;"></textarea> 
 

 
     <script type="application/javascript"> 
 
     function getIP(json) { 
 
      document.getElementById("text").value = JSON.stringify(json, null, 2); 
 
     
 
     for (key in json) { 
 
      document.write("<br>" + key + " : ", json[key]); 
 
     } 
 
     } 
 
    </script> 
 
    <script type="application/javascript" src="http://ipinfo.io/?format=jsonp&callback=getIP"></script>

1
function user_location() { 
    var xhttp = new XMLHttpRequest(); 
    xhttp.onreadystatechange = function() { 
    if (this.readyState == 4 && this.status == 200) { 
     console.log(this.responseText); 
    } 
    }; 
    xhttp.open("GET", "//api.ipify.org?format=json", true); 
    xhttp.send(); 
} 
関連する問題