1
# vim: tabstop=4 shiftwidth=4 softtabstop=4
3
# Copyright 2012 OpenStack Foundation.
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.
22
from openstack_dashboard.openstack.common import log as logging
25
LOG = logging.getLogger(__name__)
28
def parse_host_port(address, default_port=None):
30
Interpret a string as a host:port pair.
31
An IPv6 address MUST be escaped if accompanied by a port,
32
because otherwise ambiguity ensues: 2001:db8:85a3::8a2e:370:7334
33
means both [2001:db8:85a3::8a2e:370:7334] and
34
[2001:db8:85a3::8a2e:370]:7334.
36
>>> parse_host_port('server01:80')
38
>>> parse_host_port('server01')
40
>>> parse_host_port('server01', default_port=1234)
42
>>> parse_host_port('[::1]:80')
44
>>> parse_host_port('[::1]')
46
>>> parse_host_port('[::1]', default_port=1234)
48
>>> parse_host_port('2001:db8:85a3::8a2e:370:7334', default_port=1234)
49
('2001:db8:85a3::8a2e:370:7334', 1234)
54
_host, _port = address[1:].split(']')
57
port = _port.split(':')[1]
61
if address.count(':') == 1:
62
host, port = address.split(':')
64
# 0 means ipv4, >1 means ipv6.
65
# We prohibit unescaped ipv6 addresses with port.
69
return (host, None if port is None else int(port))