SoFunction
Updated on 2024-12-19

Example of python implementation to determine if a string is a legitimate IP address

A just finished the written exam question, simply post it, here is the specific implementation:

#!usr/bin/env python
#encoding:utf-8
'''
__Author__:Yishui Cold City
Function: Determine if a string is a legitimate IP address
'''
import re
def judge_legal_ip(one_str):
 '''
 Regular Matching Methods
 Determine if a string is a legitimate IP address
 '''
 compile_ip=('^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$') 
 if compile_ip.match(one_str): 
  return True 
 else: 
  return False 
def judge_legal_ip2(one_str):
 '''
 Simple string judgment
 '''
 if '.' not in one_str:
  return False
 elif one_str.count('.')!=3:
  return False
 else:
  flag=True
  one_list=one_str.split('.')
  for one in one_list:
   try:
    one_num=int(one)
    if one_num>=0 and one_num<=255:
     pass
    else:
     flag=False
   except:
    flag=False
  return flag
     
if __name__=='__main__':
 ip_list=['','172.31.137.251','100.10.0.1000','1.1.1.1','12.23.13','aa.12.1.2','12345678','289043jdhjkbh']
 for one_str in ip_list:
  if judge_legal_ip(one_str): #Regular methods
  #if judge_legal_ip2(one_str): #string method
   print '{0} is a legal ip address!'.format(one_str)
  else:
   print '{0} is not a legal ip address!'.format(one_str)

The results are as follows:

is not a legal ip address! 
172.31.137.251 is a legal ip address! 
100.10.0.1000 is not a legal ip address! 
1.1.1.1 is a legal ip address! 
12.23.13 is not a legal ip address! 
aa.12.1.2 is not a legal ip address! 
12345678 is not a legal ip address! 
289043jdhjkbh is not a legal ip address! 

The above example of this python implementation to determine whether a string is a legitimate IP address is all that I have shared with you, I hope to give you a reference, and I hope you will support me more.