PHP How to Get Local Ip of System

How do I get the local IP address of the server using PHP?

The problem that you have here is that this is not a static piece of information. Any given computer can have multiple IP addresses associated with multiple network cards. Some/all/none of those may have the web service available on them. There may not be a single answer to the question you are asking of the OS.

If your server has a simple, single IP address configuration then you would probably be best to hard-code this - it is by far and away the simplest option. If you want to determine it dynamically, here are a few bits of information which you will hopefully find useful:

  • $_SERVER['HTTP_HOST'] contains the address that was typed into the address bar of the browser in order to access the page. If you access the page by typing (for example) http://192.168.0.1/index.php into the browser, $_SERVER['HTTP_HOST'] will be 192.168.0.1.
  • If you used a DNS name to access the page, gethostbyname($_SERVER['HTTP_HOST']); will turn that DNS name into an IP address.
  • $_SERVER['SERVER_NAME'] contains the name that has been configured in the web server configuration as it's server name. If you going to use this, you might as well just hard code it in PHP.
  • $_SERVER['SERVER_ADDR'] will contain the operating system of the server's primary IP address. This may or may not be the IP address that was used to access the page, and it may or may not be an IP address with the web server bound to it. It depends heavily on OS and server configuration. if the server has a single IP address, this is probably a safe bet, although there are situations where this may contain 127.0.0.1.

The long of the short of it is that there is no 100% reliable way to determine a guaranteed working IP address of the web server, without examining information that was send to the web server in order to generate the page you are creating, which as you say totally defeats its purpose.

Get the client IP address using PHP

The simplest way to get the visitor’s/client’s IP address is using the $_SERVER['REMOTE_ADDR'] or $_SERVER['REMOTE_HOST'] variables.

However, sometimes this does not return the correct IP address of the visitor, so we can use some other server variables to get the IP address.

The below both functions are equivalent with the difference only in how and from where the values are retrieved.

getenv() is used to get the value of an environment variable in PHP.

// Function to get the client IP address
function get_client_ip() {
$ipaddress = '';
if (getenv('HTTP_CLIENT_IP'))
$ipaddress = getenv('HTTP_CLIENT_IP');
else if(getenv('HTTP_X_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
else if(getenv('HTTP_X_FORWARDED'))
$ipaddress = getenv('HTTP_X_FORWARDED');
else if(getenv('HTTP_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_FORWARDED_FOR');
else if(getenv('HTTP_FORWARDED'))
$ipaddress = getenv('HTTP_FORWARDED');
else if(getenv('REMOTE_ADDR'))
$ipaddress = getenv('REMOTE_ADDR');
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}

$_SERVER is an array that contains server variables created by the web server.

// Function to get the client IP address
function get_client_ip() {
$ipaddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP']))
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_X_FORWARDED']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_FORWARDED']))
$ipaddress = $_SERVER['HTTP_FORWARDED'];
else if(isset($_SERVER['REMOTE_ADDR']))
$ipaddress = $_SERVER['REMOTE_ADDR'];
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}

Unable to get LOCAL IP address of a machine from a site which is hosted on GODADDY

Generally you will not be able to retrieve the local ip address of any computer that resides behind a NAT router / firewall and especially not with PHP which runs at the server anyway so the code above would find the ip of the server.

However you can use Javascript and a feature found in webRTC to reveal the local IP address of a visitor to your portal. The result of which can be passed to PHP using Ajax if required. I discovered this a few weeks ago whilst investigating a connectivity issue - a site I visited was showing my public & local ip addresses. After looking at the source code and doing further research I put the following little function together - perhaps it may be of use.

<?php

?>
<!doctype html>
<html>
<head>
<meta charset='utf-8' />
<title>Get Local IP address</title>
<script>
const rtcpip=function( server, callback ){
/*
https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/createDataChannel
https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/createOffer
*/
let debug=true;

let oList={
google1:'stun1.l.google.com:19302',
google2:'stun2.l.google.com:19302',
google3:'stun3.l.google.com:19302',
google4:'stun4.l.google.com:19302',
kundenserver:'stun.kundenserver.de:3478',
mozilla:'stun.services.mozilla.com:3478',
notts:'stun.nottingham.ac.uk:3478'
};
const getserver=function(){
return oList.hasOwnProperty( server ) ? oList[ server ] : oList.mozilla;
};

let duplicates={};
let stunsvr=getserver();
let RTCPeerConnection=window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
let oConstraints={ optional: [ { RtpDataChannels: true } ] };
let oServers = { iceServers: [ { urls: 'stun:' + stunsvr } ] };

const info=function(m){
if( arguments.length==1 && debug )console.info(m);
if( arguments.length==2 && debug )console.info(m,arguments[1]);
};
const candidatehandler=function( candidate ){
info( candidate );
let regex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/
let addr = regex.exec( candidate )[1];
if( duplicates[ addr ] === undefined ) callback( addr );
duplicates[ addr ] = true;
};
const icelistener=function( oIce ){
if( oIce.candidate ) candidatehandler.call( this, oIce.candidate.candidate );
};
const icedclistener=function(e){
let oChan=e.channel;
oChan.addEventListener( 'open', function( evt ){ info( evt ) }, false );
oChan.addEventListener( 'message', function( evt ){ info( evt.data ) }, false );
oChan.addEventListener( 'close', function( evt ){ info( evt ) }, false );
};
const icecslistener=function(e){
info( 'connectionstatechange: %o',e );
};
const icenegotiate=function( e ){
info( 'icenegotiate: %o',e );
};
const icesignalchange=function(e){
info( 'icesignalchange: %o',e );
};
const icetrack=function(e){
info( 'icetrack: %o',e );
}

info( 'STUN Server: %s', stunsvr );

let rtcp=new RTCPeerConnection( oServers, oConstraints );

rtcp.addEventListener( 'icecandidate', icelistener, false );
rtcp.addEventListener( 'datachannel', icedclistener, false );
rtcp.addEventListener( 'iceconnectionstatechange', icecslistener, false );
rtcp.addEventListener( 'negotiationneeded', icenegotiate, false );
rtcp.addEventListener( 'signalingstatechange', icesignalchange, false );
rtcp.addEventListener( 'track', icetrack, false );
rtcp.createDataChannel( 'rtcpip' );

rtcp.createOffer().then( function( offer ){
return rtcp.setLocalDescription( offer )
} ).then( function(){
let lines = rtcp.localDescription.sdp.split( String.fromCharCode( 10 ) );
lines.forEach( function( line ){
if( ~line.indexOf( 'a=candidate:' ) ) candidatehandler.call( this, line );
});
});
};

const create=function(t, a, p){
try{
var el = ( typeof( t )=='undefined' || t==null ) ? document.createElement( 'div' ) : document.createElement( t );
for( var x in a ) if( a.hasOwnProperty( x ) && x!=='innerHTML' ) el.setAttribute( x, a[ x ] );
if( a.hasOwnProperty('innerHTML') ) el.innerHTML=a.innerHTML;
if( p!=null ) typeof( p )=='object' ? p.appendChild( el ) : document.getElementById( p ).appendChild( el );
return el;
}catch( err ){
console.warn( err.message );
}
};

const ipcallback=function( ip ){
try{
let type=false;

let ipv4=ip.split('.');
let ipv6=ip.split(':');

if( ipv4.length==4 ){
let local=( ipv4[0] == 10 || ( ipv4[0]==172 && ( ipv4[1]>=16 &&ipv4[1]<=31 ) ) || ( ipv4[0]==192 && ipv4[1]==168 ) );
create( null,{ innerHTML:ip + ( local ? ' - Private' : ' - Public' ) }, document.getElementById( 'ip' ) );
}

if( ipv6.length > 1 ){
switch( ipv6[0] ){
case 'FE80':type='Link-Local';break;
case 'FEC0':type='site-local';break;
case '3FFE':type='global';break;
case '2002':type='global 6to4';break;
default:type='IPV6';break;
}
create( null,{ innerHTML:ip + ' ' + type }, document.getElementById( 'ip' ) );
/*
you can use this callback to pass the ip address information on to a php script
or do something more interesting
*/
}
}catch( err ){
console.info( err.message )
}
}


rtcpip.call( this, 'google1', ipcallback );
</script>
<style>
body{display:flex;flex-direction:column;justify-content:center;align-items:center;height:100vh;width:100%;padding:0;margin:0;font-family:calibri,verdana,arial;font-size:1rem;}
#ip{display:flex;align-items:center;justify-content:center;flex-direction:column;width:50%;min-height:5rem;height:auto;box-sizing:border-box;border:2px dashed rgba(133,133,133,0.25);border-radius:1rem;color:rgba(133,133,133,0.95);box-shadow: 0 10px 25px rgba(133,133,133,0.95);text-align:center;margin:0 auto;float:none;background:whitesmoke}
</style>
</head>
<body>
<div id='ip'></div>
</body>
</html>

how to get public ip address of my localhost system

try this please:

$externalContent = file_get_contents('http://checkip.dyndns.com/');
preg_match('/Current IP Address: \[?([:.0-9a-fA-F]+)\]?/', $externalContent, $m);
$externalIp = $m[1];

Or use httpbin.org/ip as Priyesh Kumar suggests

How to get the local ip address using php?


echo $_SERVER['SERVER_ADDR']

or

echo $this->input->ip_address();


Related Topics



Leave a reply



Submit