Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 74ebd9e

Browse files
committed
Fix Issue5111 - Wrap the Ipv6 host with [] in the Host header
1 parent 5ccafba commit 74ebd9e

3 files changed

Lines changed: 28 additions & 0 deletions

File tree

Lib/http/client.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -874,6 +874,13 @@ def putrequest(self, method, url, skip_host=0, skip_accept_encoding=0):
874874
host_enc = self.host.encode("ascii")
875875
except UnicodeEncodeError:
876876
host_enc = self.host.encode("idna")
877+
878+
# As per RFC 273, IPv6 address should be wrapped with []
879+
# when used as Host header
880+
881+
if self.host.find(':') >= 0:
882+
host_enc = b'[' + host_enc + b']'
883+
877884
if self.port == self.default_port:
878885
self.putheader('Host', host_enc)
879886
else:

Lib/test/test_httplib.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,25 @@ def test_putheader(self):
106106
conn.putheader('Content-length', 42)
107107
self.assertTrue(b'Content-length: 42' in conn._buffer)
108108

109+
def test_ipv6host_header(self):
110+
# Default host header on IPv6 transaction should wrapped by [] if
111+
# its actual IPv6 address
112+
expected = b'GET /foo HTTP/1.1\r\nHost: [2001::]:81\r\n' \
113+
b'Accept-Encoding: identity\r\n\r\n'
114+
conn = client.HTTPConnection('[2001::]:81')
115+
sock = FakeSocket('')
116+
conn.sock = sock
117+
conn.request('GET', '/foo')
118+
self.assertTrue(sock.data.startswith(expected))
119+
120+
expected = b'GET /foo HTTP/1.1\r\nHost: [2001:102A::]\r\n' \
121+
b'Accept-Encoding: identity\r\n\r\n'
122+
conn = client.HTTPConnection('[2001:102A::]')
123+
sock = FakeSocket('')
124+
conn.sock = sock
125+
conn.request('GET', '/foo')
126+
self.assertTrue(sock.data.startswith(expected))
127+
109128

110129
class BasicTest(TestCase):
111130
def test_status_lines(self):

Misc/NEWS

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,8 @@ Core and Builtins
6363
Library
6464
-------
6565

66+
- Issue #5111: IPv6 Host in the Header is wrapped inside [ ]. Patch by Chandru.
67+
6668
- Fix Fraction.__hash__ so that Fraction.__hash__(-1) is -2. (See
6769
also issue #10356.)
6870

0 commit comments

Comments
 (0)