2017-04-26 138 views
0

我正在尋找一個簡單的函數(儘可能簡單)來返回公共ip地址。 我遇到了這個功能:在javascript中獲取公共ip地址

const clientsIpAdress = (onNewIP) => { 
    const MyPeerConnection = 
    window.RTCPeerConnection || 
    window.mozRTCPeerConnection || 
    window.webkitRTCPeerConnection; 
    const pc = new MyPeerConnection({ 
    iceServers: [] 
    }); 
    const noop =() => {}; 
    const localIPs = {}; 
    const ipRegex = 
    /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g; 

    const iterateIP = (ip) => { 
    if (!localIPs[ip]) onNewIP(ip); 
    localIPs[ip] = true; 
    }; 
    pc.createDataChannel(''); 
    pc.createOffer().then((sdp) => { 
    sdp.sdp.split('\n').forEach((line) => { 
     if (line.indexOf('candidate') < 0) return; 
     line.match(ipRegex).forEach(iterateIP); 
    }); 

    pc.setLocalDescription(sdp, noop, noop); 
    }); 
    pc.onicecandidate = (ice) => { 
    if (!ice || !ice.candidate || 
     !ice.candidate.candidate || 
     !ice.candidate.candidate.match(ipRegex)) return; 
    ice.candidate.candidate.match(ipRegex).forEach(iterateIP); 
    }; 
}; 
export default clientsIpAddress; 

,但它返回的本地ip地址。有任何想法嗎?

+0

您將需要使用其他來源來確定地址。本地機器通常不知道公共地址。 – Stese

+0

好的,謝謝!我是JavaScript新手,我必須完成此任務。你能給我一個指導方針嗎? – user7334203

+0

你可能想要執行一個HTTP請求到ipify:https://api.ipify.org/ – briosheje

回答

1

$(document).ready(function() { 
 
    $.getJSON("http://jsonip.com/?callback=?", function (data) { 
 
     console.log(data); 
 
     alert(data.ip); 
 
    }); 
 
});
<html> 
 
<head> 
 
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script> 
 
</head> 
 
</html>

+0

對不起,我犯了一個錯誤。我想公開的IP不是本地的。我在我的描述中寫了這個,但沒有在標題:P – user7334203

+0

哦,我明白了,等一下我要編輯我的答案。 –

+0

您可以批准它對您有用! @ user7334203 –