Python constructs icmp echo requests and implements network detector function code sharing

Source: Internet
Author: User
Tags network function

Python sends icmp echo requesy request

Copy codeThe Code is as follows:
Import socket
Import struct

Def checksum (source_string ):
Sum = 0
Countid = (len (source_string)/2) * 2
Count = 0
While count <countid:
ThisVal = ord (source_string [count + 1]) * 256 + ord (source_string [count])
Sum = sum + thisVal
Sum = sum & 0 xffffffff
Count = count + 2
If countTo <len (source_string ):
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)

Copy codeThe 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 ))

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.