source

Node.js에서 로컬 IP 주소를 가져옵니다.

nicesource 2022. 12. 4. 22:31
반응형

Node.js에서 로컬 IP 주소를 가져옵니다.

기계에서 간단한 Node.js 프로그램이 실행되고 있으며 프로그램이 실행되고 있는 PC의 로컬 IP 주소를 얻고 싶습니다.Node.js에서 입수하려면 어떻게 해야 하나요?

이 정보는 네트워크인터페이스명을 속성에 매핑하는 오브젝트(예를 들어, 1개의 인터페이스에 복수의 주소를 설정할 수 있도록)에서 확인할 수 있습니다.

'use strict';

const { networkInterfaces } = require('os');

const nets = networkInterfaces();
const results = Object.create(null); // Or just '{}', an empty object

for (const name of Object.keys(nets)) {
    for (const net of nets[name]) {
        // Skip over non-IPv4 and internal (i.e. 127.0.0.1) addresses
        // 'IPv4' is in Node <= 17, from 18 it's a number 4 or 6
        const familyV4Value = typeof net.family === 'string' ? 'IPv4' : 4
        if (net.family === familyV4Value && !net.internal) {
            if (!results[name]) {
                results[name] = [];
            }
            results[name].push(net.address);
        }
    }
}
// 'results'
{
  "en0": [
    "192.168.1.101"
  ],
  "eth0": [
    "10.0.0.101"
  ],
  "<network name>": [
    "<ip>",
    "<ip alias>",
    "<ip alias>",
    ...
  ]
}
// results["en0"][0]
"192.168.1.101"

결과를 해석하기 위해 프로그램을 실행하는 것은 약간 애매한 것 같습니다.이게 내가 쓰는 거야.

require('dns').lookup(require('os').hostname(), function (err, add, fam) {
  console.log('addr: ' + add);
})

그러면 첫 번째 네트워크인터페이스 로컬 IP 주소가 반환됩니다.

https://github.com/indutny/node-ip

var ip = require("ip");
console.dir ( ip.address() );

OS 모듈을 사용하여 찾을 수 있는 머신의 IP 주소는 Node.js에 고유합니다.

var os = require('os');

var networkInterfaces = os.networkInterfaces();

console.log(networkInterfaces);

os.network전화하기만 하면 됩니다.Interfaces()사용하면 리그별로 ifconfig를 실행하는 것보다 쉽게 관리할 수 있는 목록을 얻을 수 있습니다.

합니다.ip들면 다음과 같습니다.

npm install ip

다음으로 다음 코드를 사용합니다.

var ip = require("ip");
console.log(ip.address());

이것은, IPv4 주소를 찾고 있는 머신에 실제의 네트워크 인터페이스가 1개 밖에 없는 것을 전제로 하는 로컬 IP 주소를 취득하는 유틸리티 방법입니다.멀티 인터페이스 머신의 IP 주소 배열을 반환하기 위해 쉽게 리팩터링할 수 있습니다.

function getIPAddress() {
  var interfaces = require('os').networkInterfaces();
  for (var devName in interfaces) {
    var iface = interfaces[devName];

    for (var i = 0; i < iface.length; i++) {
      var alias = iface[i];
      if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal)
        return alias.address;
    }
  }
  return '0.0.0.0';
}

Node.Node.js의 합니다.Node.js는 Node.js를 사용합니다.ifconfig첫 합니다.「 」 ( 비비 ) 。

(Mac OS X v10.6(Snow Leopard)에서만 테스트되었습니다.Linux에서도 동작했으면 합니다.)

