在网上的一些资料的基础上自己又添了些新内容,算是python socket编程练手吧。
#coding=utf-8
import socket
import time
import sys
import struct
import threading
from threading import thread,activecount
results=[]
def portscanner(ip,port):
server = (ip,port)
sockfd = socket.socket(socket.af_inet,socket.sock_stream)
sockfd.settimeout(0.1) #设置阻塞模式下socket的超时时间
ret = sockfd.connect_ex(server) #成功返回0,失败返回error的值。
if not ret:
sockfd.close()
results.append([ip,port])
#print ‘%s:%s is opened…’ % (ip,port)
else:
sockfd.close()
pass
return ”
def ip2num(ip): #将ip地址转换成数字
lp = [int(x) for x in ip.split(‘.’)]
return lp[0] > 16
ip[0] = (num & 0xff000000) >> 24
return ‘%s.%s.%s.%s’ % (ip[0],ip[1],ip[2],ip[3])
def iprange(ip1,ip2):
num1 =socket.ntohl(struct.unpack(“i”,socket.inet_aton(str(ip1)))[0])
num2 =socket.ntohl(struct.unpack(“i”,socket.inet_aton(str(ip2)))[0])
tmp = num2 – num1
if tmp < 0:
return none
else:
return num1,num2,tmp
if name == 'main':
if((len(sys.argv)!= 4)&(len(sys.argv)!= 2)): #用法说明
print 'usage:\n\tscanner.py startip endip port'
print '\tscanner.py ip'
sys.exit()
if len(sys.argv)==4: #对某一ip段的扫描
time_start=time.time() #起始时间
startip = sys.argv[1] #起始ip
endip = sys.argv[2] #结束ip
port = int(sys.argv[3]) #端口号
res = iprange(startip,endip)
if not res:
print 'endip must be bigger than startone'
sys.exit()
elif res[2] == 0:
portscanner(startip,port)
else:
for x in xrange(int(res[2])+1): #ip地址依次递增
startipnum = ip2num(startip)
startipnum = startipnum + x
if activecount()