12

I'm trying to get the client's IP address. This is my code so far. Any suggestions?

<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>
Amadan
  • 191,408
  • 23
  • 240
  • 301
Naam
  • 121
  • 1
  • 1
  • 4
  • 2
    Your code is perfectly fine. (You were using SO Snippets incorrectly, your code was in "JavaScript", but needed to be in "HTML", so I fixed it for you.) – Amadan Jan 18 '17 at 05:20
  • 1
    Possible duplicate of [How to get client's IP address using JavaScript only?](https://stackoverflow.com/questions/391979/how-to-get-clients-ip-address-using-javascript-only) – Donald Duck Aug 13 '17 at 08:53
  • How can I use this in a JS file, rather than in the HTML file? –  Mar 27 '22 at 14:36

7 Answers7

9

Try This.Little bit Help to you.

<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>
ssc-hrep3
  • 15,024
  • 7
  • 48
  • 87
Sanjay
  • 2,481
  • 1
  • 13
  • 28
5

please try below code:-

<!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()
{
   window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;  
 var pc = new RTCPeerConnection({iceServers:[]}), 
 noop = function(){}; 
     
    pc.createDataChannel("");  
 pc.createOffer(pc.setLocalDescription.bind(pc), noop);   
     pc.onicecandidate = function(ice){ 
    if(!ice || !ice.candidate || !ice.candidate.candidate)  return;

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

        
 $('.ipAdd').text(myIP);
  
         pc.onicecandidate = noop;
  
  }; 
});
      
</script>
</html>
Sarika Koli
  • 773
  • 6
  • 11
  • So far all answers I have seen are using external link. But your answer does not any third party url... Do you know how to achieve this in Angular ? – SK. Oct 19 '18 at 20:36
  • This should be marked as the correct answer. Doesn't need any external network call. Thanks – Ndivhuwo Jul 23 '19 at 09:00
  • 1
    The above code is giving me "Uncaught TypeError: Cannot read property '1' of null" for the below line: `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];` I tried to debug and post the entire content of this command and found that element [1] of the array is "" `/()/.exec(ice.candidate.candidate);` **Output:** (2) ["", "", index: 0, input: "candidate:119889386 1 udp 2113937151 98dff370-ffe5…typ host generation 0 ufrag gNsA network-cost 999", groups: undefined] – Jaison Varghese Aug 13 '19 at 16:32
  • I'm getting the above error on Chrome only. Code is working on Firefox – Jaison Varghese Aug 13 '19 at 16:38
  • That regex is looking for an IP address (v4 or v6!) in ice.candidate.candidate, not finding one, and returning null, then the browser complains about null[1]. logging ice.candidate.candidate it looks like it has .local instead of an actual IP (I tried both Chrome and Firefox). Too bad, it would be a nice technique if it worked everywhere. – blm Jan 20 '23 at 19:58
3
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();
}
Kaushik Makwana
  • 2,422
  • 9
  • 31
  • 50
0

The JSON variable that is returned can be navigated like any object in 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>
GantTheWanderer
  • 1,255
  • 1
  • 11
  • 19
0

try this

    $.ajax({
        url: "//api.ipify.org/?format=json",
        dataType: 'JSON',
    }).success(function(data) {
        console.log(data.ip);
    }).error(function (jqXHR, textStatus, errorThrown) {
        console.log(jqXHR);
        console.log(textStatus);
        console.log(errorThrown);
    });
0

How to get current ip address using angular? Please refer link : https://github.com/apilayer/freegeoip#readme

https://ipstack.com/

OR 

getIpAddress(){
this.http.get<{ip:string}>('https://jsonip.com')
    .subscribe( data => {
      console.log('th data', data);
      this.ipAddress = data
    })
}
Sanjay
  • 2,481
  • 1
  • 13
  • 28
0
<script>
$.getJSON('http://ip-api.com/json', function(ipData){
      document.write(ipData.query)          
});
</script>
Shriyank
  • 47
  • 6