cd /news/developer-tools/show-hn-scapy-for-the-agentic-sre · home › topics › developer-tools › article
[ARTICLE · art-175341] src=github.com ↗ pub= topic=developer-tools verified=true sentiment=· neutral

Show HN: Scapy for the Agentic SRE

A developer released Crafty, a packet-crafting and network-testing tool modeled on Scapy, in which traffic is sent from a real interface and the program reacts to returning packets. Crafty lets users build packets bit by bit or from its own protocol stacks, with internals exposed through a script language: stacks are written as slash-separated layers like /IP(dst=192.0.2.10)/UDP(dst=7), terminal layers such as Raw, Request, Reply, Query and Answer end a stack and send the message, and blocks support repeat loops, expect with timeouts, try/retry error handling and catchable errors including Timeout, Closed, CannotConnect, NoRoute, NoPort, Unset, Invalid, Unresolved and Assertion. In the posted example, a script sends three UDP datagrams to an echo server at 192.0.2.10 port 7 and reports "3 answers out of 3: all back" after 0.3s with status OK, run via sudo crafty --udp 40000-40010 --fw intro.cfty.

key takeaway

Crafty scripts send packets from a real interface and match replies with expect blocks, letting a three-datagram UDP echo test at 192.0.2.10 port 7 report "3 answers out of 3: all back" in 0.3s.

read38 min views5 publishedNov 24, 2026
Show HN: Scapy for the Agentic SRE
Image: Michielbdejong (auto-discovered)

Crafty sends traffic from a real interface and reacts to what comes back, Packets can be crafted to the bit or built by crafty's own stacks, which internals are accessible.

/IP(dst=192.0.2.10)/UDP(dst=7) {
  answers = 0                     # "answers" is a variable holding integers
  repeat var=I count=3 every=100ms {
    Raw("ping ${I}")
    expect timeout=1s Raw {
      answers += 1
      print(MATCH[Raw].data)  # MATCH is the packet that matched
    } else {}                 # after the timeout: a lost answer is no error
  }
  verdict = if answers == 3 { "all back" } else { "some lost" }
  print("${answers} answers out of 3: ${verdict}")
}
% sudo crafty --udp 40000-40010 --fw intro.cfty
...
ping 0
ping 1
ping 2
3 answers out of 3: all back
Done after 0.3s, status: OK.

A stack is layers and their options, separated by slashes, like file paths. An absolute stack starts with /IP (with an Eth layer implied). A relative stack goes on top of the current one.

Some layers are terminal (Raw, Request, Reply, Query, Answer): they end the stack and send the message. An incomplete stack is followed instead, on the same line, by a block of further instructions. A few layers can be both (HttpRequest, HttpAnswer, WebSocket), and are terminal unless followed by a block or a layer. So X/Y { Z } is not X/Y then { Z } on the next line: that sends X/Y (or fails, if Y cannot end a message), then runs Z apart.

The layers of a stack are streams: UDP picks its source port once (from --udp), and every message sent and every pattern on top of it belong to that stream.

An error leaves the enclosing blocks one after the other until an enclosing try handles it or a retry runs its block again; uncaught errors end the program.

Only these errors can be caught: Timeout (of expect or on), Closed (a TCP connection), CannotConnect (writing to a TCP connection refused or timed out), NoRoute, NoPort (no source port left to pick), Unset (getenv, arg, a missing map key or packet layer), Invalid (converting a string or bytes), Unresolved (resolve, hostname) and Assertion (assert). In a handler, ERROR is the message and MATCH the packet that caused the error (the RST or ICMP error refusing a connection), else empty.

n = 1
try {
  n := int(arg(0))
} Unset {}                         # no argument: keep 1
  | Invalid { print_err(ERROR) }   # ERROR is the message
retry Timeout|Closed max=2 {       # retries on these errors only
  /IP(dst=192.0.2.10)/TCP(dst=7) {
    Raw("hello")
    expect timeout=1s Raw { print(MATCH[Raw].data) }
  }
}
target = ip_addr(getenv("TARGET"))  # Read the envvar and cast to an IP, or fail
/IP(dst=target)/UDP(dst=7) {
  Raw("hello")      # two messages on top of the same stack:
  Raw("world")      # the same stream, from the same port
  expect timeout=1s Raw { print(MATCH[Raw].data) }
    | ../ICMP/DestUnreachable(code == PORT_UNREACHABLE) { print("closed") }
}
hello

With dst=8, where nothing listens, it prints closed.

Each leading ../ goes one layer down the current stack: here, ../ is /IP(dst=target) and ../../ is /Eth. Relative stacks reuse opened streams, whereas absolute stacks create new streams: /IP/ICMP/DestUnreachable matches any Dest-Unreachable packet whereas ../ICMP matches only those about the packets of /IP(dst=target).

Like relative patterns, relative stacks can go back with ../ and modify upper layers' options while reusing the stream:

/IP(dst=192.0.2.10)/TCP(dst=7) {
  Raw("ttl 64")
  print("Sent from port ${LAST[TCP].src}")   # LAST is the last packet sent
  ../../IP(ttl=1)/TCP/Raw("ttl 1")
  print("Also sent from port ${LAST[TCP].src}")
  repeat count=2 {
    expect timeout=1s Raw { print(MATCH[Raw].data) }
  }
}
Sent from port 40000
Also sent from port 40000
ttl 64
ttl 1

The rule, for stacks and patterns alike: relative ones stay on the streams of the current stack (../ overlaying some of its layers); absolute ones start anew from Eth. Overlaying can set a temporary value for an earlier option.

So far, streams were self-driven: crafty resolves addresses, connects, retransmits, fragments and reassembles. A bang makes a layer manual, for packets as on the wire: TCP!(flags=SYN, ack_num=0) is a SYN packet with this sequence number regardless of the state of the TCP connection. On reception, IP! sees each fragment and TCP! each segment, even without data.

