Skip to content

Instantly share code, notes, and snippets.

View boxofrad's full-sized avatar

Dan Upton boxofrad

View GitHub Profile
CREATE EXTENSION IF NOT EXISTS pgcrypto;
-- Based roughly on: https://github.com/oklog/ulid
CREATE FUNCTION generate_ulid()
RETURNS TEXT
AS $$
DECLARE
-- Crockford's Base32
encoding BYTEA = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
timestamp BYTEA = E'\\000\\000\\000\\000\\000\\000';
# https://en.wikipedia.org/wiki/List_of_IP_protocol_numbers
UDP_PROTOCOL = 0x11
loop do
data = socket.recv(BUFFER_SIZE).bytes
frame = EthernetFrame.new(data)
next unless frame.ip_packet.protocol == UDP_PROTOCOL &&
frame.ip_packet.udp_datagram.destination_port == 4321
def body
bytes[8, (length - 8)].pack('C*')
end
class UDPDatagram
def source_port
word16(bytes[0], bytes[1])
end
def destination_port
word16(bytes[2], bytes[3])
end
def length
def udp_datagram
UDPDatagram.new(bytes.drop(20))
end
def source_ip_address
bytes[14, 4].join('.')
end
def ihl
bytes[0] & 0xF
end
class IPPacket
attr_reader :bytes
def initialize(bytes)
@bytes = bytes
end
def version
bytes[0] >> 4
end
def data
# Drop the first 14 bytes (MAC Header) and last 4 bytes (CRC Checksum)
IPPacket.new(bytes[14...-4])
end
class EthernetFrame
attr_reader :bytes
def initialize(bytes)
@bytes = bytes
end
def destination_mac
format_mac(bytes[0, 6])
end