Share your repls and programming experiences

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


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!

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) {

    // 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();'GET', `https://${forceipversion ? `ipv${forceipversion}.` : ''}`, asynchronous);
    if (!asynchronous) {
        if (!ok(xhr.status)) throw xhr;
        return xhr.response.trim();
    } else {
        return new Promise((resolve, reject) => {
            xhr.onload = e => {
               if (!ok( return reject(;
            xhr.onerror = e => reject(;

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

PixelNinja (319)

@squeegily The idea is to get the connecting IP from the server, not to ask the client to respond with it.

programmeruser (615)

@squeegily bruh this is a 2 year old post
also it's impossible to get IPs without client side code which is not what he wants

HackermonDev (2074)

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