| #!/usr/bin/python |
| # Copyright 2012 Google Inc. All Rights Reserved. |
| |
| """This class defines IP address related operations.""" |
| |
| __author__ = 'Lin Xue (linxue@google.com)' |
| |
| """This file defines IP address related oprations. |
| This includes IPv4, IPv6 check up |
| |
| """ |
| |
| |
| import re |
| import socket |
| |
| |
| class IPADDR(object): |
| """IP address class |
| |
| input: a string |
| fuctions: check if the given string has something like ip address |
| check if the ipv4 address is valid or not |
| check if the given string is valid ipv4 address |
| check if the ipv6 address is valid or not |
| |
| """ |
| |
| def __init__(self, ip_address): |
| self.ipaddr = ip_address |
| |
| def IsLikeIpv4Address(self): |
| """To check if the given string has something like |
| ip address, eg. 4 numbers with 3 . |
| return the ip address in the string if yes, |
| if there is no, return None |
| """ |
| ipaddr_re = re.search(r'[0-9]+(?:\.[0-9]+){3}', self.ipaddr) |
| if ipaddr_re is not None: |
| ipaddr = ipaddr_re.group() |
| return ipaddr |
| else: |
| return None |
| |
| def IsValidIpv4Address(self): |
| """To check if the ipv4 address is valid or not.""" |
| try: |
| socket.inet_aton(self.ipaddr) |
| |
| except socket.error: # not a valid ipv4 address |
| print 'Error: ' + self.ipaddr + ' is an invalid IPv4 address' |
| return False |
| |
| else: |
| if self.ipaddr.count('.') == 3: |
| return True |
| else: |
| print 'Error: ' + self.ipaddr + ' is an invalid IPv4 address' |
| return False |
| |
| def IsIpv4Address(self): |
| """To check if the given string is valid ipv4 address.""" |
| return self.is_like_ipv4_address() and self.is_valid_ipv4_address() |
| |
| def IsValidIpv6Address(self): |
| """To check if the ipv6 address is valid or not.""" |
| try: |
| socket.inet_pton(socket.AF_INET6, self.ipaddr) |
| |
| except socket.error: # not a valid ipv6 address |
| print 'Error: ' + self.ipaddr + ' is an invalid IPv6 address' |
| return False |
| |
| else: |
| if self.ipaddr.count(':') == 7: |
| return True |
| else: |
| print 'Error: ' + self.ipaddr + ' is an invalid IPv6 address' |
| return False |
| |
| # End of IPADDR class |