target = 192.0.2.10
{
  on max=1 linger=1s /IP(src == target)/TCP!(src == 7 && flags & SYN &&
                                               ack_num > 1000 && ack_num <= 2000) {
    print("SYN-ACK: seq ${MATCH[TCP].seq_num}, ack ${MATCH[TCP].ack_num}")
  }
  seg = /IP!(dst=target)/TCP!(src=40000, dst=7, flags=SYN, seq_num=1000)/Raw()
  print("SYN of seq ${seg[TCP].seq_num} sent")
}
% sudo crafty --tcp 40000 --fw syn.cfty
SYN of seq 1000 sent
SYN-ACK: seq 1969569245, ack 1001

encode(STACK) is the bytes of the layers of STACK, all manual, as if sent. An IP or IP6 right below them fills in the checksum of what they carry. This is how to fragment by hand, since no fragment has what the checksum covers:

/IP!(dst=target, id=1234, proto=17) {
  d = encode(UDP(src=4000, dst=7)/Raw(randbytes(100)))
  ../IP!(frag_offset=8)/Raw(d[64:])
  ../IP!(more_frags=true)/Raw(d[:64])
}

crafty [options] file [arg...] or crafty [options] -e program [arg...], where file - is stdin.

What follow the file are the program's own arguments (that are returned by arg(n). With -e, every argument that's not an option is a program's argument, and -- ends the options.

Options:

  • -e PROG : the program itself, rather than a file.
  • -i IFACE : the interface to send from and capture on, rather than that of the default route. Crafty needs root, orsetcap cap_net_raw,cap_net_admin=ep .
  • --routing kernel|manual :kernel (default) uses kernel routes.manual takes gateway from the interface and then does ARP etc.
  • --tcp LO-HI ,--udp LO-HI (repeatable): the ranges to pick source ports from (see alsoBudget, ports and permissions ).
  • --fw : crafty shares the interface's address with the host, whose kernel would answer what crafty receives with TCP resets and ICMP port unreachables.--fw keeps the kernel off the ports of--tcp and--udp .
  • --ip ADDR : an address of crafty's own instead, on the interface's network, for which crafty answers ARP. Then--fw is not needed.
  • -p [/PATTERN] (or--print-packets ): prints the packets à la tcpdump.
  • --format csv|json : change the output format to csv or json (json makes -p print all available details of every packet).
  • --stats : prints the stats of each stream (seestats() ) as it ends.
  • --check : check the program and quit.
  • --max-duration (default: 10m),--max-packets ,--max-bytes ,--max-packets-per-secs ,--max-bytes-per-secs ,--max-syns ,--max-syns-per-secs ,--max-ram : self-imposed budget.
  • --local-ip accept|deny:CIDR ,--remote-ip accept|deny:CIDR (repeatable),--mac-spoofing BOOL ,--exfiltration BOOL ,--promiscuous BOOL : permissions (seeBudget, ports and permissions ).
  • --reference : prints the reference manual.
  • --examples : prints many examples of use.
  • --cliref : exhaustive list of options including seldom used ones.

Exit status: 0 when the program completes, 1 when an error ends it, 2 when it does not compile, 3 when a budget stops it, 4 when it sends what its permissions deny, 130 when interrupted.

  • Use resolve("hostname") to resolve a hostname

  • Errors and warnings go to stderr, all else to stdout: filter stdout as you like, but not stderr (crafty x.cfty | grep ... , not2>&1 | grep )

  • Quote programs as -e '...' or- <<'EOF' , lest the shell expand${}

  • Parameterize your programs with arguments (crafty x.cfty 10.0.0.1 5 , read witharg(0) ,arg(1) ) or environment variables (TARGET=10.0.0.1 crafty x.cfty , read withgetenv("TARGET") ) then cast.

  • When unsure, use --max-duration

  • Crafty is not Python, despite for x in a and comprehensions: only the functions of the reference exist.

  • A statement ends at the end of its line or at a ; . Within parentheses, brackets and braces, after a binary operator, or before anelse ,elsif or| , a new line is plain white space.

  • Comments run from a # to the end of the line. A# followed by a hexadecimal digit is a byte literal instead.

  • Names of layers, fields, functions and keywords are case insensitive. Constants, MATCH ,LAST ,OWN_IP andOWN_IPS are upper case. Variables and constructors are case sensitive.

  • bool :true ,false .

  • int :42 ,-1 ,0x1f ,0o17 ,0b101 .

  • float :1.5 ,2e-3 .

  • byte :#1f .

  • bytes: #deadbeef (an even number of digits). An array of bytes.

  • string :"text ${expr}" .

  • interval :5s ,10ms ,1m30s ,1.5ms ,-2s . Units:d ,h ,m ,s ,ms ,us (orµs ),ns ,ps . Printed in one unit up tos :157.949ms ,8.85159µs ,3725.5s .

  • time :2026-10-20T22:02:45.25Z ,2026-10-20T22:02+02:00 ,2026-10-20T22:02 (local time). Printed in UTC.int(t) andfloat(t) give its unix timestamp,time(secs) the reverse.

  • ip :192.0.2.1 ,2001:db8::1 .

  • mac :aa:bb:cc:dd:ee:ff .

  • cidr :10.0.0.0/8 ,2001:db8::/32 , no bit set beyond the mask.ip in net tells whether an address is in it.

  • arrays: [1, 2, 3] . Items of one type, typed lazily (when that fails:[0s] * 0 ).

  • maps: [192.0.2.1: "gw", ::1: "lo"] , astring[ip] , in no particular order.map(key=k, default=v) is an empty map with keys of the type ofk , where missing keys have the valuev .

  • comprehensions: [e for x in a if c] ,[k: v for x in a if c] ,x being an item of the array or mapa (as{key: k, value: v} ).

  • records: {name: "gw", ip: 192.0.2.1} .{} is an empty block, not a record.

  • variants: Ok(42) ,Failed("timeout") ,Pending . A constructor starts with a capital letter; a bare name that is a variable is the variable. The layers of a packet are variants too, of constructorsIP ,UDP ...

Literals are whole words: 1.2.3.4 is an IP address, 5s an interval.

Strings interpolate any expression: "ttl ${MATCH[IP].ttl - 1}". Escapes: \n, \r, \t, \0, \\, \", \$, \xHH. Interpolated bytes are written in hexadecimal (#68656c6c6f); bytes passed where a string is expected, as to print, are text, as string(b) makes them.

