Last active
June 12, 2024 14:05
-
-
Save pyos/10980172 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
import random | |
import struct | |
import select | |
import socket | |
def chk(data): | |
x = sum(x << 8 if i % 2 else x for i, x in enumerate(data)) & 0xFFFFFFFF | |
x = (x >> 16) + (x & 0xFFFF) | |
x = (x >> 16) + (x & 0xFFFF) | |
return struct.pack('<H', ~x & 0xFFFF) | |
def ping(addr, timeout=1, number=1, data=b''): | |
with socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) as conn: | |
payload = struct.pack('!HH', random.randrange(0, 65536), number) + data | |
conn.connect((addr, 80)) | |
conn.sendall(b'\x08\0' + chk(b'\x08\0\0\0' + payload) + payload) | |
start = time.time() | |
while select.select([conn], [], [], max(0, start + timeout - time.time()))[0]: | |
data = conn.recv(65536) | |
if len(data) < 20 or len(data) < struct.unpack_from('!xxH', data)[0]: | |
continue | |
if data[20:] == b'\0\0' + chk(b'\0\0\0\0' + payload) + payload: | |
return time.time() - start | |
if __name__ == '__main__': | |
print(ping('google.com')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How can a ping a 1400 bytes?