I'm trying to write my own implementation of UDP in ruby for educational purposes using raw sockets.
Here's what I have so far:
require 'socket'
addr = Socket.pack_sockaddr_in(4567, '127.0.0.1')
socket = Socket.new(
Socket::PF_INET,
Socket::SOCK_RAW,
Socket::IPPROTO_RAW
)
socket.bind(addr)
socket.recvfrom(1024)
I am testing it like so:
require 'socket'
udp = UDPSocket.new
udp.send "Hello World", 0, "127.0.0.1", 4567
But the call to recvfrom is blocking indefinitely.
If I change it to this:
socket = Socket.new(
Socket::PF_INET,
Socket::SOCK_DGRAM,
Socket::IPPROTO_UDP
)
It of course works because this is the system-level way to accept UDP packets.
How can I receive UDP packets on a raw socket?
To be clear: I want to handle the actual UDP protocol (decoding the datagram & doing a checksum) myself!