Conversions happen where that make sense: an int to a float, a byte to an int, an IP address or a MAC address to bytes and back, an int to a bool... Bytes compare with the others as bytes. Others use the functions int, float, bool, byte, interval, time, ip_addr, mac_addr and cidr, which also read a string as a literal: ip_addr(getenv("SERVER")). An IPv4 address converts to an int: ip_addr(int(a) + 1). + can concatenate strings and bytes.

Variants need no declaration. Where variants meet (items of an array, branches of an if, values assigned to a variable...), they make one variant with the constructors of all, which case tells apart:

result = Pending   # of type (Failed string | Got int | Pending)
expect Raw("pong") { result := Got(length(MATCH)) }
  | ../ICMP { result := Failed("unreachable") }
print(case result Got { "${I} layers" } else { "${result}" })
  • x = expr declaresx in the current block, with the type ofexpr . An inner block may shadow it.
  • x := expr assigns it, andx += expr (also-= ,*= , etc.) updates it.
  • Predefined: MATCH (in the block of anexpect oron , or a handler oftry ),ERROR (in a handler oftry ),LAST (the last packet sent, once a block has sent one),I , the counter of arepeat ,BUDGET ,PORTS ,PERMISSIONS ,OWN_IPS , the addresses of the interface (or--ip 's), IPv4 ones first, andOWN_IP , the first of them.
  • LAST is the packet as given, not as it left: reading a field that only the wire knows (LAST[Eth].ts , orIP.id ,UDP.checksum ... under a self-drivenIP ) is an error. In contrast,p = MESSAGE captures the packet as it leaves (seeSelf-driven vs manual stacks ).

A program may declare them, once each, at its top level, with literals only:

BUDGET = {max_duration: 30s, max_syns: 30}
PORTS = {tcp: [[40000, 40100]], udp: [[5000, 5000]]}
PERMISSIONS = {local_ips: [Accept(10.20.4.1)],  # spoofs 10.20.4.1
               remote_ips: [Deny(192.0.2.66), Accept(192.0.2.0/24)]}
  • BUDGET 's fields are the budget options of crafty, named alike.
  • max_ram , in bytes.
  • PORTS has ranges[first, last] by protocol; default to no port.
  • crafty runs with what both the program and the command line allow.
  • PERMISSIONS :
    • local_ips ,remote_ips : rulesAccept(x) orDeny(x) ,x being a CIDR orOWN_IP(S) ; the first that matches an address decides, and none matching denies.local_ips always ends withAccept(OWN_IPS) ; unset,remote_ips accepts any. Sending from an address takeslocal_ips accepting it.
    • mac_spoofing : allows sending from another MAC than the interface's.
    • exfiltration : allows sending a payload made of the payload of a received packet or ofgetenv .
    • promiscuous : receives the frames for other addresses too, unlesslocal_ips denies them.
    • A sent packet denied by the above rules stops the program. A received one that is denied is dropped. Received ICMP errors are judged by the packet they quote, not by the router that sent it.

Operators, from the tightest binding to the loosest:

  1. !x ,-x .
  2. * ,/ ,% : on numbers. An array, a byte or a string times an int repeats it.
  3. + ,- : on numbers; a time minus a time is an interval, a time plus an interval (or a number of seconds) is a time.+ also concatenates arrays ([1] + [2, 3] ) and appends or prepends an item ([1, 2] + 3 ,0 + [1, 2] ). To+ , a byte is one-element bytes:#41 + #42 is#4142 . A string plus a string or bytes is a string; usestring(b) for bytes as text.
  4. << ,>> : shift an int or a byte by an int;>> keeps the sign of an int, and a byte stays 8 bits.
  5. & , then^ , then| : bitwise, on ints or bytes.
  6. == ,!= ,< ,<= ,> ,>= , andin (an IP address in a CIDR).
  7. && , then|| .
  8. c ? a : b :a ifc , elseb , computing only that one.

Also: r.field, a[i] (a[-1] is the last item), m[k], f(arg, name=arg), and the layer selectors of Patterns. Arrays, bytes and strings slice as in Python. a[i] := v and m[k] += 1 change an item, adding the key to a map if need be.

Blocks, if, case, expect and try are expressions:

y = if cond 1 else 2
ttl = case var=h MATCH[1] IP { h.ttl } else { 0 }
resp = expect timeout=1s Raw { Got(MATCH[Raw].data) } else { Lost }
rtt = { t0 = now() ; Request("ping") ; expect Reply {} ; now() - t0 }
code = try { MATCH[DestUnreachable].code } Unset { -1 }

Sent messages can be assigned to a variable:

p = /IP!(dst=target)/TCP!(src=1, dst=2, flags=SYN)/Raw()

This sends a packet and waits until it is recaptured on its way out. Its timestamp p[Eth].ts is therefore accurate. Through self-driven layers, p is the first frame that carries some of the message.

Self-driven and manual layers can be mixed with some restrictions: a manual layer cannot carry a self-driven one: IP/TCP! is fine, IP!/TCP is not.

  • /IP/UDP(dst == 7)/Raw :absolute , matched from the interface up.
  • Raw("pong") :relative , on top of the current stack.
  • ../ICMP/DestUnreachable : relative to a layer below the top of the current stack.
  • Raw("pong") | ../ICMP : alternatives.
  • UDP(src == port) : conditions in parentheses are boolean expressions.
  • IP.src is the field of the innermost IP layer, this one included. A path names the layers below the one meant,_ being any one:/IP.src is the first IP'ssrc ,ICMP/_/IP.src the one on top of any ICMP error.
  • A condition that is not a bool compares the default field: Raw("pong") isRaw(data == "pong") .
  • The fields that can be read depend on the mode (see Layers ): a self-drivenTCP shows its ports, a manualTCP! each segment's header.

MATCH is the packet that matched, as an array of layers: MATCH[IP].src, MATCH[Raw].data, with paths as in conditions ( MATCH[/IP], MATCH[ICMP/_/IP]). MATCH[1] and MATCH[ICMP/_] are layers of any allowed kinds, which case tells apart:

for l in MATCH {
  print(case l IP { "IP from ${I.src}" } | UDP { "UDP to ${I.dst}" } else { "other" })
}

LAST, likewise, is the last packet sent. Self-driven layers show their options, what crafty picked (source ports) and their defaults (ttl), but not what their engine computes (checksums).

  • repeat var=v count=n every=d for=d { ... } : runs the blockcount times, or whilefor has not elapsed. An iteration startsevery after the previous one started.v (defaultI ) counts from 0.

  • for v in a every=d for=d { ... } : arepeat over the itemsv of the array or mapa (as{key: k, value: v} ).

  • retry E|E max=n { ... } : runs the block again, up ton times (default 3), while it fails with one of these errors. The last error escapes.

  • try { ... } E|E { ... } | E { ... } else { ... } : runs the block of the first handler naming the error, or else that ofelse (any error that can be caught). Other errors escape.

  • if COND STMT [elsif COND STMT] else STMT : conditionals.

  • case var=v X C { ... } | C { ... } else { ... } : runs the block of the constructor ofX , wherev (defaultI ) is what that constructor holds.

  • break n : leaves then (default 1) innermostrepeat ,for ,on orspawn .

  • continue n : likewise, but goes on with the next iteration of then th (or, for anon , waits for its next match).

  • exit : ends the program successfully, from anywhere.

  • wait d (orsleep d ): s.

  • expect timeout=d PATTERN { ... } | PATTERN { ... } else { ... } : waits for the first packet that matches any pattern, then runs its block; after the timeout (none by default), runselse , or without one fails withTimeout . Its value is that of the block it ran.

  • on for=d linger=d timeout=d max=n PATTERN { ... } | PATTERN { ... } : the enclosing block goes on; each matching packet runs the block of its pattern, repeatedly (max times or unlimited) until its lifetime or that of the enclosing blocks are over.linger (default 0) instructs that enclosing block to wait further.

  • spawn for=d { ... } : runs the block alongside the enclosing one, which goes on. Withfor , the enclosing block waits for at the end, cancelling it afterd ; without, it ends with the statements of the enclosing block.

  • { ... } : a block. Ends once its statements are done, itslinger s waited and itson s andspawn s with afor ended. Leaving a block, normally or on an error, cancels what it still had going.

  • print(x) ,print_err(x) : to stdout, to stderr, as"${x}" (bytes as text).

  • string(x) :x as"${x}" (bytes as text).

  • format(x) : any value as a string, in the format of--format . CSV takes a scalar, or a record, array or map of scalars.

  • summary(x) : return{count, min, mean, stddev, p50, p95, p99, max} from all values inx (key by key ifx is a map or a record).

  • report(x, name=s) : prints the summary ofx according to--format .

  • assert(cond, msg=s) : fails ifcond is false.

  • now() : the current time.

  • stats() : the stats so far of the streams of the current stack. Every stream countspackets_out ,packets_in ,bytes_out ,bytes_in (the payloads at that layer). A self-driven TCP connection counts its segments, retransmissions included, and adds, as Linux'stcp_info :bytes_acked ,bytes_received (in order),retrans ,dupacks ,timeouts ,holes_in (gaps opened in what was received),ooo_in (segments filling a gap withinmin_rtt of the one beyond it),dup_in (segments with only data already receiveds),srtt ,rttvar ,min_rtt ,rtt_samples ,rto ,snd_mss ,rcv_mss ,cwnd ,ssthresh (2^31-1 before any loss),snd_wnd (the peer's window),rcv_wnd ,snd_wscale andrcv_wscale (the window shifts the peer and we offered, -1 if none) andestablished . An IP or IP6 stream addsfragmented ,frags_out ,frags_in ,reassembled andreasm_timeouts (incomplete after 30s, or 60s for IP6).

  • getenv(name, default=s)

  • arg(n, default=s) : the n-th argument after the program, from 0.nargs() : how many there are.

  • resolve(name) : the addresses of a name, IPv4 first, as an array, from the system's resolver. Blocking.

  • hostname(ip, default=s) : the name of an address. Blocking.

  • is_ip4(ip) ,is_ip6(ip)

  • rand(max) : an int or a float in[0, max) (or a bool ifmax istrue )

  • randbytes(len) : random bytes.

  • int(x) ,float(x) ,bool(x) ,byte(x) (the low 8 bits): of intervals, times, or numbers

  • interval(secs) .

  • exp(x) ,ln(x) ,log(x) (base 10).log2(n) .

  • split(s, by) : the parts ofs between the occurrences ofby .

  • array(init=v, len=n) ,length(a) (orcount(a) , of an array, a map or a string),concat(a, b) ,append(a, x) ,prepend(x, a) .

  • range(n) ,range(a, b) : the ints from 0 (ora ) up to, excluding,n (orb ).

  • sorted(a) : a sorted copy.

  • sort(a) : in place.

  • has(m, k) ,remove(m, k) (a copy),keys(m) ,values(m) on mapm .

  • any(a) ,all(a) : of an array of bools or ints, or the values of a map.

  • sum(a) ,min(a) ,max(a) ,mean(a) ,stddev(a) ,percentile(a, p) : of an array, or the values of a map.

  • histogram(a, bucket=b) : the values counted in buckets of widthb from 0, as an array of{min, count, max} ,min andmax being observed values.

  • checksum(b) : the 2 bytes of the Internet checksum ofb (RFC 1071)

  • be16(x) ,le16(x) , all the way to 64: the bytes of an int, big and little endian.

