How to get my external IP address with node.js?

后端 未结 14 1515
情深已故
情深已故 2020-12-06 05:00

I\'m using node.js and I need to get my external IP address, provided by my ISP. Is there a way to achieve this without using a service like http://myexternalip.com/raw ?

14条回答
  •  隐瞒了意图╮
    2020-12-06 05:23

    node.js has a lot of great built in modules you can use without including any external dependencies. you can make this file.
    WhatsMyIpAddress.js

    const http = require('http');
    
    function WhatsMyIpAddress(callback) {
        const options = {
            host: 'ipv4bot.whatismyipaddress.com',
            port: 80,
            path: '/'
        };
        http.get(options, res => {
            res.setEncoding('utf8');
            res.on("data", chunk => callback(chunk, null));
        }).on('error', err => callback(null, err.message));
    }
    
    module.exports = WhatsMyIpAddress;
    

    Then call it in your main.js like this.

    main.js

    const WhatsMyIpAddress = require('./src/WhatsMyIpAddress');
    WhatsMyIpAddress((data,err) => {
       console.log('results:', data, err);
    });
    

提交回复
热议问题