1
# vim: tabstop=4 shiftwidth=4 softtabstop=4
3
# Copyright 2012 OpenStack LLC.
6
# Licensed under the Apache License, Version 2.0 (the "License"); you may
7
# not use this file except in compliance with the License. You may obtain
8
# a copy of the License at
10
# http://www.apache.org/licenses/LICENSE-2.0
12
# Unless required by applicable law or agreed to in writing, software
13
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15
# License for the specific language governing permissions and limitations
19
Network-related utilities and helper functions.
24
LOG = logging.getLogger(__name__)
27
def parse_host_port(address, default_port=None):
29
Interpret a string as a host:port pair.
30
An IPv6 address MUST be escaped if accompanied by a port,
31
because otherwise ambiguity ensues: 2001:db8:85a3::8a2e:370:7334
32
means both [2001:db8:85a3::8a2e:370:7334] and
33
[2001:db8:85a3::8a2e:370]:7334.
35
>>> parse_host_port('server01:80')
37
>>> parse_host_port('server01')
39
>>> parse_host_port('server01', default_port=1234)
41
>>> parse_host_port('[::1]:80')
43
>>> parse_host_port('[::1]')
45
>>> parse_host_port('[::1]', default_port=1234)
47
>>> parse_host_port('2001:db8:85a3::8a2e:370:7334', default_port=1234)
48
('2001:db8:85a3::8a2e:370:7334', 1234)
53
_host, _port = address[1:].split(']')
56
port = _port.split(':')[1]
60
if address.count(':') == 1:
61
host, port = address.split(':')
63
# 0 means ipv4, >1 means ipv6.
64
# We prohibit unescaped ipv6 addresses with port.
68
return (host, None if port is None else int(port))