Skip to content

Commit ffd251f

Browse files
committed
Support IP2Proxy Web Service.
1 parent 91e6ce3 commit ffd251f

File tree

7 files changed

+123
-4
lines changed

7 files changed

+123
-4
lines changed

ChangeLog

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
3.3.0 2021-08-18
2+
* Support IP2Proxy Web Service.
3+
14
3.2.1 2021-07-19
25
* Removed unused code.
36

IP2Proxy.py

Lines changed: 67 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,45 @@
1919
import socket
2020
import ipaddress
2121
import os
22+
import json
23+
import re
2224

2325
if sys.version < '3':
26+
import urllib, httplib
27+
def urlencode(x):
28+
return urllib.urlencode(x)
29+
def httprequest(x, usessl):
30+
try:
31+
# conn = httplib.HTTPConnection("api.ip2proxy.com")
32+
if (usessl is True):
33+
conn = httplib.HTTPSConnection("api.ip2proxy.com")
34+
else:
35+
conn = httplib.HTTPConnection("api.ip2proxy.com")
36+
conn.request("GET", "/?" + x)
37+
res = conn.getresponse()
38+
return json.loads(res.read())
39+
except:
40+
return None
2441
def u(x):
2542
return x.decode('utf-8')
2643
def b(x):
2744
return str(x)
2845
else:
46+
import urllib.parse, http.client
47+
def urlencode(x):
48+
return urllib.parse.urlencode(x)
49+
def httprequest(x, usessl):
50+
try:
51+
# conn = http.client.HTTPConnection("api.ip2proxy.com")
52+
if (usessl is True):
53+
conn = http.client.HTTPSConnection("api.ip2proxy.com")
54+
else:
55+
conn = http.client.HTTPConnection("api.ip2proxy.com")
56+
conn.request("GET", "/?" + x)
57+
res = conn.getresponse()
58+
return json.loads(res.read())
59+
except:
60+
return None
2961
def u(x):
3062
if isinstance(x, bytes):
3163
return x.decode()
@@ -53,7 +85,7 @@ def inet_pton(t, addr):
5385
return out_addr_p.raw
5486
socket.inet_pton = inet_pton
5587

56-
_VERSION = '3.2.1'
88+
_VERSION = '3.3.0'
5789
_NO_IP = 'MISSING IP ADDRESS'
5890
_FIELD_NOT_SUPPORTED = 'NOT SUPPORTED'
5991
_INVALID_IP_ADDRESS = 'INVALID IP ADDRESS'
@@ -623,3 +655,37 @@ def _get_record(self, ip):
623655
high = mid - 1
624656
else:
625657
low = mid + 1
658+
659+
class IP2ProxyWebService(object):
660+
''' IP2Proxy web service '''
661+
def __init__(self,apikey,package,usessl=True):
662+
if ((re.match(r"^[0-9A-Z]{10}$", apikey) == None) and (apikey != 'demo')):
663+
raise ValueError("Please provide a valid IP2Proxy web service API key.")
664+
if (re.match(r"^PX[0-9]+$", package) == None):
665+
package = 'PX1'
666+
self.apikey = apikey
667+
self.package = package
668+
self.usessl = usessl
669+
670+
def lookup(self,ip):
671+
'''This function will look the given IP address up in IP2Proxy web service.'''
672+
parameters = urlencode((("ip", ip), ("key", self.apikey), ("package", self.package)))
673+
response = httprequest(parameters, self.usessl)
674+
if (response == None):
675+
return False
676+
if (('response' in response) and (response['response'] != "OK")):
677+
raise IP2ProxyAPIError(response['response'])
678+
return response
679+
680+
def getcredit(self):
681+
'''Get the remaing credit in your IP2Proxy web service account.'''
682+
parameters = urlencode((("key", self.apikey), ("check", True)))
683+
response = httprequest(parameters, self.usessl)
684+
if (response == None):
685+
return 0
686+
if ('response' in response is False):
687+
return 0
688+
return response['response']
689+
690+
class IP2ProxyAPIError(Exception):
691+
"""Raise for IP2Proxy API Error Message"""

PKG-INFO

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
Metadata-Version: 1.0
22
Name: IP2Proxy
3-
Version: 3.2.1
3+
Version: 3.3.0
44
Summary: Python API for IP2Proxy database
55
Home-page: http://www.ip2location.com
66
Author: IP2Location

README.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,18 @@ Below are the methods supported in this library.
3535
|get_threat|Return the threat types reported to proxy's IP address or domain name.|
3636
|get_provider|Returns the VPN service provider name if available.|
3737

38+
## Web Service
39+
40+
Below is the description of the functions available in the **Web Service** lookup.
41+
42+
| Method Name | Description |
43+
| ----------- | ------------------------------------------------------------ |
44+
| Constructor | Expect 3 input parameters:IP2Proxy API Key.Package (PX1 - PX10)Use HTTPS or HTTP |
45+
| lookup | Return the proxy information in array.<ul><li>countryCode</li><li>countryName</li><li>regionName</li><li>cityName</li><li>isp</li><li>domain</li><li>usageType</li><li>asn</li><li>as</li><li>lastSeen</li><li>threat</li><li>proxyType</li><li>isProxy</li></ul> |
46+
| getcredit | Return remaining credit of the web service account. |
47+
3848
## Requirements
49+
3950
1. Python 2.2 and above
4051

4152
## Installation
@@ -100,6 +111,13 @@ print ('Provider: ' + record['provider'])
100111

101112
# close IP2Proxy BIN database
102113
db.close()
114+
115+
# Web Service
116+
ws = IP2Proxy.IP2ProxyWebService("demo","PX11",True)
117+
rec = ws.lookup("8.8.8.8")
118+
print (rec)
119+
print ("\n")
120+
print ("Credit Remaining: {}\n".format(ws.getcredit()))
103121
```
104122

105123
## Proxy Type

example.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,4 +45,11 @@
4545
print ('Provider: ' + record['provider'])
4646

4747
# close IP2Proxy BIN database
48-
db.close()
48+
db.close()
49+
50+
# Web Service
51+
ws = IP2Proxy.IP2ProxyWebService("demo","PX11",True)
52+
rec = ws.lookup("8.8.8.8")
53+
print (rec)
54+
print ("\n")
55+
print ("Credit Remaining: {}\n".format(ws.getcredit()))

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
setuptools.setup(
77
name="IP2Proxy",
8-
version="3.2.1",
8+
version="3.3.0",
99
author="IP2Location",
1010
author_email="support@ip2location.com",
1111
description="Python API for IP2Proxy database. It can be used to query an IP address if it was being used as open proxy, web proxy, VPN anonymizer and TOR exits.",

tests/test_webservice.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# -*- coding: utf-8 -*-
2+
3+
import pytest
4+
5+
import IP2Proxy
6+
7+
apikey = "demo"
8+
package = "PX11"
9+
usessl = True
10+
11+
ws = IP2Proxy.IP2ProxyWebService(apikey,package,usessl)
12+
13+
def testcountrycode():
14+
# ws = IP2Proxy.IP2ProxyWebService(apikey,package,usessl)
15+
rec = ws.lookup("8.8.8.8")
16+
assert rec['country_code'] == "US", "Test failed because country code not same."
17+
18+
def testgetcredit():
19+
credit = ws.getcredit()
20+
assert str(credit).isdigit() == True, "Test failed because it is no a digit value."
21+
22+
def testfunctionexist():
23+
functions_list = ['lookup', 'getcredit']
24+
for x in range(len(functions_list)):
25+
assert hasattr(ws, functions_list[x]) == True, "Function did not exist."

0 commit comments

Comments
 (0)