Each field has the modes in which it can be set as an option and read in a condition or in MATCH: M manual, S self-driven. A layer with a single mode is manual. (key) fields tell streams apart.

Every layer but the terminal ones has also length: int; read M; the bytes it carries (TCP!(length > 0): segments with data). Raw has it too: the bytes of its data. Exception: UDP.length is the length field of the header.

  • src : mac; set M; read M, S. Default: the interface's.
  • dst : mac; set M; read M, S. Default: what the interface knows of the next hop of the route (neighbors, gateway), without asking.
  • proto : int; set M; read M, S. Default: the layer on top.
  • ts : time; read M, S. When the frame was captured; for what is reassembled, the frame that completed it. Unset inLAST .

Self-driven, it carries IP and IP6, and finds next hops with ARP and neighbor discovery (or ask the kernel). Eth! frames go out as they are.

  • src (key): ip; set M, S; read M, S. Default: the interface's address (that reachesdst ).
  • dst (key): ip; set M, S; read M, S. Required.
  • proto : int; set M, S; read M, S. Default: the layer on top.
  • tos : int; set M, S; read M, S.
  • ttl : int; set M, S; read M, S. Default 64.
  • dont_frag : bool; set M, S; read M, S. Default false.
  • id : int; set M; read M, S. Default: the stream's counter, from a random value.
  • more_frags : bool; set M; read M.
  • frag_offset : int; set M; read M. In blocks of 8 bytes.
  • tot_len : int; set M; read M. Default: computed.
  • options : bytes; set M, S; read M, S.
  • rr_slots : int; set M, S; read M, S. The slots of the record route option, up to 9, or -1 without one.
  • record_route : ip[]; set M, S; read M, S. The addresses recorded in it. Given, they fill its first slots;rr_slots is then their number unless given.
  • is_fragment : bool; read M.

