0

How do I check whether the IP address exist in URL by using Python? Is there any function that can be used to check the IP address? For example:data 1 & data 2 got the IP then will return 1, while data 3 will return 0

data =['http://95.154.196.187/broser/6716804bc5a91f707a34479012dad47c/',
       'http://95.154.196.187/broser/',
       'http://paypal.com.cgi-bin-websc5.b4d80a13c0a2116480.ee0r-cmd-login-submit-dispatch-']

def IP_exist(data):
    for b in data:
        containsdigit = any(a.isdigit() for a in b)
        if containsdigit:
            print("1")
        else:
            print("0")
CDspace
  • 2,639
  • 18
  • 30
  • 36
user3340270
  • 187
  • 1
  • 10
  • 1
    A particular IP address, or any IP address? Anywhere in the URL or in the host part? I.e. should http://google.com/search?q=127.0.0.1 match? What about http://me:95.154.196.187@localhost/? (StackOverflow displays these without the `http://` part and I'm too lazy to work around that.) – tripleee Feb 27 '14 at 16:47

2 Answers2

1

Use a regular expression:

>>> import re
>>> re.match(r'http://\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/.*', 'http://95.154.196.187/broser/6716804bc5a91f707a34479012dad47c/')
<_sre.SRE_Match object at 0x7f4412043440>
>>> re.match(r'http://\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/.*', 'http://paypal.com.cgi-bin-websc5.b4d80a13c0a2116480.ee0r-cmd-login-submit-dispatch-')
>>> 

For a more fine grained regex look here.

Community
  • 1
  • 1
warvariuc
  • 57,116
  • 41
  • 173
  • 227
  • what does the "<_sre.SRE_Match object at 0x02FEF758>" means? if I want data 1 & data 2 got the IP then will return 1, while data 3 will return 0 – user3340270 Feb 27 '14 at 16:50
  • 1
    @user3340270 It means a match has been found and it's returning the match. If nothing matches, it returns None, as shown in the fourth line. – Hugo Feb 27 '14 at 16:55
  • @user3340270, see the [docs](http://docs.python.org/2/library/re.html#re.match) – warvariuc Feb 28 '14 at 05:15
0

If you want to make sure the IP is correct you could extract it from the url using a regex as suggested in the other answer and then to validate you could use netaddr it is fairly simple to use.

from netaddr import IP, AddrFormatError
ip = extract_ip_from_url(url)
try:
  IP(ip)
  return True
except AddrFormatError:
  return False
El Bert
  • 2,958
  • 1
  • 28
  • 36