var getNetworkIP = (function () {
    var ignoreRE = /^(127\.0\.0\.1|::1|fe80(:1)?::1(%.*)?)$/i;

    var exec = require('child_process').exec;
    var cached;
    var command;
    var filterRE;

    switch (process.platform) {
        // TODO: implement for OSes without the ifconfig command
        case 'darwin':
             command = 'ifconfig';
             filterRE = /\binet\s+([^\s]+)/g;
             // filterRE = /\binet6\s+([^\s]+)/g; // IPv6
             break;
        default:
             command = 'ifconfig';
             filterRE = /\binet\b[^:]+:\s*([^\s]+)/g;
             // filterRE = /\binet6[^:]+:\s*([^\s]+)/g; // IPv6
             break;
    }

    return function (callback, bypassCache) {
        // Get cached value
        if (cached && !bypassCache) {
            callback(null, cached);
            return;
        }

        // System call
        exec(command, function (error, stdout, sterr) {
            var ips = [];
            // Extract IP addresses
            var matches = stdout.match(filterRE);

            // JavaScript doesn't have any lookbehind regular expressions, so we need a trick
            for (var i = 0; i < matches.length; i++) {
                ips.push(matches[i].replace(filterRE, '$1'));
            }

            // Filter BS
            for (var i = 0, l = ips.length; i < l; i++) {
                if (!ignoreRE.test(ips[i])) {
                    //if (!error) {
                        cached = ips[i];
                    //}
                    callback(error, ips[i]);
                    return;
                }
            }
            // Nothing found
            callback(error, null);
        });
    };
})();

사용 예:

getNetworkIP(function (error, ip) {
    console.log(ip);
    if (error) {
        console.log('error:', error);
    }
}, false);

가 " " " 인 true이 함수는 매번 시스템콜을 실행합니다.이치노


갱신된 버전

모든 로컬 네트워크 주소의 배열을 반환합니다.

Ubuntu 11.04(Naty Narwhal) 및 Windows XP 32에서 테스트 완료.

var getNetworkIPs = (function () {
    var ignoreRE = /^(127\.0\.0\.1|::1|fe80(:1)?::1(%.*)?)$/i;

    var exec = require('child_process').exec;
    var cached;
    var command;
    var filterRE;

    switch (process.platform) {
        case 'win32':
        //case 'win64': // TODO: test
            command = 'ipconfig';
            filterRE = /\bIPv[46][^:\r\n]+:\s*([^\s]+)/g;
            break;
        case 'darwin':
            command = 'ifconfig';
            filterRE = /\binet\s+([^\s]+)/g;
            // filterRE = /\binet6\s+([^\s]+)/g; // IPv6
            break;
        default:
            command = 'ifconfig';
            filterRE = /\binet\b[^:]+:\s*([^\s]+)/g;
            // filterRE = /\binet6[^:]+:\s*([^\s]+)/g; // IPv6
            break;
    }

    return function (callback, bypassCache) {
        if (cached && !bypassCache) {
            callback(null, cached);
            return;
        }

        // System call
        exec(command, function (error, stdout, sterr) {
            cached = [];
            var ip;
            var matches = stdout.match(filterRE) || [];
            //if (!error) {
            for (var i = 0; i < matches.length; i++) {
                ip = matches[i].replace(filterRE, '$1')
                if (!ignoreRE.test(ip)) {
                    cached.push(ip);
                }
            }
            //}
            callback(error, cached);
        });
    };
})();

업데이트된 버전의 사용 예

getNetworkIPs(function (error, ip) {
console.log(ip);
if (error) {
    console.log('error:', error);
}
}, false);

npm 모듈을 사용합니다.

var ip = require('ip');

console.log(ip.address());

> '192.168.0.117'

ifconfig를 호출하는 것은 플랫폼에 매우 의존하며 네트워킹레이어는 소켓의 IP 주소를 인식하기 때문에 문의하는 것이 가장 좋습니다.

Node.js는 이 작업을 수행하는 직접적인 방법을 공개하지 않지만 임의의 소켓을 열고 사용 중인 로컬 IP 주소를 확인할 수 있습니다.예를 들어 www.google.com에 소켓을 여는 경우:

var net = require('net');
function getNetworkIP(callback) {
  var socket = net.createConnection(80, 'www.google.com');
  socket.on('connect', function() {
    callback(undefined, socket.address().address);
    socket.end();
  });
  socket.on('error', function(e) {
    callback(e, 'error');
  });
}

사용 예:

getNetworkIP(function (error, ip) {
    console.log(ip);
    if (error) {
        console.log('error:', error);
    }
});

로컬 IP 주소는 항상 127.0.0.1 입니다.

으로 네트워크 주소가 , 이 주소는 주소에서 수 .이 주소는ifconfig (*nix) 。ipconfigwin). 이것은 로컬네트워크 내에서만 유효합니다.

다음으로 외부/퍼블릭 IP 주소가 있습니다.이 주소는, 어떻게든 라우터에 요구할 수 있는 경우에만 취득할 수 있습니다.또, 외부 서비스가 요구를 수신했을 때에 클라이언트 IP 주소를 반환하는 외부 서비스를 설정할 수도 있습니다.whatismyip.com과 같은 다른 서비스도 존재합니다.

경우에 따라서는(WAN 접속이 있는 경우 등), 네트워크 IP 주소와 퍼블릭 IP가 같으며, 양쪽 모두를 사용해 컴퓨터에 외부에서 액세스 할 수 있습니다.

네트워크 주소와 퍼블릭 IP 주소가 다른 경우는, 네트워크 라우터에 모든 착신 접속을 네트워크 IP 주소로 전송 할 필요가 있습니다.


업데이트 2013:

이제 새로운 방법이 생겼다.에 접속하다라는 할 수 .localAddress 예 , ) 。net.socket.localAddress이치

가장 쉬운 방법은 랜덤 포트를 열고 수신한 후 주소를 가져와 소켓을 닫는 것입니다.


업데이트 2015:

이전 것은 더 이상 작동하지 않습니다.

Underscore.jsLodash에 대한 올바른 한 줄 문구는 다음과 같습니다.

var ip = require('underscore')
    .chain(require('os').networkInterfaces())
    .values()
    .flatten()
    .find({family: 'IPv4', internal: false})
    .value()
    .address;

다음은 의존관계가 없는 가장 깔끔하고 심플한 답변으로 모든 플랫폼에서 사용할 수 있는 방법입니다.

const { lookup } = require('dns').promises;
const { hostname } = require('os');

async function getMyIPAddress(options) {
  return (await lookup(hostname(), options))
    .address;
}

있는 은, 「IP」로 입니다.192.168. 이는 다음과 같은 줍니다.

function getLocalIp() {
    const os = require('os');

    for(let addresses of Object.values(os.networkInterfaces())) {
        for(let add of addresses) {
            if(add.address.startsWith('192.168.')) {
                return add.address;
            }
        }
    }
}

물론 다른 번호를 찾으시면 번호만 바꾸셔도 됩니다.

Node.js만 사용하여 이 작업을 수행할 수 있었습니다.

Node.js로서:

var os = require( 'os' );
var networkInterfaces = Object.values(os.networkInterfaces())
    .reduce((r,a) => {
        r = r.concat(a)
        return r;
    }, [])
    .filter(({family, address}) => {
        return family.toLowerCase().indexOf('v4') >= 0 &&
            address !== '127.0.0.1'
    })
    .map(({address}) => address);
var ipAddresses = networkInterfaces.join(', ')
console.log(ipAddresses);

Bash 스크립트(Node.js 설치 필요)

function ifconfig2 ()
{
    node -e """
        var os = require( 'os' );
        var networkInterfaces = Object.values(os.networkInterfaces())
            .reduce((r,a)=>{
                r = r.concat(a)
                return r;
            }, [])
            .filter(({family, address}) => {
                return family.toLowerCase().indexOf('v4') >= 0 &&
                    address !== '127.0.0.1'
            })
            .map(({address}) => address);
        var ipAddresses = networkInterfaces.join(', ')
        console.log(ipAddresses);
    """
}

다음은 단일 IP 주소를 얻기 위한 vanilla JavaScript의 간략화된 버전입니다.

function getServerIp() {

  var os = require('os');
  var ifaces = os.networkInterfaces();
  var values = Object.keys(ifaces).map(function(name) {
    return ifaces[name];
  });
  values = [].concat.apply([], values).filter(function(val){
    return val.family == 'IPv4' && val.internal == false;
  });

  return values.length ? values[0].address : '0.0.0.0';
}