Self-driven IP fragments to the MTU and reassembles. tos, ttl, dont_frag and options apply to what it sends, but for the segments of a self-driven TCP connection. IP! sends the header as given, but for the checksum.

  • src (key): ip; set M, S; read M, S. Default: the interface's address that reachesdst .
  • dst (key): ip; set M, S; read M, S. Required.
  • proto : int; set M, S; read M, S. Default: the layer on top. Received, that past the extension headers.
  • traffic_class : int; set M, S; read M, S. Default 0.
  • hop_limit : int; set M, S; read M, S. Default 64.
  • flow_label : int; set M; read M, S. Default 0.
  • frag_id : int; set M; read M. Default 0.
  • frag_offset : int; set M; read M. In blocks of 8 bytes. Default 0.
  • more_frags : bool; set M; read M. Default false.
  • is_fragment : bool; read M.

The frag_ fields and more_frags are those of the fragment header: 0 and false without one.

Self-driven IP6 fragments to the MTU and reassembles, as IP.

  • src (key): int; set M, S; read M, S. Default: a port of--tcp .
  • dst (key): int; set M, S; read M, S. Required.
  • seq_num : int; set M; read M.
  • ack_num : int; set M; read M.
  • flags : int; set M; read M. ConstantsFIN ,SYN ,RST ,PSH ,ACK ,URG ,ECE ,CWR .
  • win_size : int; set M; read M.
  • urg_ptr : int; set M; read M.
  • checksum : int; set M; read M. Default: computed, as when 0, but in a fragment (seeencode ).
  • options : bytes; set M; read M. Default: none.
  • mss ,wscale : int; set M, S; read M. The first option of each kind, or -1.
  • ts_val ,ts_ecr : int; set M; read M. Those of the timestamps option, or -1.
  • sack_ok : bool; set M; read M. Whether SACK is permitted.

The fields of the options cannot be given with options. A missing ts_val or ts_ecr is 0. Given -1 they leave it out. Self-driven, mss and wscale are what the connection offers (-1 offers no window scaling, which caps its window at 64KiB).

Self-driven, the first message sent connects, and what follows waits for the connection. A TCP stream created by a pattern accepts the connection instead.

TCP! segments take the sequence and ack numbers, the window and the ACK|PSH flags of the stream's connection when not given, and update them.

  • src (key): int; set M; read M. Default: a port of--udp .

  • dst (key): int; set M; read M. Required, unless told by the layer on top.

  • length : int; set M; read M. Default: computed.

  • checksum : int; set M; read M. Default: computed, as when 0, but in a fragment (seeencode ).

  • type ,code : int; set M; read M. Set by the message on top, but forRaw :ICMP(type=13)/Raw(...) needs atype (code defaults to 0).

  • type ,code : int; set M; read M. As those ofICMP . On top:Echo (128, 129),DestUnreachable (1),PacketTooBig (2),TimeExceeded (3),RouterSolicit (133),RouterAdvert (134),Redirect (137), elseRaw .IP6 computes the checksum.

  • id (key): int; set M; read M. Default: a free random id.

The stream of an echo id, for Request and Reply messages, which count their sequence numbers per stream.

  • seq : int; set M; read M. Default: the stream's counter, from 1.

  • payload : bytes; set M; read M. Default field.

  • code : int; set M; read M. Default 0. Constants:NET_UNREACHABLE ,TTL_EXCEEDED ,PORT_UNREACHABLE6 etc.

  • mtu : int; set M; read M. Not inTimeExceeded ; default 0. Always 0 in aDestUnreachable ofICMP6 .

On top is the quoted IP (IP6 under ICMP6) the error is about, or Raw.

RouterSolicit:

  • src_lla : mac; set M; read M. Default: the interface's.

RouterAdvert:

  • hop_limit : int; set M; read M. Default 64.
  • managed ,other_config : bool; set M; read M. Default false.
  • flags : int; set M; read M. The 6 other bits. Default 0.
  • lifetime : int; set M; read M. Seconds. Default 1800.
  • reachable ,retrans : int; set M; read M. Milliseconds. Default 0.
  • src_lla : mac; set M; read M. Default: the interface's.
  • mtu : int; set M; read M. Default -1.
  • prefixes : records; set M; read M. Default none. Each is{prefix: cidr, on_link: bool, autonomous: bool, valid: int, preferred: int} .

Redirect:

  • target ,dst : ip; set M; read M. Required.
  • target_lla : mac; set M; read M. Default 00:00:00:00:00:00.

All have options: bytes; set M; read M. On top of Redirect is the start of the packet redirected, a quoted IP6 or Raw, cut to a multiple of 8 bytes.

p = {prefix: 2001:db8:1::/64, on_link: true, autonomous: true, valid: 86400, preferred: 14400}
/IP6(dst=ff02::1)/ICMP6/RouterAdvert(mtu=1400, prefixes=[p])

They have the fields of IP, IP6, UDP and TCP (but is_fragment), all readable and settable. They are no streams: a quoted TCP segment is no part of a connection. Errors print them as IP?, IP6?, UDP?, TCP?.

on for=5s /IP/ICMP/TimeExceeded/IP(dst == target)/UDP(dst == 33434) {
  print("from ${MATCH[/IP].src}, ttl ${MATCH[TimeExceeded/IP].ttl}")
}

