Parse an IP Address: Difference between revisions

Content added Content deleted
m (→‎version 1: changed whitespace and some comments, simplified the program.)
(→‎{{header|Python}}: added a simpler version)
Line 1,823: Line 1,823:


=={{header|Python}}==
=={{header|Python}}==
<lang python>from ipaddress import ip_address
from urllib.parse import urlparse

tests = [
"127.0.0.1",
"127.0.0.1:80",
"::1",
"[::1]:80",
"::192.168.0.1",
"2605:2700:0:3::4713:93e3",
"[2605:2700:0:3::4713:93e3]:80" ]

def parse_ip_port(netloc):
try:
ip = ip_address(netloc)
port = None
except ValueError:
parsed = urlparse('//{}'.format(netloc))
ip = ip_address(parsed.hostname)
port = parsed.port
return ip, port

for address in tests:
ip, port = parse_ip_port(address)
hex_ip = {4:'{:08X}', 6:'{:032X}'}[ip.version].format(int(ip))
print("{:39s} {:>32s} IPv{} port={}".format(
str(ip), hex_ip, ip.version, port ))</lang>

{{out}}
<pre>
127.0.0.1 7F000001 IPv4 port=None
127.0.0.1 7F000001 IPv4 port=80
::1 00000000000000000000000000000001 IPv6 port=None
::1 00000000000000000000000000000001 IPv6 port=80
::c0a8:1 000000000000000000000000C0A80001 IPv6 port=None
2605:2700:0:3::4713:93e3 260527000000000300000000471393E3 IPv6 port=None
2605:2700:0:3::4713:93e3 260527000000000300000000471393E3 IPv6 port=80
</pre>
{{libheader|pyparse}}
{{libheader|pyparse}}
The following uses [http://pyparsing.wikispaces.com/ pyparse] to parse the IP address. It's an attempt at using pyparse to describe an IP address in an ''extended'' [[wp:Backus–Naur_Form|BNF syntax]]. Using a parser does seems a bit like using a sledgehammer to crack a nut. However it does make for an interesting alternative to using a [[Regular expression|regular expressions]] to parse IP addresses. Note - for example - that the parser specifically reports - as an exception - the location where the IP address is syntactically wrong.
The following uses [http://pyparsing.wikispaces.com/ pyparse] to parse the IP address. It's an attempt at using pyparse to describe an IP address in an ''extended'' [[wp:Backus–Naur_Form|BNF syntax]]. Using a parser does seems a bit like using a sledgehammer to crack a nut. However it does make for an interesting alternative to using a [[Regular expression|regular expressions]] to parse IP addresses. Note - for example - that the parser specifically reports - as an exception - the location where the IP address is syntactically wrong.