Typed binary serializer
- Using
npmnpm i ts-struct
- Using
Yarnyarn add ts-struct
- Using
pnpmpnpm add ts-struct
Model raw packets
import{struct,types}from"ts-struct";exportenumEtherType{Ether=0x00_01,IPv4=0x08_00,ARP=0x08_06,IPv6=0x86_dd}exportclassMacAddressextendsstruct.bigEndian({value: types.bytes(6)}){staticreadonlyTYPE=EtherType.Ether;staticreadonlyDEFAULT=MacAddress.parse("00:00:00:00:00:00");staticparse(address: string){constraw=address.replace(/[:-]/g,"");constvalue=Buffer.from(raw,"hex").slice(0,MacAddress.SIZE);returnnewthis({ value });}getaddress(){return[...this.data.value].map((value)=>value.toString(16).padStart(2,"0")).join(":");}}exportclassIPv4Addressextendsstruct.bigEndian({value: types.bytes(4)}){staticreadonlyTYPE=EtherType.IPv4;staticreadonlyDEFAULT=IPv4Address.from("0.0.0.0");staticfrom(address: string){constraw=address.split(".").map((part)=>Number.parseInt(part,10));constvalue=Buffer.from(raw).slice(0,IPv4Address.SIZE);returnnewthis({ value });}}exportenumARPOperation{REQUEST=0x00_01,REPLY=0x00_02}constnet=Object.freeze({ether: types.enum<EtherType>(types.uint16,EtherType,EtherType.Ether),mac: types.any(MacAddress,MacAddress.DEFAULT.data),ipv4: types.any(IPv4Address,IPv4Address.DEFAULT.data),arpOperation: types.enum<ARPOperation>(types.uint16,ARPOperation,ARPOperation.REPLY)});exportconstEthernet=struct.bigEndian({source: net.mac,target: net.mac,type: net.ether});