디폴트 게이트웨이가 포함되어 있는 네트워크인터페이스를 보고 로컬 IP 주소를 결정하는 Node.js 모듈을 작성했습니다.

은, 보다 할 수 입니다.os.networkInterfaces()「DNS」입니다.VMware "VPN" "VPN" "Windows, Linux, Mac OS "FreeB"SD ★★★★★★★★★★★★★★★★★★★★★에서는, under under 、 것 under 、 것 under 、 under under under under 。route.exe ★★★★★★★★★★★★★★★★★」netstat출력을 해석합니다.

var localIpV4Address = require("local-ipv4-address");

localIpV4Address().then(function(ipAddress){
    console.log("My IP address is " + ipAddress);
    // My IP address is 10.4.4.137 
});

Linux 및 macOS에서 사용하는 경우 동기식으로 IP 주소를 가져오려면 다음을 수행하십시오.

var ips = require('child_process').execSync("ifconfig | grep inet | grep -v inet6 | awk '{gsub(/addr:/,\"\");print $2}'").toString().trim().split("\n");
console.log(ips);

결과는 다음과 같습니다.

['192.168.3.2', '192.168.2.1']

간결성에 관심이 있는 분들을 위해 표준 Node.js 설치의 일부가 아닌 플러그인/의존관계가 필요하지 않은 몇 가지 '한 줄'을 소개합니다.

어레이로서 eth0 의 퍼블릭 IPv4 및 IPv6 주소:

var ips = require('os').networkInterfaces().eth0.map(function(interface) {
    return interface.address;
});

문자열로서의 eth0(통상은 IPv4)의 첫 번째 퍼블릭 IP 주소:

var ip = require('os').networkInterfaces().eth0[0].address;

macOS의 첫 번째 로컬호스트 주소용 라이너 1개만

macOS에서 애플리케이션을 개발할 때 전화로 테스트하고 싶을 때 로컬 호스트 IP 주소를 자동으로 선택하는 앱이 필요합니다.

require('os').networkInterfaces().en0.find(elm => elm.family=='IPv4').address

이것은, IP 주소를 자동적으로 검출하는 방법에 대해 설명하기 위해서입니다.이를 테스트하려면 터미널 히트로 이동합니다.

node
os.networkInterfaces().en0.find(elm => elm.family=='IPv4').address

출력은 로컬호스트의 IP 주소가 됩니다.

이 질문에는 늦었을지도 모르지만, IP 주소의 배열을 취득하기 위해서 1개의 라이너 ES6 솔루션을 필요로 하는 경우는, 다음과 같이 도움이 됩니다.

Object.values(require("os").networkInterfaces())
    .flat()
    .filter(({ family, internal }) => family === "IPv4" && !internal)
    .map(({ address }) => address)

~하듯이

Object.values(require("os").networkInterfaces())

어레이 배열을 반환하기 때문에flat()단일 배열로 평평하게 만드는 데 사용됩니다.

.filter(({ family, internal }) => family === "IPv4" && !internal)

내부가 아닌 경우 IPv4 주소만 포함하도록 어레이를 필터링합니다.

마침내.

.map(({ address }) => address)

필터링된 어레이의 IPv4 주소만 반환합니다.

그래서 결과는 다음과 같다.[ '192.168.xx.xx' ]

그런 다음 필터 조건을 변경하거나 원하는 경우 해당 배열의 첫 번째 인덱스를 가져올 수 있습니다.

OS사용하고 있는 것은 Windows 입니다.

다음과 같은 솔루션이 효과적입니다.

const ip = Object.values(require("os").networkInterfaces())
        .flat()
        .filter((item) => !item.internal && item.family === "IPv4")
        .find(Boolean).address;

Google은 "Node.js get server IP"를 검색하면서 이 질문을 하도록 지시했습니다.그러므로 Node.js 서버 프로그램에서 이를 달성하려는 사용자를 위해 대체 답변을 드리겠습니다(원래 포스터의 경우일 수 있습니다).

