Home
PHP
Tech Tube
MySQL
Linux
CSS&HTML
JavaScript

Get the IP address in the local network

The following script allows you to get the internal IP from the local network of the user. If you need it for some reason... Your IP address in the local network should be:
<script>
    function report_local_address() {
	// NOTE: window.RTCPeerConnection is "not a constructor" in FF22/23
	var RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection;

	if (RTCPeerConnection) (function () {
	    var rtc = new RTCPeerConnection({iceServers:[]});
	    if (1 || window.mozRTCPeerConnection) {      // FF [and now Chrome!] needs a channel/stream to proceed
		rtc.createDataChannel('', {reliable:false});
	    };
	    
	    rtc.onicecandidate = function (evt) {
		// convert the candidate to SDP so we can run it through our general parser
		// see<a href=" https://twitter.com/lancestout/status/525796175425720320" target="_blank"> https://twitter.com/lancestout/status/525796175425720320</a>  for details
		if (evt.candidate) grepSDP("a="+evt.candidate.candidate);
	    };
	    rtc.createOffer(function (offerDesc) {
		grepSDP(offerDesc.sdp);
		rtc.setLocalDescription(offerDesc);
	    }, function (e) { console.warn("offer failed", e); });
	    
	    
	    var addrs = Object.create(null);
	    addrs["0.0.0.0"] = false;
	    function updateDisplay(newAddr) {
		if (newAddr in addrs) return;
		else addrs[newAddr] = true;
		var displayAddrs = Object.keys(addrs).filter(function (k) { return addrs[k]; });
		var ipsting = displayAddrs.join(" - ") || "nope";
		document.body.innerHTML = document.body.innerHTML + ipsting;
	    }
	    
	    function grepSDP(sdp) {
		var hosts = [];
		sdp.split('\r\n').forEach(function (line) { // c.f.<a href=" http://tools.ietf.org/html/rfc4566#page-39" target="_blank"> http://tools.ietf.org/html/rfc4566#page-39</a> 
		    if (~line.indexOf("a=candidate")) {     //<a href=" http://tools.ietf.org/html/rfc4566#section-5.13" target="_blank"> http://tools.ietf.org/html/rfc4566#section-5.13</a> 
			var parts = line.split(' '),        //<a href=" http://tools.ietf.org/html/rfc5245#section-15.1" target="_blank"> http://tools.ietf.org/html/rfc5245#section-15.1</a> 
			    addr = parts[4],
			    type = parts[7];
			if (type === 'host') updateDisplay(addr);
		    } else if (~line.indexOf("c=")) {       //<a href=" http://tools.ietf.org/html/rfc4566#section-5.7" target="_blank"> http://tools.ietf.org/html/rfc4566#section-5.7</a> 
			var parts = line.split(' '),
			    addr = parts[2];
			updateDisplay(addr);
		    }
		});
	    }
	})();
    
    }
    
    var readyStateCheckInterval = setInterval(function() {
	if (document.readyState === "complete") {
	    clearInterval(readyStateCheckInterval);
	    report_local_address();
	}
    }, 10);
    </script>