annyoung

[javascript] get ip only using javascript 본문

프로그래밍

[javascript] get ip only using javascript

nopsled 2018. 4. 19. 18:06

Client

>> 내부 아이피


/**

 * Get the user IP throught the webkitRTCPeerConnection

 * @param onNewIP {Function} listener function to expose the IP locally

 * @return undefined

 */

function getUserIP(onNewIP) { //  onNewIp - your listener function for new IPs

    //compatibility for firefox and chrome

    var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;

    var pc = new myPeerConnection({

        iceServers: []

    }),

    noop = function() {},

    localIPs = {},

    ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,

    key;


    function iterateIP(ip) {

        if (!localIPs[ip]) onNewIP(ip);

        localIPs[ip] = true;

    }


     //create a bogus data channel

    pc.createDataChannel("");


    // create offer and set local description

    pc.createOffer().then(function(sdp) {

        sdp.sdp.split('\n').forEach(function(line) {

            if (line.indexOf('candidate') < 0) return;

            line.match(ipRegex).forEach(iterateIP);

        });

        

        pc.setLocalDescription(sdp, noop, noop);

    }).catch(function(reason) {

        // An error occurred, so handle the failure to connect

    });


    //listen for candidate events

    pc.onicecandidate = function(ice) {

        if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;

        ice.candidate.candidate.match(ipRegex).forEach(iterateIP);

    };

}


// Usage


getUserIP(function(ip){

    alert("Got IP! :" + ip);

});


>> 외부 아이피

 $.getJSON('http://ipinfo.io', function(data){

console.log(data);

});


얘들도 답이 없는지 외부 사이트로 xhr 쏜다... jQuery 싫으면 axios로 쏴도된다.

출처 : https://ourcodeworld.com/articles/read/257/how-to-get-the-client-ip-address-with-javascript-only




Server

Routes.route('/testAPI').get(async (req, res) => {

const ip = req.connection.remoteAddress.split(':')[req.connection.remoteAddress.split(':').length-1]

}); 

request 헤더 중에 connection.remoteAddress이 있다. ipv6까지 표시해주는거 같은데 필요없으니까 잘라 주려고 split하고 가져온다.



var ip = req.header('x-forwarded-for') || req.connection.remoteAddress;

아니면 그냥 이거 써도 된다.

'프로그래밍' 카테고리의 다른 글

python pyodbc 설치 탐험기  (0) 2018.06.04
[javascript] calculate datetime  (0) 2018.04.24
python ctypes GetFileVersion  (0) 2016.11.09
python 윈도우 한글문제  (0) 2016.04.26
python unicode unescape (html unescape)  (0) 2015.11.07
Comments