使用javascript获取本地机器的IP地址

时间:2016-12-09 06:30:09

标签: javascript websocket

当我使用Request.UserHostAddress使用Javascript获取我的机器的ipaddress时,我没有得到ip地址而不是我未定义的。

我的代码:

var ip = Request.UserHostAddress;
console.log(ip);

3 个答案:

答案 0 :(得分:2)

请尝试以下代码:



<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>

</head>
<body>
 Ip Address:=<h3 class='ipAdd'><h3>
  </body>

<script>
$(document).ready(function ubsrt()
{
  	window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;  
	var pc = new RTCPeerConnection({iceServers:[]}), 
	noop = function(){}; 
     
   	pc.createDataChannel("");  
	pc.createOffer(pc.setLocalDescription.bind(pc), noop);   
    	pc.onicecandidate = function(ice){ 
   	if(!ice || !ice.candidate || !ice.candidate.candidate)  return;

        	var myIP = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/.exec(ice.candidate.candidate)[1];

        	console.log('my IP: ', myIP); 
	$('.ipAdd').text(myIP);
  
        	pc.onicecandidate = noop;
  
	 }; 
});
      
</script>
</html>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你可以对hostip.info或类似的服务进行ajax调用......

Rhyme is [one, two, three, four, five]
The player list is [Player 1, Player 2, Player 3, Player 4, Player 5]
Player 1: one
Player 2: two
Player 3: three
Player 4: four
Player 5: five
Removing Player 5
The player list is [Player 1, Player 2, Player 3, Player 4]
Player 1: one
Player 2: two
Player 3: three
Player 4: four
Player 1: five
Removing Player 1
The player list is [Player 2, Player 3, Player 4]
Player 2: one
Player 3: two
Player 4: three
Player 2: four
Player 3: five
Removing Player 3
The player list is [Player 2, Player 4]
Player 2: one
Player 4: two
Player 2: three
Player 4: four
Player 2: five
Removing Player 2
The winner is Player 4

答案 2 :(得分:0)

以下是我的回答。我删除了jQuery的要求,在函数中封装了机制并使用了一些ES6特性。

<html>
<head><title>My IP Address</title></head>
<body><h3 class='ipAdd'>Ip Address : <h3></body>

<script> "use strict";
  window.RTCPeerConnection = window.RTCPeerConnection ||
                             window.mozRTCPeerConnection ||
                             window.webkitRTCPeerConnection;  

  function getMyIP (cb) {
    // Calls the cb function with the local host IP address found 
    // using RTC functions. We cannot just return the IP address 
    // because the RTC functions are asynchronous.

    var pc = new RTCPeerConnection ({iceServers: []}),
        noop = () => {};

    pc.onicecandidate = ice => 
      cb = cb ((ice = ice && ice.candidate && ice.candidate.candidate)
                   ? ice.match (/(\d{1,3}(\.\d{1,3}){3}|[a-f\d]{1,4}(:[a-f\d]{1,4}){7})/)[1]
                   : 'unavailable') || noop;
    pc.createDataChannel ("");  
    pc.createOffer (pc.setLocalDescription.bind (pc), noop);
  };

  getMyIP (addr => { document.querySelector ('.ipAdd').innerHTML += addr; });
</script>

</html>