Skip to content

Instantly share code, notes, and snippets.

@anishjoshi1999
Created January 15, 2024 02:22
Show Gist options
  • Save anishjoshi1999/7c39f336b680fde03411bc28ca35eef2 to your computer and use it in GitHub Desktop.
Save anishjoshi1999/7c39f336b680fde03411bc28ca35eef2 to your computer and use it in GitHub Desktop.
How to Find the IP Address of Your Computer Using Express.js
const http = require("http");
const trackVisitsMiddleware = async (req, res, next) => {
// Obtain the public IP address from api.ipify.org
const api = {
host: "api.ipify.org",
port: 80,
path: "/",
};
try {
const responseData = await fetchData(api);
const ipAddress = responseData.trim();
console.log(`Here is your IP Address: ${ipAddress}`)
} catch (error) {
console.error("Error fetching data:", error);
}
next();
};
const fetchData = async (api) => {
return new Promise((resolve, reject) => {
const req = http.get(api, (response) => {
let data = "";
response.on("data", (chunk) => {
data += chunk;
});
response.on("end", () => {
resolve(data);
});
});
req.on("error", (error) => {
reject(error);
});
req.end();
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment