1

I couldn't find any javascript file that would get the remote address(ip). I am thinking of creating my own javascript helper with api, but maybe there is a better way or the javascript that I am looking for already exists.

Any help is welcome, tnx fellas :)

2 Answers 2

1

You get the ip of the customer with javascript using WebRTC, not all browsers support this check here.

function findIP(onNewIP) { //  onNewIp - your listener function for new IPs
  var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; //compatibility for firefox and chrome
  var pc = new myPeerConnection({iceServers: []}),
    noop = function() {},
    localIPs = {},
    ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,
    key;

  function ipIterate(ip) {
    if (!localIPs[ip]) onNewIP(ip);
    localIPs[ip] = true;
  }
  pc.createDataChannel(""); //create a bogus data channel
  pc.createOffer(function(sdp) {
    sdp.sdp.split('\n').forEach(function(line) {
      if (line.indexOf('candidate') < 0) return;
      line.match(ipRegex).forEach(ipIterate);
    });
    pc.setLocalDescription(sdp, noop, noop);
  }, noop); // create offer and set local description
  pc.onicecandidate = function(ice) { //listen for candidate events
    if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
    ice.candidate.candidate.match(ipRegex).forEach(ipIterate);
  };
}



var ul = document.createElement('ul');
ul.textContent = 'Your IPs are: '
document.body.appendChild(ul);

function addIP(ip) {
  console.log('got ip: ', ip);
  var li = document.createElement('li');
  li.textContent = ip;
  ul.appendChild(li);
}

Credit goes to https://stackoverflow.com/a/32841164/1016425

Or you can try this instead:

$.getJSON('//freegeoip.net/json/?callback=?', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

Or check this post for multiple ways of doing it: https://stackoverflow.com/a/35123097/1016425

0

You can assign $_SERVER['REMOTE_ADDR'] to to JavaScript variable

<script type="text/javascript">
    var RemoteAddress  = '<?php echo $_SERVER['REMOTE_ADDR'];?>';
    console.log(RemoteAddress);
</script> 

you can use this RemoteAddress variable in js file as well but make sure you call this before including js files

2
  • This would raise the issue of where to put the code, a good solution however.
    – Olavi Sau
    Mar 15, 2016 at 10:36
  • Yes. You need to put in global template like page/html/head.phtml in magento 1.x. not sure for magento2 Mar 15, 2016 at 10:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.