This article shares two python examples. python constructs icmpecho requests and implements network detector code. similar to the nmap function, python Sends icmp echo requesy requests.
The code is as follows:
Import socket
Import struct
Def checksum (source_string ):
Sum = 0
Countid = (len (source_string)/2) * 2
Count = 0
While count ThisVal = ord (source_string [count + 1]) * 256 + ord (source_string [count])
Sum = sum + thisVal
Sum = sum & 0 xffffffff
Count = count + 2
If countid Sum = sum + ord (source_string [len (source_string)-1])
Sum = sum & 0 xffffffff
Sum = (sum> 16) + (sum & 0 xffff)
Sum = sum + (sum> 16)
Answer = ~ Sum
Answer = answer & 0 xffff
Answer = answer> 8 | (answer <8 & 0xff00)
Return answer
Def ping (ip ):
S = socket. socket (socket. AF_INET, socket. SOCK_RAW, 1)
Packet = struct. pack (
"! BBHHH ", 8, 0, 0, 0, 0
)
Chksum = checksum (packet)
Packet = struct. pack (
"! BBHHH ", 8, 0, chksum, 0, 0
)
S. sendto (packet, (ip, 1 ))
If _ name __= = '_ main __':
Ping ('1970. 168.41.56 ')
Scan and probe network function (network detector)
The code is as follows:
#! /Usr/bin/env python3
#-*-Coding: UTF-8 -*-
'''
Detects the survival of the network host.
'''
Import OS
Import struct
Import array
Import time
Import socket
Import IPy
Import threading
Class SendPingThr (threading. Thread ):
'''
The thread that sends the ICMP request message.
Parameters:
IpPool -- IP address pool that can be iterated
IcmpPacket -- constructed icmp packet
IcmpSocket -- icmp
Timeout -- set sending timeout
'''
Def _ init _ (self, ipPool, icmpPacket, icmpSocket, timeout = 3 ):
Threading. Thread. _ init _ (self)
Self. Sock = icmpSocket
Self. ipPool = ipPool
Self. packet = icmpPacket
Self. timeout = timeout
Self. Sock. settimeout (timeout + 3)
Def run (self ):
Time. sleep (0.01) # wait for the receiving thread to start
For ip in self. ipPool:
Try:
Self. Sock. sendto (self. packet, (ip, 0 ))
Failed T socket. timeout:
Break
Time. sleep (self. timeout)
Class Nscan:
'''
Parameters:
Timeout -- Socket timeout. the default value is 3 seconds.
IPv6-whether it is IPv6; default value: False
'''
Def _ init _ (self, timeout = 3, IPv6 = False ):
Self. timeout = timeout
Self. IPv6 = IPv6
Self. _ data = struct. pack ('D', time. time () # load bytes used for ICMP packets (8bit)
Self. _ id = OS. getpid () # construct the ID field of the ICMP message, which has no practical significance.
@ Property # attribute modifier
Def _ icmpSocket (self ):
'''Create 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
Def _ inCksum (self, packet ):
'''Icmp message verification and calculation method '''
If len (packet) & 1:
Packet = packet + '\ 0'
Words = array. array ('H', packet)
Sum = 0
For word in words:
Sum + = (word & 0 xffff)
Sum = (sum> 16) + (sum & 0 xffff)
Sum = sum + (sum> 16)
Return (~ Sum) & 0 xffff
@ Property
Def _ icmpPacket (self ):
''' Construct ICMP message '''
If not self. IPv6:
Header = struct. pack ('bbhhh', 8, 0, 0, self. _ id, 0) # TYPE, CODE, CHKSUM, ID, SEQ
Else:
Header = struct. pack ('bbhhh', 128, 0, 0, self. _ id, 0)
Packet = header + self. _ data # packet without checksum
ChkSum = self. _ inCksum (packet) # make checksum
If not self. IPv6:
Header = struct. pack ('bbhhh', 8, 0, chkSum, self. _ id, 0)
Else:
Header = struct. pack ('bbhhh', 128, 0, chkSum, self. _ id, 0)
Return header + self. _ data # packet * with * checksum
Def isUnIP (self, IP ):
''' Determine whether the IP address is a valid unicast address '''
IP = [int (x) for x in IP. split ('.') if x. isdigit ()]
If len (IP) = 4:
If (0 <IP [0] <223 and IP [0]! = 127 and IP [1] <256 and IP [2] <256 and 0 <IP [3] <255 ):
Return True
Return False
Def makeIpPool (self, startIP, lastIP ):
'''Production IP address pooled '''
IPver = 6 if self. IPv6 else 4
IntIP = lambda ip: IPy. IP (ip). int ()
IpPool = {IPy. intToIp (ip, IPver) for ip in range (intIP (startIP), intIP (lastIP) + 1 )}
Return {ip for ip in ipPool if self. isUnIP (ip )}
Def mPing (self, ipPool ):
''' Use ICMP packets to detect network host survival
Parameters:
IpPool -- IP address pool that can be iterated
'''
Sock = self. _ icmpSocket
Sock. settimeout (self. timeout)
Packet = self. _ icmpPacket
RecvFroms = set () # container of the source IP address of the receiving thread
SendThr = SendPingThr (ipPool, packet, Sock, self. timeout)
SendThr. start ()
While True:
Try:
RecvFroms. add (Sock. recvfrom (1024) [1] [0])
Failed T Exception:
Pass
Finally:
If not sendThr. isAlive ():
Break
Return recvFroms & ipPool
If _ name __= = '_ main __':
S = Nscan ()
IpPool = s. makeIpPool ('192. 168.0.1 ', '192. 168.0.254 ')
Print (s. mPing (ipPool ))