MATCH[TimeExceeded/IP] is the quoted packet, MATCH[/IP] the error's. A quote is often cut 8 bytes after the IP header: absent fields will read 0. A quoted first fragment has its UDP or TCP on top; a later one, Raw. Sent, a quoted IP or IP6 needs a src and a dst; lengths and checksums are managed.

/IP6(dst=2001:db8::2)/UDP(src=4000, dst=9)/Raw("anyone?")
expect timeout=1s /IP6/ICMP6/DestUnreachable(code == PORT_UNREACHABLE6)/IP6/UDP(src == 4000) {
  print("closed, says ${MATCH[/IP6].src}")
}
  • id (key): int; set M; read M. Default: a free random id.

The stream of a DNS id, for Query and Answer messages.

  • name : string; set M; read M. Default field; required. Without the trailing dot ("example.com" ), but for the root ("." ).
  • type : int; set M; read M. DefaultTYPE_A . ConstantsTYPE_A ,TYPE_NS , etc.
  • class : int; set M; read M. DefaultCLASS_IN .
  • opcode : int; set M; read M. Default 0.
  • authoritative ,truncated ,rec_avail ,authentic_data ,checking_disabled : bool; set M; read M. Default false.
  • rec_desired : bool; set M; read M. Default true.
  • status : int; set M; read M. DefaultNOERROR . ConstantsNOERROR ,FORMERR ,SERVFAIL , etc.
  • answers ,authority ,additional : records; set M; read M. Default none. Each is{name: string, type: int, class: int, ttl: int, data: bytes} ; the data of an A record converts to an IP address.

A message has one question (name, type, class): the first, of a received message with several.

