Share your repls and programming experiences

← Back to all posts
Problem trying to get user ip
h
PixelNinja (314)

Hi,

I am trying to make an ip ban system which requires the client to get there ip and then send it to the server, I have no clue how to get there ip, i have done some research and found nothing! Thanks!

Comments
hotnewtop
squeegily (0)

You could use XHR or Fetch with icanhazip, if you're running client-side in-browser JS.

Be aware, though, that a malicious client can alter this code, so it may not be useful for your use-case.

Here's a function which should simply work, and serve all reasonable (and some unreasonable) use-cases:

function icanhazip(forceipversion=null, asynchronous=false) {
    // GENERAL-PURPOSE ICANHAZIP FUNCTION

    // Usage:
    //  0. If you call the function, it will
    //     return the client's IP address.
    //
    //  1. If your code expects an IPv4 address,
    //     you MUST pass 4 as the first option.
    //
    //  2. If you want their IPv6 address,
    //     pass 6 as the first option.
    //
    //  3. If you are OK with any version of IP address,
    //     pass null as the first option.
    //
    //  4. If you want to send the request asynchronously,
    //     pass true as the second option. In this case, the
    //     function will return a Promise which resolves to
    //     the client's IP address.

    function ok(status) { return (status / 100 | 0) == 2; }

    const xhr = new XMLHttpRequest();
    xhr.open('GET', `https://${forceipversion ? `ipv${forceipversion}.` : ''}icanhazip.com/`, asynchronous);
    if (!asynchronous) {
        xhr.send();
        if (!ok(xhr.status)) throw xhr;
        return xhr.response.trim();
    } else {
        return new Promise((resolve, reject) => {
            xhr.onload = e => {
               if (!ok(e.target.status)) return reject(e.target);
               resolve(e.target.response.trim());
            };
            xhr.onerror = e => reject(e.target);
            xhr.send();
        });
    }
}

(From there, you could use XHR or Fetch or whatever to communicate the IP to the server-side code.)

HackermonDev (2009)

@theangryepicbanana Why does his repl say it refused to connect?