How To Get or Detect The Local IP Address in PHP

Hello developers, today I am here to provide you with what you are exactly looking for.

In maximum cases developers need to find out the IP address of a user, But if you are developing something for your organization which is bounded by your organization only. Then you will find computers connected to a network and if all the machines are on the same network then the machines can work as a workgroup connected with a network.
So why I am writing this post? what’s the need to find out local IP address?
Actually one of my friends recently asked for my help to find out someone’s local address.

Detect The Country Of The Visitor In PHP


He has a webpage for all the employees and that is served by a local host. But one of his employees is posting unnecessary things on that page. So it is his responsibility to detect the person by finding his local IP address so that he can speak to him personally.
So I guess you are aware of why sometimes its require to find local IP address of a machine.

There are many ways to get the local IP address but I will put here the easiest methods to get us the result.

Finding Local IP address using PHP

echo getHostByName(php_uname('n'));

if you are using PHP version 5.3 or above then this is possibly the best way to get the Local IP Address.

Another way provided below


echo getHostByName(getHostName());

gethostbyname : Get the IPv4 address corresponding to a given Internet host name.

This is also a cool way to find the local IP address of a device connected to a network.


echo gethostbyname(trim(exec("hostname")));

This will also give you the IP address which is local.

Easy to use PHP class to detect client location


Actually here exec used to execute a given command and even you can avoid trim to get the same output.

I will suggest you, leave blank in “hostname” and run on your own and give us a response in the comment section below.
Get visitors country and city in PHP using freegeoip API


Leave a Reply

Your email address will not be published. Required fields are marked *