-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathip_handler.py
32 lines (27 loc) · 950 Bytes
/
ip_handler.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import csv
import random
import socket
import struct
class IPHandler(object):
ip_lookup_table = []
@staticmethod
def decimal_to_ip(ip):
return socket.inet_ntoa(struct.pack(">L", ip))
@staticmethod
def get_random_ip(geo=None):
if not IPHandler.ip_lookup_table:
IPHandler.read_csv()
candidates = IPHandler.ip_lookup_table
if geo != None:
candidates = [x for x in candidates if x[2] == geo.upper()]
if len(candidates) == 0:
raise Exception("Geo does not exist!")
row = random.choice(candidates)
decimal_ip = random.randint(int(row[0]), int(row[1]))
return IPHandler.decimal_to_ip(decimal_ip)
@staticmethod
def read_csv():
with open("IP2LOCATION-LITE-DB1.CSV") as file:
c = csv.reader(file, delimiter=",", quotechar='"')
for row in c:
IPHandler.ip_lookup_table.append(row)