Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """High-level ICMP (fallback)"""
- import socket
- import os
- import struct
- import time
- ICMP_ECHO_REQUEST = 8
- ICMP_ECHO_RESPONSE = 0
- def checksum(data: bytearray):
- """ICMP checksum function"""
- if len(data) % 2:
- data += b'\x00'
- total: int = 0
- for i in range(0, len(data), 2):
- w = (data[i] << 8) + data[i + 1]
- total += w
- total = (total & 0xFFFF) + (total >> 16)
- total = ~total & 0xFFFF
- return total
- def build_icmp_packet(pid: int, seq: int, data: bytearray = b''):
- """Builds ICMP packets with the correct sum"""
- header = struct.pack('bbHHh', ICMP_ECHO_REQUEST, 0, 0, pid, seq)
- packet = header + data
- chksum = checksum(packet)
- header = struct.pack('bbHHh', ICMP_ECHO_REQUEST, 0, chksum, pid, seq)
- packet = bytearray(header) + data
- return packet
- def icmp_ping(data, host, timeout: float):
- """"Basic ICMP response ping"""
- icmp_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
- icmp_socket.settimeout(timeout)
- pid = os.getpid() &0xFFFF
- packet = build_icmp_packet(pid, 1, data)
- rt = time.time()
- try:
- host_byname = socket.gethostbyname(host)
- icmp_socket.sendto(packet, (host_byname, 0))
- recv_packet, addr = icmp_socket.recvfrom(1024)
- end_time = (time.time() - rt) * 1000
- print(f"Ping to {host}. RTT: {end_time:.2f}ms\nRecieved: {repr(recv_packet)} from {addr}")
- except socket.timeout as err:
- print(f"Connection to {host} || {host_byname} timed out after {timeout}s. Error: {err}")
- except PermissionError as err:
- print(f"You aren't allowed, {err}")
- except socket.gaierror as err:
- print(f"Could not resolve the domain {host} || {host_byname}. Error: {err}")
- finally:
- icmp_socket.close()
- icmp_ping(bytearray("", encoding="utf-8"), "8.8.8.8", 5)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement