IP and port handling in python and bash

Using python and bash, I would like to accomplish two things:

  • It is necessary to split the ipv6 address and the combination of ports in the format [fec2 :: 10]: from 80 to fec2 :: 10 and 80.

  • Given the IP address and the combination of ports, I need to determine if the IP address is v4 or v6. For example: 1.2.3.4:80 and [fec2 :: 10]: 80

Please suggest a way to do this.

Thank!

Code example:

#!/usr/bin/env python

import optparse

def main():
    server = "[fec1::1]:80"
    if server.find("[", 0, 2) == -1:
       print "IPv4"
       ip, port = server.split(':')
    else:
       print "IPv6"
       new_ip, port = server.rsplit(':', 1)
       print new_ip
       ip = new_ip.strip('[]')

    print ip
    print port

if __name__ == '__main__':
    main()

This works for all cases except when input is specified without a port. For example: 10.78.49.50 and [fec2 :: 10]

Any suggestions to fix this?

+3
source share
3 answers

, . , . / :)

#!/usr/bin/env python

import optparse

def main():
    server = "[fec1::1]:80"

    if server.find("[", 0, 2) == -1:
       print "IPv4"
       if server.find(":", 0, len(server)) == -1:
          ip = server
          port = ""
       else:
          ip, port = server.split(':')
    else:
       print "IPv6"
       index = server.find("]", 0, len(server))
       if index == -1:
          print "Something wrong"
          new_ip = ""
          port = ""
       else:
          if server.find(":", index, len(server)) == -1:
             new_ip = server
             port = ""
          else:
             new_ip, port = server.rsplit(':', 1)
       print new_ip
       ip = new_ip.strip('[]')

    print ip
    print port

if __name__ == '__main__':
    main()
0

, your_input "[fec2::10]:80" "1.2.3.4:80", IP-:

#!/usr/bin/env python3
from ipaddress import ip_address

ip, separator, port = your_input.rpartition(':')
assert separator # separator (`:`) must be present
port = int(port) # convert to integer
ip = ip_address(ip.strip("[]")) # convert to `IPv4Address` or `IPv6Address` 
print(ip.version) # print ip version: `4` or `6`
+3

urlparse ( urllib.parse 3.x), URL- :

>>> from urlparse import urlparse
>>> ipv4address = urlparse("http://1.2.3.4:80")
>>> ipv4address
ParseResult(scheme='http', netloc='1.2.3.4:80', path='', params='', query='', fragment='')
>>> ipv6address = urlparse("http://[fec2::10]:80")
>>> ipv6address
ParseResult(scheme='http', netloc='[fec2::10]:80', path='', params='', query='', fragment='')

, , rfind:

>>> ipv4address.netloc.rfind(':')
7
>>> ipv4address.netloc[:7], ipv4address.netloc[8:]
('1.2.3.4', '80')
>>> ipv6address.netloc.rfind(':')
10
>>> ipv6address.netloc[:10], ipv6address.netloc[11:]
('[fec2::10]', '80')

, , if ':' in that_split_tuple[0], ? ( 100% , , , IPv6 URL-.)

, IPv6- , :

>>> ipv6address.netloc[:10].replace('[', '').replace(']', '')
'fec2::10'
>>> ipv6address.netloc[:10].strip('[]')
'fec2::10'

: , , :

>>> import re
>>> f = lambda(n): re.split(r"(?<=\]):" if n.startswith('[') else r"(?<=\d):", n)
>>> f(ipv4address.netloc)
['1.2.3.4', '80']
>>> f(ipv6address.netloc)
['[fec2::10]', '80']
>>> f("1.2.3.4")
['1.2.3.4']
>>> f("[fec2::10]")
['[fec2::10]']

(I have problems being smarter with my regex, hence inline triple.)

+1
source

All Articles