Skip to content

Commit 5a3e0fa

Browse files
committed
Ignore IPv6 zone IDs from hosts file
1 parent 036d6ca commit 5a3e0fa

2 files changed

Lines changed: 26 additions & 1 deletion

File tree

src/Config/HostsFile.php

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,11 @@ public function getIpsForHost($name)
101101
$parts = preg_split('/\s+/', $line);
102102
$ip = array_shift($parts);
103103
if ($parts && array_search($name, $parts) !== false) {
104+
// remove IPv6 zone ID (`fe80::1%lo0` => `fe80:1`)
105+
if (strpos($ip, ':') !== false && ($pos = strpos($ip, '%')) !== false) {
106+
$ip= substr($ip, 0, $pos);
107+
}
108+
104109
$ips[] = $ip;
105110
}
106111
}
@@ -122,8 +127,14 @@ public function getHostsForIp($ip)
122127
$names = array();
123128
foreach (preg_split('/\r?\n/', $this->contents) as $line) {
124129
$parts = preg_split('/\s+/', $line);
130+
$addr = array_shift($parts);
131+
132+
// remove IPv6 zone ID (`fe80::1%lo0` => `fe80:1`)
133+
if (strpos($addr, ':') !== false && ($pos = strpos($addr, '%')) !== false) {
134+
$addr = substr($addr, 0, $pos);
135+
}
125136

126-
if (inet_pton(array_shift($parts)) === $ip) {
137+
if (@inet_pton($addr) === $ip) {
127138
foreach ($parts as $part) {
128139
$names[] = $part;
129140
}

tests/Config/HostsFileTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,13 @@ public function testContainsSingleLocalhostEntry()
4141
$this->assertEquals(array(), $hosts->getIpsForHost('example.com'));
4242
}
4343

44+
public function testIgnoresIpv6ZoneId()
45+
{
46+
$hosts = new HostsFile('fe80::1%lo0 localhost');
47+
48+
$this->assertEquals(array('fe80::1'), $hosts->getIpsForHost('localhost'));
49+
}
50+
4451
public function testSkipsComments()
4552
{
4653
$hosts = new HostsFile('# start' . PHP_EOL .'#127.0.0.1 localhost' . PHP_EOL . '127.0.0.2 localhost # example.com');
@@ -115,6 +122,13 @@ public function testReverseLookupChecksNormalizedIpv6()
115122
$this->assertEquals(array('localhost'), $hosts->getHostsForIp('fe80::A1'));
116123
}
117124

125+
public function testReverseLookupIgnoresIpv6ZoneId()
126+
{
127+
$hosts = new HostsFile('fe80::1%lo0 localhost');
128+
129+
$this->assertEquals(array('localhost'), $hosts->getHostsForIp('fe80::1'));
130+
}
131+
118132
public function testReverseLookupReturnsMultipleHostsOverSingleLine()
119133
{
120134
$hosts = new HostsFile("::1 ip6-localhost ip6-loopback");

0 commit comments

Comments
 (0)