The following code implements the IP query function
Processing program
Copy Code code as follows:
Import Os,time
def getip (filepath):
ip2city={}
File=open (filepath, ' R ')
Lines=file.readlines ()
File.close ()
For line in lines:
Ip=line.split (") [0]
City=line.split (") [1]
HASHIP=HASHM (IP)
If haship in ip2city:
Pass
Else
Ip2city[haship]=city
Print (' Hash done! ')
Return ip2city
def hashm (IP):
Iplist=ip.split ('. ')
Ip=int (Iplist[0]) *4+int (iplist[1]) *2+int (iplist[2))
return IP
def GETCITYFROMIP (filepath,ipandcity):
Outputstr=[]
For file in Os.listdir (filepath):
File_handler=open (filepath+ ' \ ' +file, ' R ')
Line=file_handler.readline ()
While line:
Ip=hashm (Line.rstrip ())
If IP in ipandcity:
Outputstr.append (Line.rstrip () + ' +ipandcity[ip])
Line=file_handler.readline ()
File_handler.close ()
Outfile_handler=open (filepath+ ' \ "+file.split) ('. ') [0]+ ' _out.txt ', ' A + ']
Outfile_handler.writelines (OUTPUTSTR)
Outfile_handler.close ()
Print (File.split ('. ') [0]+ ' _out.txt ' + ' done! ')
def splitfile (filepath):
File=open (filepath, ' R ')
block_size=8000000
Filecount=1
Temp=[]
Count=0
Line=file.readline ()
While line or temp:
If count==block_size:
Wfile=open (' D:\\ipfile\\file_ ' +str (filecount) + ' txt ', ' A + ')
Wfile.writelines (temp)
Temp=[]
Count=0
Wfile.close ()
Filecount+=1
Print (' Split ' +str (filecount) + ' done! ')
Else
Count+=1
Temp.append (line)
Line=file.readline ()
File.close ()
Return Os.path.join (' d:\\ ' + ' ipfile ')
if __name__ = = ' __main__ ':
Start=time.clock ()
Filepath= ' D:\\ip.txt '
Ippath= ' D:\\citys.txt '
Ip2city=getip (Ippath)
Splitfilepath=splitfile (filepath)
GETCITYFROMIP (' d:\\ ' + ' ipfile ', ip2city)
End=time.clock ()
Print (End-start)
Generate IP
Copy Code code as follows:
#Generate millon IP
Import Random
Import time
def generateipadd (File,num):
Ip=[]
File=open (file, ' A + ')
For I in range (num):
Ipadd= ' 192.168. ' +str (Random.randint (0,255)) + '. ' +str (Random.randint (0,255))
Ip.append (ipadd+ ' \ n ')
File.writelines (IP)
File.close ()
If __name__== ' __main__ ':
Start=time.clock ()
For I in range (10000):
Generateipadd (' D:\ip.txt ', 10000)
End=time.clock ()
Print (End-start)