Understanding Internal IP and Its APIs
The “internal-ip” library is an essential tool that lets developers fetch the internal (local) IP address of the current machine. This can be useful in a variety of development projects that require internal network addressing. Below, we provide a comprehensive guide to its usages and include several APIs with code snippets.
Installation
To get started, you need to install the “internal-ip” library:
npm install internal-ip
API Methods
Getting the Internal IPv4 Address
This is the most common use case of the “internal-ip” library. Here’s how to get the internal IPv4 address:
const internalIp = require('internal-ip');
(async () => {
console.log(await internalIp.v4());
// Example output: 192.168.1.100
})();
Getting the Internal IPv6 Address
Similarly, you can obtain the internal IPv6 address. Below is the relevant code:
const internalIp = require('internal-ip');
(async () => {
console.log(await internalIp.v6());
// Example output: fe80::1c2a:7fa5:2fa4:e5a5
})();
Synchronous Methods
If you prefer synchronous methods, the “internal-ip” library provides those as well:
const internalIp = require('internal-ip');
console.log(internalIp.v4.sync());
// Example output: 192.168.1.100
console.log(internalIp.v6.sync());
// Example output: fe80::1c2a:7fa5:2fa4:e5a5
Example Application Using Internal IP APIs
Let’s create a simple Node.js application that outputs the internal IP address:
const http = require('http');
const internalIp = require('internal-ip');
(async () => {
const ip = await internalIp.v4();
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(`Your internal IP address is ${ip}`);
});
server.listen(3000, '127.0.0.1', () => {
console.log('Server is running at http://127.0.0.1:3000/');
});
})();
Conclusion
The “internal-ip” library is a handy tool for developers dealing with local network configurations or developing applications that interact within local networks. We hope the API explanations and examples provided are useful for you to integrate internal IP functionalities into your applications effectively.
Hash: e7d07e42b6d89ca56f8fa66f17527a3a5e011effa454d81e471bf76d3dc45a0b