Skip to content

Commit eb8b4d4

Browse files
committed
Add support for URI that contains an IPv6 address
Fix #73: Net::HTTP.get_response(URI.parse("http://[::1]")) When the 'Host' header does not wrap an IPv6 address in brackets, some servers (eg Apache) reject the request with a 400 status code.
1 parent beb20c0 commit eb8b4d4

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

lib/net/http/generic_request.rb

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,10 @@ def initialize(m, reqbody, resbody, uri_or_path, initheader = nil) # :nodoc:
1919

2020
if URI === uri_or_path then
2121
raise ArgumentError, "not an HTTP URI" unless URI::HTTP === uri_or_path
22-
hostname = uri_or_path.hostname
23-
raise ArgumentError, "no host component for URI" unless (hostname && hostname.length > 0)
22+
host = uri_or_path.host
23+
raise ArgumentError, "no host component for URI" unless (host && host.length > 0)
2424
@uri = uri_or_path.dup
25-
host = @uri.hostname.dup
25+
host = host.dup
2626
host << ":" << @uri.port.to_s if @uri.port != @uri.default_port
2727
@path = uri_or_path.request_uri
2828
raise ArgumentError, "no HTTP request path given" unless @path
@@ -220,7 +220,7 @@ def update_uri(addr, port, ssl) # :nodoc: internal use only
220220
end
221221

222222
if host = self['host']
223-
host.sub!(/:.*/m, '')
223+
host.sub!(/:\d+\Z/, '')
224224
elsif host = @uri.host
225225
else
226226
host = addr

test/net/http/test_http_request.rb

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,5 +89,27 @@ def test_header_set
8989
'Bug #7831 - do not decode content if the user overrides'
9090
end if Net::HTTP::HAVE_ZLIB
9191

92+
def test_ipv6_address_as_host_header
93+
req = Net::HTTP::Get.new(URI.parse("http://[::1]"))
94+
assert_equal "[::1]", req["host"]
95+
end
96+
97+
def test_ipv6_address_as_host_header_with_port
98+
req = Net::HTTP::Get.new(URI.parse("http://[::1]:2020"))
99+
assert_equal "[::1]:2020", req["host"]
100+
end
101+
102+
def test_ipv6_address_on_update_uri
103+
req = Net::HTTP::Get.new(URI.parse("http://[::1]"))
104+
req.send(:update_uri, "[::1]", 80, false)
105+
assert_equal "[::1]", req.instance_variable_get(:@uri).host
106+
end
107+
108+
def test_ipv6_address_with_port_on_update_uri
109+
req = Net::HTTP::Get.new(URI.parse("http://[::1]:7777"))
110+
req.send(:update_uri, "[::1]", 2020, false)
111+
assert_equal "[::1]", req.instance_variable_get(:@uri).host
112+
assert_equal 2020, req.instance_variable_get(:@uri).port
113+
end
92114
end
93115

0 commit comments

Comments
 (0)