Skip to content

Commit 036d6ca

Browse files
committed
Support reverse lookups from hosts file
1 parent b1b4b8c commit 036d6ca

2 files changed

Lines changed: 69 additions & 0 deletions

File tree

src/Config/HostsFile.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,4 +107,29 @@ public function getIpsForHost($name)
107107

108108
return $ips;
109109
}
110+
111+
/**
112+
* Returns all hostnames for the given IPv4 or IPv6 address
113+
*
114+
* @param string $ip
115+
* @return string[]
116+
*/
117+
public function getHostsForIp($ip)
118+
{
119+
// check binary representation of IP to avoid string case and short notation
120+
$ip = @inet_pton($ip);
121+
122+
$names = array();
123+
foreach (preg_split('/\r?\n/', $this->contents) as $line) {
124+
$parts = preg_split('/\s+/', $line);
125+
126+
if (inet_pton(array_shift($parts)) === $ip) {
127+
foreach ($parts as $part) {
128+
$names[] = $part;
129+
}
130+
}
131+
}
132+
133+
return $names;
134+
}
110135
}

tests/Config/HostsFileTest.php

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,4 +84,48 @@ public function testMergesIpv4AndIpv6EntriesOverMultipleLines()
8484

8585
$this->assertEquals(array('127.0.0.1', '::1'), $hosts->getIpsForHost('localhost'));
8686
}
87+
88+
public function testReverseLookup()
89+
{
90+
$hosts = new HostsFile('127.0.0.1 localhost');
91+
92+
$this->assertEquals(array('localhost'), $hosts->getHostsForIp('127.0.0.1'));
93+
$this->assertEquals(array(), $hosts->getHostsForIp('192.168.1.1'));
94+
}
95+
96+
public function testReverseNonIpReturnsNothing()
97+
{
98+
$hosts = new HostsFile('127.0.0.1 localhost');
99+
100+
$this->assertEquals(array(), $hosts->getHostsForIp('localhost'));
101+
$this->assertEquals(array(), $hosts->getHostsForIp('127.0.0.1.1'));
102+
}
103+
104+
public function testReverseLookupReturnsLowerCaseHost()
105+
{
106+
$hosts = new HostsFile('127.0.0.1 LocalHost');
107+
108+
$this->assertEquals(array('localhost'), $hosts->getHostsForIp('127.0.0.1'));
109+
}
110+
111+
public function testReverseLookupChecksNormalizedIpv6()
112+
{
113+
$hosts = new HostsFile('FE80::00a1 localhost');
114+
115+
$this->assertEquals(array('localhost'), $hosts->getHostsForIp('fe80::A1'));
116+
}
117+
118+
public function testReverseLookupReturnsMultipleHostsOverSingleLine()
119+
{
120+
$hosts = new HostsFile("::1 ip6-localhost ip6-loopback");
121+
122+
$this->assertEquals(array('ip6-localhost', 'ip6-loopback'), $hosts->getHostsForIp('::1'));
123+
}
124+
125+
public function testReverseLookupReturnsMultipleHostsOverMultipleLines()
126+
{
127+
$hosts = new HostsFile("::1 ip6-localhost\n::1 ip6-loopback");
128+
129+
$this->assertEquals(array('ip6-localhost', 'ip6-loopback'), $hosts->getHostsForIp('::1'));
130+
}
87131
}

0 commit comments

Comments
 (0)