Search code examples
javascriptnode.jshttpipnode-modules

How to return device IP address instead of 127.0.0.1 in http module in node js


So, I have a website that runs on NodeJS (I don't need to run it on node, but I only need some functionality that NodeJS modules provide) and I have a Discord webhook that sends a message in a channel every time the website turns on. And I have this:

const http = require("http");
const fs = require("fs");
const fetch = require("node-fetch")

const host = "localhost"
const port = 8080
var IP = "Unknown :face_with_raised_eyebrow:"

var params

const requestListener = function (req, res) {
    fs.readFile(__dirname + `${req.url}`, (err, contents) => {
        if (err) {
            contents = fs.readFileSync("index.html", "utf-8")
        }
        res.end(contents);
    })
};
const server = http.createServer(requestListener);
server.listen(port, host, () => {
    IP = server.address().address + ":" + server.address().port
    console.log(`Server is running on http://${host}:${port}`);

    params = {
        content:"تم رفع موقع توثيق غياب الطلاب",
        embeds:[{
            title:"IP Address: " + IP,
        }]
    }

    fetch('https://discord.com/api/webhooks/1156237937864876052/IJ_C3ShEsuHPGU4_21SuCI2b7hawC71nJgP7Hsj6ifk6zjUUAC7xktToF7OfZRzAPw6T', {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(params)
    }).then(async (res) => {
        //console.log(res)
    }) 

})

And, naturally and sensibly, it says 127.0.0.1 because as far as the script's concerned, WHATEVER device it's running on is gonna be 127.0.0.1 relative to it, but I want to change that, I want to make it show the device's actual IP since my school is gonna use this website.

Please help and, if you have any other recommendations for my code, don't forget to tell me!


Solution

  • To do so, you can fetch the IP from https://api.ipify.org, which returns the IP of whatever machine that tries to visit or fetch it.

    In short, you can use it to get the IP of whatever machine is running the script, here's a sample script to show you how:

    const fetch = require("node-fetch");
    
    fetch('https://api.ipify.org')
            .then(res => res.text())
            .then(body => body);
    

    First, you get the node-fetch nodejs module (which you can install by running npm i node-fetch), then you use it to fetch https://api.ipify.org. In the last two lines, we basically get the result that the API gave us.

    You can also do this in another way if you intend for your application to contain more client/server info later on by creating a class that contains a function called getServerIP() that does exactly that for us:

    class Server {
        constructor() {
            this.fetch = require("node-fetch")
        }
        async getServerIP() {
            var result = await this.fetch('https://api.ipify.org')
                .then(res => res.text())
                .then(body => body);
            return result
        }
    }
    
    module.exports = {
       Server
    }
    

    and you can use the function like this:

    const OnlineManager = require("./OnlineManager.js")
    const Server = new OnlineManager.Server()
    
    var IP = "Unknown"
    
    IP = await Server.getServerIP()
    

    You can also directly return the this.fetch() function in getServerIP().

    I hope this answer provided useful info