from netaddr.ip import IPAddress def isIP4or6(cfgstr): ipFlg = False if '/' in cfgstr: text = cfgstr[:cfgstr.rfind('/')] else: text = cfgstr try: addr = IPAddress(text) ipFlg = True except: ipFlg = False if ipFlg == True: return addr.version else: return False str_IPaddress = '192.168.1.2' if isIP4or6(str_IPaddress) == 4: print('It is ipv4.') elif isIP4or6(str_IPaddress) == 6: print('It is ipv6.') else: print('It is neither ipv4 nor ipv6.')