-2

Try to use json tag but there is some problem and not get the domain,try to use one tag for both domain and ip . there is any suggestion how to get both and print them.

Cœur
  • 32,421
  • 21
  • 173
  • 232
user3851652
  • 27
  • 1
  • 1
  • 7

4 Answers4

1

Logically, you will need send a request from client side and respond with IP using the server side scripting. There are several ways you can implement this.

Let me explain one way, you can do it: Send an ajax request to a PHP page on your code. PHP will give you the client IP. Support PHP page is getIP.php with following code:

header("Content-Type: application/json");
$sIP = $_SERVER['REMOTE_ADDR'];
echo json_encode($sIP);
exit();

Now you will need to send an AJAX request to your PHP page. Suppose we are achieving this using following method using jquery:

var myIP = '';
$.ajax({
  url: "getIP.php",
  method: "get",
  dataType: "json",
  success: function(data) {
    myIP = data;
  }
});

We just implemented the logic. But in case you don't have access to server side scripting. You can use any other API or services that give you the IP.

You can get domain using window.location.hostname

ksg91
  • 1,209
  • 14
  • 31
0

You can get the ip with an API.

And while googling to find one, found it here on SO Can I perform a DNS lookup (hostname to IP address) using client-side Javascript?

<script type="application/javascript">
    function getip(json){
      alert(json.ip); // alerts the ip address
    }
</script>

<script type="application/javascript" src="http://jsonip.appspot.com/?callback=getip"></script>

The domain name is very simple. Just use location.hostname

Community
  • 1
  • 1
Andreas Furster
  • 1,338
  • 1
  • 10
  • 26
0

Try this

<script type="application/javascript">
$.get("http://ipinfo.io", function(response) {
            alert(response.ip);
        }, "jsonp");
</script>

OR

<script type="application/javascript">
$.get("http://ipinfo.io/json", function(response) {
            console.log(response);
        });
</script>

JS Fiddle

Sadikhasan
  • 17,212
  • 19
  • 72
  • 111
0

You can access domain by

window.location.origin;

or in IE you may want to do this.

if (!window.location.origin) {
  window.location.origin = window.location.protocol + "//" + window.location.hostname +    
    (window.location.port ? ':' + window.location.port: '');
}

For ip, you would need to use 3rd party service to get ip. I like freegeoip

$.ajax({
    url: '//freegeoip.net/json/',
    type: 'POST',
    dataType: 'jsonp',
    success: function(location) {
        console.log(location.ip);//Apart from ip it also gives more details 
        //Like country etc
    }
});
Neo
  • 3,837
  • 6
  • 27
  • 43