Suppose I have a string of the of the format host:port, where :port is optional. How can I reliably extract the two components?
The host can be any of:
- A hostname (
localhost,www.google.com) - An IPv4 literal (
1.2.3.4) - An IPv6 literal (
[aaaa:bbbb::cccc]).
In other words, this is the standard format used across the internet (such as in URIs: complete grammar at https://www.rfc-editor.org/rfc/rfc3986#section-3.2, excluding the "User Information" component).
So, some possible inputs, and desired outputs:
'localhost' -> ('localhost', None)
'my-example.com:1234' -> ('my-example.com', 1234)
'1.2.3.4' -> ('1.2.3.4', None)
'[0abc:1def::1234]' -> ('[0abc:1def::1234]', None)
split.