本文整理汇总了Python中socket.getprotobyname函数的典型用法代码示例。如果您正苦于以下问题:Python getprotobyname函数的具体用法?Python getprotobyname怎么用?Python getprotobyname使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了getprotobyname函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: open_sockets
def open_sockets(self):
# Create sockets for the connections.
self.recv_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
self.send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp)
icmp = socket.getprotobyname('icmp')
udp = socket.getprotobyname('udp')
示例2: __icmpSocket
def __icmpSocket(self):
'''创建ICMP Socket'''
if not self.IPv6:
Sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp"))
else:
Sock = socket.socket(socket.AF_INET6, socket.SOCK_RAW, socket.getprotobyname("ipv6-icmp"))
return Sock
示例3: trace
def trace(address):
port = 33500
ttl = 1
icmp_proto = socket.getprotobyname('icmp')
upd_proto = socket.getprotobyname('udp')
while ttl < 127:
ssocket = socket.socket(type=socket.SOCK_DGRAM, proto=upd_proto)
rsocket = socket.socket(type=socket.SOCK_RAW, proto=icmp_proto)
ssocket.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
rsocket.bind(('', port))
ssocket.sendto('', (address, port))
last_addr = None
try:
rsocket.settimeout(20)
_, last_addr = rsocket.recvfrom(256)
last_addr = last_addr[0]
print last_addr
except socket.timeout:
print "* * *"
except socket.error:
print "* * *"
finally:
ssocket.close()
rsocket.close()
if last_addr == address:
break
else:
ttl += 1
示例4: start
def start(self, *args, **kws):
with\
closing(socket.socket( socket.AF_INET,
socket.SOCK_RAW, socket.getprotobyname('icmp') )) as self.ipv4,\
closing(socket.socket( socket.AF_INET6,
socket.SOCK_RAW, socket.getprotobyname('ipv6-icmp') )) as self.ipv6:
return self._start(*args, **kws)
示例5: rtt
def rtt(result):
port = 33434
print ("result: ", result)
rtt = 0.0 # initialize important values
host_name = result[0]
host_ip = result[1]
ttl = result[2]
udp = socket.getprotobyname("udp") # set up sockets
icmp = socket.getprotobyname("icmp")
timeout = struct.pack("ll", 3, 0)
r = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp) # raw socket: receive ICMP messages
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp) # raw socket to send UDP packets
r.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, timeout) # timeout
s.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl) # initial TTL for the UDP packet
send_time = time.time() # record time packet was sent
s.sendto("", (host_name, port)) # sends UDP packet to host over port
current_ip = None
pckt = False
att = 3
data = ""
while data != "": # listener
data, host = r.recvfrom(512) # take 512 bytes
rtt = (time.time() - send_time) # in ms
r.close() # close sockets
s.close()
return "{0:.2f}".format(rtt*1000)
示例6: addport
def addport( csvline, domain=defaultdomain ):
"""
Adds a network port to the FMC
"""
proto,port,name,description = csvline.split(",")
post_data = { "type": "ProtocolPortObject" }
try:
#Checks if proto is a string and a known protocol
socket.getprotobyname( proto )
except:
try:
#Check if protocol is a number
int( protocol ) + 1
except:
raise ValueError( "addport", "ERROR", "Unknown value: {value} for {field} in csv line: {line}".format( value=repr( proto ), field="protocol", line=repr( csvline ) ) )
post_data[ "protocol" ] = proto
try:
portname = socket.getservbyname( port )
except:
try:
portname = socket.getservbyport( port )
except:
raise ValueError( "addport", "ERROR", "Unknown value: {value} for {field} in csv line: {line}".format( value=repr( port ), field="port", line=repr( csvline ) ) )
post_data[ "port" ] = port
post_data[ "overridable" ] = "true"
post_data[ "description" ] = description
post_data[ "name" ] = name
api_path = "/api/fmc_config/v1/domain/" + domain + "/object/protocolportobjects"
json_resp = requesttofmc( api_path, post_data )
objectadded( json_resp [ "name" ], json_resp [ "type" ], json_resp [ "id" ] )
return True
示例7: main
def main(dest_name):
dest_addr = socket.gethostbyname(dest_name)
port = 33434
icmp = socket.getprotobyname('icmp')
udp = socket.getprotobyname('udp')
ttl = 1
recv_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp)
send_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
recv_socket.bind(("", port))
send_socket.sendto("", (dest_name, port))
curr_addr = None
curr_name = None
try:
_, curr_addr = recv_socket.recvfrom(512)
curr_addr = curr_addr[0]
try:
curr_name = socket.gethostbyaddr(curr_addr)[0]
except socket.error:
curr_name = curr_addr
except socket.error:
pass
finally:
send_socket.close()
recv_socket.close()
if curr_addr is not None:
curr_host = "%s (%s)" % (curr_name, curr_addr)
else:
curr_host = "*"
print "%d\t%s" % (ttl, curr_host)
ttl += 1
示例8: trace
def trace(self):
"""Handles iteration of send/receive messages and setup of sockets.
Initial ttl=1, then increments ttl and repeats until the destination
is reached or *max_hops* is exceeded.
"""
icmp = socket.getprotobyname('icmp')
udp = socket.getprotobyname('udp')
receive_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp)
while True:
send_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, self.ttl)
time_sent = time.time()
self.send_message(send_socket, self.destination_name)
current_address, current_name = self.receive_message(receive_socket)
receive_time = time.time() - time_sent
if current_address is not None:
current_host = '{host} ({address})'.format(host=current_name,
address=current_address)
else:
current_host = '*'
print("{ttl}\t{host} {time} msec".format(ttl=self.ttl,
host=current_host,
time=round(receive_time * 1000, 3)))
if current_address == self.destination_address or self.ttl >= self.max_hops:
break
self.ttl += 1
send_socket.close()
receive_socket.close()
示例9: raw_traceroute
def raw_traceroute(target, ttl):
port = 33433
# icmp = socket.getprotobyname('icmp')
# udp = socket.getprotobyname('udp')
recv_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname('icmp'))
send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.getprotobyname('udp'))
send_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
recv_socket.bind(("", port))
recv_socket.settimeout(30)
# Start timing in milliseconds
t0 = time.time() * 1000.00
t1 = 0
send_socket.sendto("", (target, port))
try:
#If we receive something, stop the clock
recv_packet, curr_addr = recv_socket.recvfrom(1024)
t1 = time.time() * 1000.00
except socket.error:
pass
finally:
send_socket.close()
recv_socket.close()
#If we didn't get an answer, return Nones
if (t1 == 0):
return None, None
else:
return curr_addr[0], t1 - t0
示例10: distMeasurement
def distMeasurement(desthost):
print ("Measure the hop distance and RTT of " + desthost)
destaddr = socket.gethostbyname(desthost) #get the ip address for a given hsot
#print (destaddr)
port = 33435 #port used in the destination port field in udp packet
udp = socket.getprotobyname("udp")
icmp = socket.getprotobyname("icmp")
ttl = 32 #the initial TTL in the ip header will be this
#use UDP segment to test a host, the UDP segment is send to a port that is unlikely to be used in destination host
#create a sending socket using udp protocol
sendsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp)
sendsocket.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl) #set the ttl field in IP header
#create a receiving socket as a raw socket, using icmp protocol, in order to receive all the IP datagram
recvsocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
sendtime = send(destaddr, sendsocket, port)
TTL, arrivedtime = getreply(recvsocket, destaddr, port)
if TTL:
delay = arrivedtime - sendtime
delay = 1000*delay #delay is going to be showed in the unit of ms.
TTL = 32 - TTL #subtracting 32 with the remaining TTL in the header field to get the hop distance
print ("Destination host: %s, Hop distance: %s, RTT: %1.1fms" %(desthost, TTL, delay))
sendsocket.close()
recvsocket.close()
开发者ID:YaokaiYang-assultmaster,项目名称:Python-based-RTT-hop-distance-and-geo-distance-measurer,代码行数:25,代码来源:distMeasurement.py
示例11: run
def run(host, port):
icmp = socket.getprotobyname('icmp')
udp = socket.getprotobyname('udp')
_ttl = 1
_hop_max = 30
while True:
r_icmp_sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
s_udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp)
s_udp_sock.setsockopt(socket.SOL_IP, socket.IP_TTL, _ttl)
r_icmp_sock.bind(("0.0.0.0", port))
s_udp_sock.sendto(b"", (host, port))
try:
_addr, _port = r_icmp_sock.recvfrom(1024)[1]
host_name = socket.gethostbyname(_addr)
addr_info = socket.getaddrinfo(_addr, _port)
print("{}. - {}:{}\n{}".format(_ttl, _addr, _port, addr_info))
except Exception as e:
print(sys.exc_info()[1])
s_udp_sock.close()
r_icmp_sock.close()
_ttl += 1
if _ttl >= _hop_max:
break
示例12: probe
def probe(host, ttl=30):
sending_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.getprotobyname('udp'))
receiving_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname('icmp'))
sending_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
receiving_socket.bind(('', PORT_NUM))
receiving_socket.settimeout(3)
start_probe_time = time.time()
end_probe_time = time.time()+3 #3 is the timeout
sending_socket.sendto('', (host, PORT_NUM))
data = None
address = None
name = None
try:
data, address = receiving_socket.recvfrom(512)
address = address[0]
end_probe_time = time.time()
try:
name = socket.gethostbyaddr(address)
name = name[0]
except Exception, e:
name = address
else:
示例13: traceroute
def traceroute(dest_addr, max_hops=30, timeout=0.2):
proto_icmp = socket.getprotobyname('icmp')
proto_udp = socket.getprotobyname('udp')
port = 33434
for ttl in xrange(1, max_hops+1):
rx = socket.socket(socket.AF_INET, socket.SOCK_RAW, proto_icmp)
rx.settimeout(timeout)
rx.bind(('', port))
tx = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, proto_udp)
tx.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
tx.sendto('', (dest_addr, port))
try:
data, curr_addr = rx.recvfrom(512)
curr_addr = curr_addr[0]
except socket.error:
curr_addr = None
finally:
rx.close()
tx.close()
yield curr_addr
if curr_addr == dest_addr:
break
示例14: PING_START
def PING_START(type, source, alive = 0, timeout = 1.0, ipv6 = 0, number = sys.maxint, node = None, flood = 0, size = ICMP_DATA_STR, status_only = 0):
repl = ''
if ipv6:
if socket.has_ipv6:
try:
info, port = socket.getaddrinfo(node, None)
host = info[4][0]
if host == node:
noPrintIPv6adr = 1
except:
repl += (u'Не могу найти %s: Неизвестный хост' % node)+'\n'
else:
repl += u'Недоступно IPv6 для на данной платформе\n'
else:
try:
host = socket.gethostbyname(node)
except:
repl += (u'Не могу найти %s: Неизвестный хост' % node)+'\n'
if not ipv6:
try:
if int(string.split(host, ".")[-1]) == 0:
repl += u'Нет поддержки пинга в сети'+'\n'
except:
repl += u'Пинг: ошибка, не корректный запрос'+'\n'
host = '0.0.0.0'
if number == 0:
repl += (u'Ошибка количества пакетов на передачу: %s' % str(a))+'\n'
if alive:
number = 1
start, mint, maxt, avg, lost, tsum, tsumsq = 1, 999, 0.0, 0.0, 0, 0.0, 0.0
if not alive:
if ipv6 and not status_only:
if noPrintIPv6adr == 1:
repl += (u'Пинг: %s : %d байты (40+8+%d)' % (str(node), 40 + 8 + size, size))+'\n'
else:
repl += (u'Пинг: %s (%s): %d байты (40+8+%d)' % (str(node), str(host), 40 + 8 + size, size))+'\n'
elif not status_only:
repl += (u'Пинг: %s (%s): %d байты (20+8+%d)' % (str(node), str(host), 20 + 8 + size, size))+'\n'
try:
while start <= number:
lost += 1
if ipv6:
try:
Psocket = socket.socket(socket.AF_INET6, socket.SOCK_RAW, socket.getprotobyname("ipv6-icmp"))
except socket.error, e:
repl += u'Ошибка сокета: %s' % e+u' You must be root (%s uses raw sockets)' % os.path.basename(sys.argv[0])+'\n'
else:
try:
Psocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp"))
except socket.error, e:
repl += u'Ошибка сокета: %s' % e+u' You must be root (%s uses raw sockets)' % os.path.basename(sys.argv[0])+'\n'
Packet = Packet_construct(start, size, ipv6)
try:
Psocket.sendto(Packet,(node, 1))
except socket.error, e:
repl += u'Ошибка сокета: %s' % e+'\n'
示例15: main
def main(dest_name, logfilename):
logfile = open(logfilename, "wb")
headline = "#time\tduration\tmin\tavg_60\tavg_300\tmax\taddress"
print headline
logfile.write(headline + "\n")
dest_addr = socket.gethostbyname(dest_name)
port = random.randint(1, 65535)
icmp = socket.getprotobyname("icmp")
udp = socket.getprotobyname("udp")
recv_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp)
# send_socket.setsockopt(socket.SOL_IP)
recv_socket.bind(("", port))
curr_addr = None
curr_name = None
min_value = 99.0
max_value = 0.0
avg_60 = 0.0
avg_300 = 0.0
while True:
starttime = time.time()
duration = 0
send_socket.sendto("", (dest_name, port))
try:
recv_socket.setblocking(0)
# set receive timeout in seconds
ready = select.select([recv_socket], [], [], recv_timeout)
if ready[0]:
_, curr_addr = recv_socket.recvfrom(512)
duration = time.time() - starttime
curr_addr = curr_addr[0]
if duration > max_value:
max_value = duration
if duration < min_value:
min_value = duration
avg_60 = (59 * avg_60 + duration) / 60
avg_300 = (299 * avg_300 + duration) / 300
output = "%d\t%0.8f\t%0.8f\t%0.8f\t%0.8f\t%0.8f\t%s" % (
starttime,
duration,
min_value,
avg_60,
avg_300,
max_value,
curr_addr,
)
print output
logfile.write(output + "\n")
logfile.flush()
else:
print "%d Timeout waiting for response" % starttime
except socket.error:
pass
time.sleep(1)
send_socket.close()
recv_socket.close()
logfile.close()