Reputation: 336
I need to extract the hostname from my ip adress.I have tried this:
echo shell_exec('nslookup ' . $iper->Get_Ip())["Server"];
Basically it export everything i need,but i' unable to access the host ip. It looks similar to this:
Server: xxxxx
Address: xxxxx
Non-authoritative answer:
xxxxxxxa name = xxxxxx
Authoritative answers can be found from:
xx.in-addr.arpa nameserver = sec3.apnic.net.
xx.in-addr.arpa nameserver = ns3.lacnic.net.
xx.in-addr.arpa nameserver = tinnie.arin.net.
xx.in-addr.arpa nameserver = sns-pb.isc.org.
xx.in-addr.arpa nameserver = ns3.afrinic.net.
xx.in-addr.arpa nameserver = pri.authdns.ripe.net.
pri.authdns.ripe.net internet address = xxxx
sec3.apnic.net internet address = xxxxxxxx
sns-pb.isc.org internet address = xxxxxx
tinnie.arin.net internet address = xxxx
pri.authdns.ripe.net has AAAA address xxxx
sec3.apnic.net has AAAA address xxxx
sns-pb.isc.org has AAAA address xxxx
tinnie.arin.net has AAAA address xxxx
Is there a better aproach to get the host ,or i'l have to mess around with this way,and try somehow to extract the host ip.... Thanks
Upvotes: 1
Views: 4633
Reputation: 29
PHP has a built-in function for this, gethostbyaddr()
.
<?php
class IpEr{
public function Get_Ip(){
if(!empty($_SERVER['HTTP_CLIENT_IP'])){
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
}
$iper = new IpEr();
$ip_adress = $iper->Get_Ip();
echo gethostbyaddr($ip_adress);
?>
Also, as a general rule, it is not a good idea to use shell_exec
and exec
because it introduces potential security vulnerabilities
Upvotes: 2
Reputation: 336
Here is the answer,the only way which i could find to get the host from the ip was :
$data = (shell_exec('nslookup ' . $ip_adress));
Here is the working code that will return your host ip:
$iper = new IpEr();
$ip_adress = $iper->Get_Ip();
$data = (shell_exec('nslookup ' . $ip_adress));
$data = (explode("\n",$data));
$data = explode(":",$data[0]);
echo trim($data[1]);
And here is the iper class if someone needs it:
<?php
class IpEr{
public function Get_Ip(){
if(!empty($_SERVER['HTTP_CLIENT_IP'])){
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
}
?>
Upvotes: 1