The stream of the HTTP/1.x messages of a TCP connection, then, after a 101 answer received or sent, of its WebSocket frames. On TCP, each is seen once complete; on TCP!, those that fill a segment. An answer without a length ends with the connection (or the segment's FIN). Not seen: the answer to a HEAD (it waits for a body).

  • method : string; set M; read M. OfHttpRequest . Default"GET" .
  • url : string; set M; read M. OfHttpRequest . Default field; default"/" .
  • code : int; set M; read M. OfHttpAnswer . Default field; required.
  • version : string; set M; read M. Default"HTTP/1.1" .
  • headers : records; set M; read M. Default none. Each is{name: string, value: string} , sent in order, as given: give aHost .

Alone, a message has no body; Raw on top is its body, sent as given. Content-Length is added unless a length or Transfer-Encoding header is given. Received, MATCH[Raw].data is the body, dechunked. A 101 answer to a request with a Sec-WebSocket-Key gets its Sec-WebSocket-Accept, unless given.

/IP(dst=192.0.2.10)/TCP(dst=80)/HTTP {
  HttpRequest("/upload", method="POST", headers=[{name: "Host", value: "example.com"}])/Raw("data")
  expect timeout=1s HttpAnswer(code >= 400) { print("refused: ${MATCH[HttpAnswer].code}") }
}
  • url : string; set M. Default field; required. Gives the request line and theHost ; the stack gives the destination. Nowss orhttps : no TLS.
  • version : string; set M. Default"HTTP/1.1" .
  • headers : records; set M. Default none. Added last, replacing those of the same name. Must give aHost ifurl has no host.

The GET asking for a WebSocket. Only sent: it is received, matched and read back (p[HttpRequest]) as an HttpRequest.

  • opcode : int; set M, S; read M, S. Default field; defaultWS_BINARY . ConstantsWS_CONTINUATION ,WS_TEXT ,WS_BINARY ,WS_CLOSE , etc.
  • final : bool; set M; read M. Default true.
  • masked : bool; set M; read M. Default: whether this side sent the request.
  • mask : int; set M; read M. As on the wire (0 if not masked). Default: random.

Raw on top is the payload, unmasked. WebSocket! is each frame, sent as given. WebSocket is each message, its fragments joined, and each close; once a self-driven stack or pattern uses the stream, it answers pings (which it does not show) and a close it did not send.

/IP(dst=192.0.2.10)/TCP(dst=80)/HTTP {
  HttpUpgrade("ws://example.com/chat")
  expect timeout=1s HttpAnswer(101) {}
  WebSocket(WS_TEXT)/Raw("hello")
  expect timeout=1s WebSocket(WS_TEXT) { print(MATCH[Raw].data) }
  WebSocket(WS_CLOSE)
}

Raw (on Eth, IP, TCP, UDP, ICMP, the ICMP errors, the quoted layers, HttpRequest, HttpAnswer and WebSocket, terminal)

  • data : bytes; set M; read M. Default field.

What a layer carries when not decoded further. Sent as given.

/IP(dst=192.0.2.53)/UDP/DNS {
  Query("www.example.com")
  expect timeout=2s Answer(status == NOERROR) {
    a = MATCH[Answer].answers
    assert(length(a) > 0 && a[0].type == TYPE_A, msg="no address")
    /IP(dst=a[0].data)/ICMP/Echo {
      received = 0
      repeat count=5 every=200ms {
        Request("hi")
        expect timeout=1s Reply {
          received += 1
          print("reply from ${MATCH[IP].src}: seq=${MATCH[Reply].seq} ttl=${MATCH[IP].ttl}")
        } else {}
      }
      print("${received} replies out of 5")
    }
  } | Answer {
    assert(false, msg="DNS error ${MATCH[Answer].status}")
  }
}
% sudo crafty --ip 192.0.2.5 ping.cfty
reply from 192.0.2.10: seq=1 ttl=64
...
5 replies out of 5

The replies come back to the Echo stream of the requests, whatever its id.

/IP!(dst=192.0.2.10)/UDP(dst=7) {
  rtts = []
  spawn { repeat every=10s { report(rtts, name="rtt") ; rtts := [] } }
  repeat count=6000 every=10ms {
    p = Raw("probe ${I}")
    expect timeout=500ms Raw("probe ${I}") { rtts += MATCH[Eth].ts - p[Eth].ts } else {}
  }
}

With --format json, each report is a line such as {"type":"report","ts":10.0,"name":"rtt","value":{"count":998,"max":0.0021,"mean":0.0012,...}} (intervals in seconds). The first one, at 0s, has only a count of 0.

/IP!(dst=192.0.2.10)/UDP(dst=7) {
  rtts = []
  repeat count=100 every=10ms {
    p = Raw("probe ${I}")
    expect timeout=500ms Raw("probe ${I}") { rtts += MATCH[Eth].ts - p[Eth].ts } else {}
  }
  print("${length(rtts)}/100 echoed, rtt min ${min(rtts)} median ${percentile(rtts, 50)} p99 ${percentile(rtts, 99)} max ${max(rtts)}")
  for b in histogram(rtts, bucket=1ms) { print("${b.min} to ${b.max}: ${b.count}") }
}
% sudo crafty --ip 192.0.2.5 --udp 40000-40010 rtt.cfty
100/100 echoed, rtt min 4.34351ms median 7.94053ms p99 10.2825ms max 10.6628ms
4.34351ms to 4.77314ms: 8
...

The times are those of the captures, of the probe going out and of its echo coming in. Each probe expects its own echo, so that a late one is not taken for the next.

BUDGET = {max_duration: 61m}
on for=1h /IP/TCP(dst == 80)/HTTP/HttpRequest {
  /IP(dst=MATCH[IP].src)/TCP(src=80, dst=MATCH[TCP].src)/HTTP {
    if MATCH[HttpRequest].url == "/" { HttpAnswer(200)/Raw("hello\n") }
    else { HttpAnswer(404) }
  }
}
% sudo crafty --tcp 80 --fw server.cfty
PERMISSIONS = {exfiltration: true}  # it sends what's sniffed
BUDGET = {max_duration: 61m}
on for=1h /IP/UDP(dst == 7)/Raw {
  /IP(dst=MATCH[IP].src)/UDP(src=7, dst=MATCH[UDP].src)/Raw(MATCH[Raw].data)
}
% sudo crafty --udp 7 --fw server.cfty
target = ip_addr(arg(0))
lost = array(init=25, len=4)
{
  on linger=1s /IP(src == target)/UDP(src == 7, dst >= 40000, dst < 40004) {
    lost[MATCH[UDP].dst - 40000] -= 1
  }
  repeat count=100 every=10ms {
    /IP(dst=target)/UDP(src=40000 + I % 4, dst=7)/Raw("ping")
  }
}
repeat var=f count=4 { print("flow ${f}: ${lost[f]} lost") }
% sudo crafty --udp 40000-40003 --fw losses.cfty
flow 0: 0 lost
...

The on starts listening before the datagrams go out, and goes on 1s after the last one.

/IP(dst=192.0.2.10)/TCP(src=40001, dst=22) {
  Raw("hello")
  expect timeout=1s ../TCP!(flags & RST) { print("reset by ${MATCH[IP].src}") }
}

A reset carries no data, so a pattern on top of TCP never sees it; ../TCP! sees each segment of the connection.

/IP(dst=192.0.2.10)/UDP(dst=7) {
  p = Raw("ping")
  expect timeout=1s Raw { print("rtt: ${MATCH[Eth].ts - p[Eth].ts}") }
}
/IP(dst=192.0.2.10)/TCP(dst=7) {
  Raw("hello")
  expect timeout=1s Raw {
    s = stats()
    print("srtt ${s.srtt}, mss ${s.snd_mss}, peer window ${s.snd_wnd}")
  }
}
/IP(dst=192.0.2.10)/TCP(dst=7) {
  repeat for=10s { Raw(randbytes(1000)) }
  wait 1s             # for what is still buffered or in flight
  s = stats()
  print("${s.bytes_acked} bytes acked, ${s.retrans} retransmitted, srtt ${s.srtt}, cwnd ${s.cwnd}")
}

A write waits while TCP's send buffer is full, so the connection sets the rate; every=10ms would set it to 100 writes per second instead.

/Eth!(dst=ff:ff:ff:ff:ff:ff, proto=0x88b5)/Raw("hello")
/IP!(dst=192.0.2.10, ttl=1, id=1234, dont_frag=true)/UDP(src=40000, dst=9)/Raw(#deadbeef)

Whole programs

target = resolve(arg(0))[0]
probes = int(arg(1, default="5"))      # per hop
max_hops = int(arg(2, default="30"))
port = int(arg(3, default="33434"))
/IP!(dst=target)/UDP(dst=port) {
  probe = 0                       # the IP id, that tells the probes apart
  repeat var=hop count=max_hops {
    rtts = map(key=0.0.0.0, default=[])
    reached = false
    repeat count=probes {
      probe += 1
      p = ../../IP!(ttl=hop + 1, id=probe)/UDP/Raw("probe")
      if probe == 1 { print("to ${target} from UDP port ${p[UDP].src} to ${port}") }
      expect timeout=1s /IP/ICMP/TimeExceeded/IP(id == probe, dst == target)/UDP {
        rtts[MATCH[/IP].src] += MATCH[Eth].ts - p[Eth].ts
      } | /IP/ICMP/DestUnreachable/IP(id == probe, dst == target)/UDP {
        rtts[MATCH[/IP].src] += MATCH[Eth].ts - p[Eth].ts
        reached := true
      } else {}
    }
    head = "${hop + 1}"
    answered = 0
    for r in rtts {
      answered += length(r.value)
      ms = float(int(float(min(r.value)) * 100000.0)) / 100.0
      print("${head}\t${r.key}\t${length(r.value)}/${probes}\tmin ${ms}ms")
      head := ""
    }
    if answered < probes { print("${head}\t*\t${probes - answered}/${probes}") }
    if reached { break }
  }
}
% sudo crafty --udp 40000 --fw lbtrace.cfty 10.2.1.3 8
to 10.2.1.3 from UDP port 40000 to 33434
1	10.1.1.1	8/8	min 0.04ms
2	10.1.0.5	4/8	min 37.67ms
	10.1.0.6	4/8	min 34.92ms
3	10.2.0.1	2/8	min 89.71ms
	10.2.0.2	6/8	min 90.97ms
4	10.2.0.6	8/8	min 117.6ms
5	10.2.1.3	8/8	min 110.92ms

Hops 2 and 3 balance per packet. Behind routers that balance per flow, each hop shows one router, and another port may show another path. A * line counts the probes without an answer.

target = resolve(arg(0))[0]
lo = 68                                         # fits any IPv4 path
hi = int(arg(1, default="1500"))
frag_max = 0                                    # largest fragment of the last reply
ret_mtu = 0                                     # the way back fragmented at this size
{
  on /IP!(src == target && is_fragment) {
    if MATCH[IP].tot_len > frag_max { frag_max := MATCH[IP].tot_len }
  }
  /IP(dst=target, dont_frag=true)/ICMP/Echo {
    size = hi
    repeat count=32 {
      told = 0
      answered = false
      frag_max := 0
      Request(seq=size, payload=#00 * (size - 28))
      expect timeout=1s Reply(seq == size) {
        answered := true
        lo := size
        if frag_max > 0 {
          print("${size}: echoed in fragments of up to ${frag_max} bytes")
          ret_mtu := frag_max
        } else { print("${size}: echoed whole") }
      } | /IP(src != target)/ICMP/DestUnreachable(code == FRAG_NEEDED)/IP(dst == target, tot_len == size) {
        told := MATCH[DestUnreachable].mtu
        answered := true
        print("${size}: too big for ${MATCH[/IP].src}, next hop MTU ${told}")
      } else {}
      if !answered { print("${size}: no answer (dropped one way or the other)") }
      if told > lo && told < size {
        hi := told
        size := told
      } else {
        if !answered || told > 0 { hi := size - 1 }
        if lo >= hi { break }
        size := (lo + hi + 1) / 2
      }
    }
  }
}
print("way out: ${lo} bytes get through")
if ret_mtu > 0 { print("way back: fragmented, MTU about ${ret_mtu} bytes") }
% sudo crafty pmtu.cfty 10.2.1.3
1500: too big for 10.1.0.5, next hop MTU 1400
1400: no answer (dropped one way or the other)
734: echoed whole
1067: echoed whole
1233: echoed whole
1316: no answer (dropped one way or the other)
1274: echoed whole
1295: no answer (dropped one way or the other)
1284: no answer (dropped one way or the other)
1279: echoed whole
1281: no answer (dropped one way or the other)
1280: echoed whole
way out: 1280 bytes get through

10.1.0.5 reports its MTU of 1400, but a router further on drops what exceeds 1280 without a word.

target = resolve(arg(0))[0]
rounds = int(arg(1, default="60"))
per_report = int(arg(2, default="10"))   # rounds per report
pace = interval(arg(3, default="1s"))
max_hops = int(arg(4, default="30"))   # less than 64
port = int(arg(5, default="33434"))
last = max_hops - 1               # the target's hop, from 0, once known
sent = array(init=0, len=max_hops)
rtts = array(init=[], len=max_hops)
hosts = array(init=map(key=0.0.0.0, default=0), len=max_hops)
sent_at = map(key=0, default=now())     # by IP id: round * 64 + hop
/IP!(dst=target)/UDP(dst=port) {
  on /IP/ICMP/TimeExceeded/IP(dst == target)/UDP(dst == port) |
     /IP/ICMP/DestUnreachable(code == PORT_UNREACHABLE)/IP(dst == target)/UDP(dst == port) {
    id = MATCH[ICMP/_/IP].id
    if has(sent_at, id) {
      hop = id % 64
      rtts[hop] += MATCH[Eth].ts - sent_at[id]
      hosts[hop][MATCH[/IP].src] += 1
      if MATCH[/IP].src == target && hop < last { last := hop }
      sent_at := remove(sent_at, id)
    }
  }
  repeat var=r count=rounds + 1 every=pace {
    if r > 0 && r % per_report == 0 {
      print("after ${r} rounds:")
      repeat var=hop count=last + 1 {
        s = sent[hop]
        n = length(rtts[hop])
        line = "${hop + 1}\t${keys(hosts[hop])}\tloss ${(s - n) * 100 / s}%"
        if n > 0 {
          avg = float(int(float(mean(rtts[hop])) * 100000.0)) / 100.0
          best = float(int(float(min(rtts[hop])) * 100000.0)) / 100.0
          worst = float(int(float(max(rtts[hop])) * 100000.0)) / 100.0
          line := "${line}\tavg ${avg}ms\tbest ${best}ms\tworst ${worst}ms"
        }
        print(line)
        sent[hop] := 0
        rtts[hop] := []
        hosts[hop] := map(key=0.0.0.0, default=0)
      }
      sent_at := map(key=0, default=now())    # too late for the next report
    }
    if r < rounds {
      repeat var=hop count=last + 1 {
        id = (r * 64 + hop) % 65536
        p = ../../IP!(ttl=hop + 1, id=id)/UDP/Raw("probe")
        sent_at[id] := p[Eth].ts
        sent[hop] += 1
      }
    }
  }
}
% sudo crafty --udp 40000 --fw mtr.cfty 10.2.1.3 40 20 200ms
after 20 rounds:
1	[10.1.1.1]	loss 0%	avg 0.33ms	best 0.11ms	worst 0.48ms
2	[10.1.0.5]	loss 50%	avg 37.81ms	best 37.6ms	worst 38.1ms
3	[10.2.0.2]	loss 0%	avg 90.91ms	best 90.69ms	worst 91.07ms
4	[10.2.0.6]	loss 10%	avg 114.42ms	best 114.18ms	worst 115.02ms
5	[10.2.1.3]	loss 5%	avg 114.23ms	best 114.09ms	worst 114.73ms
after 40 rounds:
1	[10.1.1.1]	loss 0%	avg 0.33ms	best 0.09ms	worst 0.6ms
2	[10.1.0.5]	loss 45%	avg 37.81ms	best 37.6ms	worst 37.97ms
3	[10.2.0.2]	loss 0%	avg 90.87ms	best 90.68ms	worst 91.3ms
4	[10.2.0.6]	loss 20%	avg 114.47ms	best 114.1ms	worst 116.44ms
5	[10.2.1.3]	loss 15%	avg 114.37ms	best 114.02ms	worst 116.14ms

Hop 2 only answers half of its probes: hop 3 losing none, what is lost is the answers, not the traffic. The losses start between hops 3 and 4, and go on to the target.

── more in #developer-tools 4 stories · sorted by recency
── more on @crafty 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/show-hn-scapy-for-th…] indexed:0 read:38min 2026-11-24 · —