1

I'm looking for a simple function (as simple as it can be) for returning the public ip address. I came across this function:

const clientsIpAdress = (onNewIP) => {
  const MyPeerConnection =
    window.RTCPeerConnection ||
    window.mozRTCPeerConnection ||
    window.webkitRTCPeerConnection;
  const pc = new MyPeerConnection({
    iceServers: []
  });
  const noop = () => {};
  const localIPs = {};
  const ipRegex =
    /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g;

  const iterateIP = (ip) => {
    if (!localIPs[ip]) onNewIP(ip);
    localIPs[ip] = true;
  };
  pc.createDataChannel('');
  pc.createOffer().then((sdp) => {
    sdp.sdp.split('\n').forEach((line) => {
      if (line.indexOf('candidate') < 0) return;
      line.match(ipRegex).forEach(iterateIP);
    });

    pc.setLocalDescription(sdp, noop, noop);
  });
  pc.onicecandidate = (ice) => {
    if (!ice || !ice.candidate ||
      !ice.candidate.candidate ||
      !ice.candidate.candidate.match(ipRegex)) return;
    ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
  };
};
export default clientsIpAddress;

but it is returning the local ipAddress. Any ideas?

4
  • You will need to use another source to determine that address. The local machine generally has no knowledge of the public address. Commented Apr 26, 2017 at 8:20
  • Ok thanks! I'm new to javascript and i must complete this task. Can you provide me a guideline? Commented Apr 26, 2017 at 8:21
  • You may want to perform an HTTP request to ipify: api.ipify.org Commented Apr 26, 2017 at 8:22
  • 2
    Sorry, I couldn't answer this, as I don't know how to do it... I just know the networking side :) Seems you have an answer below. Commented Apr 26, 2017 at 8:29

1 Answer 1

2

$(document).ready(function () {
    $.getJSON("http://jsonip.com/?callback=?", function (data) {
        console.log(data);
        alert(data.ip);
    });
});
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</head>
</html>

Sign up to request clarification or add additional context in comments.

8 Comments

Excuse me i made an awfull mistake. I want the public ip not the local. I wrote this in my description but not in the Title :P
ohh i see, Wait a minute i am going to edit my answer.
You can approve if it is useful to you ! @user7334203
Can you write this in es6?
Yes it's works, just you have to enable "allow block script" from your browser in case it is not working.
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.