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
?
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.
$_SERVER['REMOTE_ADDR'] Returns the IP address from where the user is viewing the current page.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With