pythonip-address

Parsing IP address and port in python


Using python, I'd like to accomplish two things:

  1. Need to split an ipv6 address and port combination in the format [fec2::10]:80 to fec2::10 and 80.

  2. Given an IP address and port combination, I need to determine if the IP is a v4 or v6 address. Eg: 1.2.3.4:80 and [fec2::10]:80

Please suggest a way to do it.

Thanks!

Sample code:

#!/usr/bin/env python


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 the input is specified without a port. Eg: 10.78.49.50 and [fec2::10]

Any suggestions to address this?


Solution

  • This is the code I came up with. It looks lengthy and laborious, but it addresses all possible input scenarios. Any suggestion to condense/better it is most welcome :)

    #!/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()