서버가 1개의 IP 주소에만 바인드 되어 있는 경우는, IP 주소를 바인드 한 주소를 이미 알고 있기 때문에, IP 주소를 결정할 필요는 없습니다(예를 들면, 2번째 파라미터가 에 건네진 경우 등).listen()기능).

서버가 복수의 IP 주소에 바인드 되어 있는 경우는, 클라이언트가 접속한 인터페이스의 IP 주소를 확인할 필요가 있습니다.그리고 Tor Valamo가 간단히 제안했듯이, 오늘날 우리는 이 정보를 연결된 소켓과 그 소켓에서 쉽게 얻을 수 있습니다.localAddress소유물.

예를 들어 프로그램이 웹 서버인 경우:

var http = require("http")

http.createServer(function (req, res) {
    console.log(req.socket.localAddress)
    res.end(req.socket.localAddress)
}).listen(8000)

범용 TCP 서버인 경우:

var net = require("net")

net.createServer(function (socket) {
    console.log(socket.localAddress)
    socket.end(socket.localAddress)
}).listen(8000)

서버 프로그램을 실행할 때 이 솔루션은 매우 높은 휴대성, 정확성 및 효율성을 제공합니다.

상세한 것에 대하여는, 다음을 참조해 주세요.

코멘트에 근거해, 현재 버전의 Node.js 로 동작하고 있는 것은 다음과 같습니다.

var os = require('os');
var _ = require('lodash');

var ip = _.chain(os.networkInterfaces())
  .values()
  .flatten()
  .filter(function(val) {
    return (val.family == 'IPv4' && val.internal == false)
  })
  .pluck('address')
  .first()
  .value();

위의 답변 중 하나에 대한 코멘트는 다음 연락처에 대한 문의가 누락되었습니다.values()os.networkInterfaces()이치

다음은 이전 예제의 변형입니다.VMware 인터페이스 등을 필터링 할 때는 주의가 필요합니다.인덱스를 통과하지 못하면 모든 주소가 반환됩니다.그렇지 않으면 기본값을 0으로 설정한 다음 null을 전달하여 모두 가져오기를 원할 수 있지만, 이 문제는 해결됩니다.추가할 의향이 있는 경우 regex 필터에 대한 다른 인수를 전달할 수도 있습니다.

function getAddress(idx) {

    var addresses = [],
        interfaces = os.networkInterfaces(),
        name, ifaces, iface;

    for (name in interfaces) {
        if(interfaces.hasOwnProperty(name)){
            ifaces = interfaces[name];
            if(!/(loopback|vmware|internal)/gi.test(name)){
                for (var i = 0; i < ifaces.length; i++) {
                    iface = ifaces[i];
                    if (iface.family === 'IPv4' &&  !iface.internal && iface.address !== '127.0.0.1') {
                        addresses.push(iface.address);
                    }
                }
            }
        }
    }

    // If an index is passed only return it.
    if(idx >= 0)
        return addresses[idx];
    return addresses;
}

간결함을 중시하는 고객은 Lodash를 사용하고 있습니다.

var os = require('os');
var _ = require('lodash');
var firstLocalIp = _(os.networkInterfaces()).values().flatten().where({ family: 'IPv4', internal: false }).pluck('address').first();

console.log('First local IPv4 address is ' + firstLocalIp);

var ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress 

다음은 휴대용 방식으로 IPv4 및 IPv6 주소를 모두 가져올 수 있는 변형입니다.

/**
 * Collects information about the local IPv4/IPv6 addresses of
 * every network interface on the local computer.
 * Returns an object with the network interface name as the first-level key and
 * "IPv4" or "IPv6" as the second-level key.
 * For example you can use getLocalIPs().eth0.IPv6 to get the IPv6 address
 * (as string) of eth0
 */
