Created
December 9, 2016 16:41
-
-
Save lt/f1a706b19964fb4fb2de1caf988c08cb to your computer and use it in GitHub Desktop.
Minimal PHP packet sniffer
This file contains hidden or 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
<?php declare(strict_types=1); | |
$socket = socket_create(AF_INET, SOCK_RAW, SOL_TCP); | |
if (!$socket) { | |
$errorCode = socket_last_error(); | |
throw new \RuntimeException(socket_strerror($errorCode), $errorCode); | |
} | |
const IP_HDR = 'Cversion_ihl/Ctos/ntot_len/nid/nfrag_off/Cttl/Cprotocol/ncheck/Nsaddr/Ndaddr/'; | |
const TCP_HDR = 'nsource/ndest/Nseq/Nack_seq/Cdoff_res/Cflags/nwindow/ncheck/nurg_ptr/'; | |
while (socket_recv($socket, $data, 4096, 0)) { | |
$unpackedIPHeader = unpack(IP_HDR, $data); | |
// TCP check. | |
if ($unpackedIPHeader['protocol'] !== 6) { | |
continue; | |
} | |
$version = $unpackedIPHeader['version_ihl'] >> 4; | |
// IPv4 check. | |
if ($version !== 4) { | |
continue; | |
} | |
$ipHdrLen = ($unpackedIPHeader['version_ihl'] & 0x0f) << 2; | |
// Ignore options data | |
$data = substr($data, $ipHdrLen); | |
$unpackedTCPHeader = unpack(TCP_HDR, $data); | |
$tcpHdrLen = ($unpackedTCPHeader['doff_res'] >> 4) << 2; | |
// Ignore options data | |
$data = substr($data, $tcpHdrLen); | |
var_dump($data); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment