Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Get IP based on host name

Tags:

c#

php

ip

I have to implement a solution from WinApp written in C# to PHP. I need to extract the IP based on the host name. The below piece of code works perfectly:

IPHostEntry LocalHostIPEntry = Dns.GetHostEntry(hostname);
IPAddress LocalHostIP = LocalHostIPEntry.AddressList[0];
string ipfromhost = LocalHostIP.ToString();

The only option I've found so far in PHP is:

gethostbyname('hostname');

But that returns a different IP for the same host than the C# code. Furthermore, the IP it returns is incorrect. If I check the related host using nslookup -IPaddress- then I get a totally different hostname.

What's going on? What other methods could be used to lookup the IP of a host on the network using PHP?

like image 299
fishmong3r Avatar asked Jun 21 '16 14:06

fishmong3r


People also ask

How do you get the user's IP address in PHP?

Using getenv() function: To get the IP Address,we use getenv(“REMOTE_ADDR”) command. The getenv() function in PHP is used for retrieval of values of an environment variable in PHP. It is used to return the value of a specific environment variable.

What is $_ server [' Remote_addr ']?

$_SERVER['REMOTE_ADDR'] Returns the IP address from where the user is viewing the current page.

How validate IP in PHP?

PHP's filter_var function can validate if an IP address is valid and can further validate if it is an IPv4 IP, IPv6 IP, or not within the private or reserved ranges.


1 Answers

you can use the php dns_get_record function

array dns_get_record ( string $hostname [, int $type = DNS_ANY [, array &$authns [, array &$addtl [, bool &$raw = false ]]]] )

And then look in the array for a record of type A (means IPv4)

like image 193
fucethebads Avatar answered Sep 29 '22 04:09

fucethebads