getLocalIPs = function () {
    var addrInfo, ifaceDetails, _len;
    var localIPInfo = {};
    //Get the network interfaces
    var networkInterfaces = require('os').networkInterfaces();
    //Iterate over the network interfaces
    for (var ifaceName in networkInterfaces) {
        ifaceDetails = networkInterfaces[ifaceName];
        //Iterate over all interface details
        for (var _i = 0, _len = ifaceDetails.length; _i < _len; _i++) {
            addrInfo = ifaceDetails[_i];
            if (addrInfo.family === 'IPv4') {
                //Extract the IPv4 address
                if (!localIPInfo[ifaceName]) {
                    localIPInfo[ifaceName] = {};
                }
                localIPInfo[ifaceName].IPv4 = addrInfo.address;
            } else if (addrInfo.family === 'IPv6') {
                //Extract the IPv6 address
                if (!localIPInfo[ifaceName]) {
                    localIPInfo[ifaceName] = {};
                }
                localIPInfo[ifaceName].IPv6 = addrInfo.address;
            }
        }
    }
    return localIPInfo;
};

다음은 같은 기능의 CoffeeScript 버전입니다.

getLocalIPs = () =>
    ###
    Collects information about the local IPv4/IPv6 addresses of
      every network interface on the local computer.
    Returns an object with the network interface name as the first-level key and
      "IPv4" or "IPv6" as the second-level key.
    For example you can use getLocalIPs().eth0.IPv6 to get the IPv6 address
      (as string) of eth0
    ###
    networkInterfaces = require('os').networkInterfaces();
    localIPInfo = {}
    for ifaceName, ifaceDetails of networkInterfaces
        for addrInfo in ifaceDetails
            if addrInfo.family=='IPv4'
                if !localIPInfo[ifaceName]
                    localIPInfo[ifaceName] = {}
                localIPInfo[ifaceName].IPv4 = addrInfo.address
            else if addrInfo.family=='IPv6'
                if !localIPInfo[ifaceName]
                    localIPInfo[ifaceName] = {}
                localIPInfo[ifaceName].IPv6 = addrInfo.address
    return localIPInfo

의 예console.log(getLocalIPs())

{ lo: { IPv4: '127.0.0.1', IPv6: '::1' },
  wlan0: { IPv4: '192.168.178.21', IPv6: 'fe80::aa1a:2eee:feba:1c39' },
  tap0: { IPv4: '10.1.1.7', IPv6: 'fe80::ddf1:a9a1:1242:bc9b' } }

다른 답변과 비슷하지만 보다 간결하게:

'use strict';

const interfaces = require('os').networkInterfaces();

const addresses = Object.keys(interfaces)
  .reduce((results, name) => results.concat(interfaces[name]), [])
  .filter((iface) => iface.family === 'IPv4' && !iface.internal)
  .map((iface) => iface.address);

의 내부 인터페이스와 수 (예: " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " "10.0.75.1,172.100.0.1,192.168.2.3 것은 ( )172.100.0.1를 참조해 주세요.

만약 다른 누군가가 비슷한 문제를 가지고 있다면, 여기 이 문제에 대한 또 다른 견해가 있습니다. 도움이 되길 바랍니다.

const address = Object.keys(os.networkInterfaces())
    // flatten interfaces to an array
    .reduce((a, key) => [
        ...a,
        ...os.networkInterfaces()[key]
    ], [])
    // non-internal ipv4 addresses only
    .filter(iface => iface.family === 'IPv4' && !iface.internal)
    // project ipv4 address as a 32-bit number (n)
    .map(iface => ({...iface, n: (d => ((((((+d[0])*256)+(+d[1]))*256)+(+d[2]))*256)+(+d[3]))(iface.address.split('.'))}))
    // set a hi-bit on (n) for reserved addresses so they will sort to the bottom
    .map(iface => iface.address.startsWith('10.') || iface.address.startsWith('192.') ? {...iface, n: Math.pow(2,32) + iface.n} : iface)
    // sort ascending on (n)
    .sort((a, b) => a.n - b.n)
    [0]||{}.address;

용도:

var os = require('os');
var networkInterfaces = os.networkInterfaces();
var arr = networkInterfaces['Local Area Connection 3']
var ip = arr[1].address;

언급URL : https://stackoverflow.com/questions/3653065/get-local-ip-address-in-node-js

반응형