8000 UDP · socketry/socketry Wiki · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
This repository was archived by the owner on Jan 14, 2025. It is now read-only.

UDP

Tony Arcieri edited this page Nov 26, 2016 · 13 revisions

Clients

connect

To connect to a remote UDP server, call the Socketry::UDP::Socket.connect method:

udp_socket = Socketry::UDP::Socket.connect("8.8.8.8", 53)

send

To send a datagram to a remote server, call #send on the Socketry::UDP::Socket instance with a message:

# Make a DNS query with the Ruby standard library's Resolv module
query = Resolv::DNS::Message.new
query.add_question "github.com", Resolv::DNS::Resource::IN::A

# Send the query to the server we connected to earlier
udp_socket.send query.encode

recvfrom

To receive a response from a remote server, call #recvfrom on a Socketry::UDP::Socket instance with the maximum length of a packet you wish to receive:

datagram = udp_socket.recvfrom(512)

This will return a Socketry::UDP::Datagram instance containing the received message.

>> datagram
 => #<Socketry::UDP::Datagram:0x007fd65e0007d0 @message="\x00\x01\x81\x80\x00\x01\x00\x02\x00\x00\x00\x00\x06github\x03com\x00\x00\x01\x00\x01\xC0\f\x00\x01\x00\x01\x00\x00\x00\xB1\x00\x04\xC0\x1E\xFDp\xC0\f\x00\x01\x00\x01\x00\x00\x00\xB1\x00\x04\xC0\x1E\xFDq", @sockaddr=["AF_INET", 53, "8.8.8.8", "8.8.8.8"]>

Calling #message on the datagram object returns the underlying message:

>> Resolv::DNS::Message.decode(datagram.message)
 => #<Resolv::DNS::Message:0x007fd65d082ab0 @id=1, @qr=1, @opcode=0, @aa=0, @tc=0, @rd=1, @ra=1, @rcode=0, @question=[[#<Resolv::DNS::Name: github.com.>, Resolv::DNS::Resource::IN::A]], @answer=[[#<Resolv::DNS::Name: github.com.>, 177, #<Resolv::DNS::Resource::IN::A:0x007fd65d0818e0 @address=#<Resolv::IPv4 192.30.253.112>, @ttl=177>], [#<Resolv::DNS::Name: github.com.>, 177, #<Resolv::DNS::Resource::IN::A:0x007fd65d080d50 @address=#<Resolv::IPv4 192.30.253.113>, @ttl=177>]], @authority=[], @additional=[]>

The #addrinfo method returns the source of the received message:

>> datagram.addrinfo
 => #<Addrinfo: 8.8.8.8:53 UDP>

Servers

bind

To create a UDP server, call the Socketry::UDP::Socket.bind method with the address and port to bind to:

udp_server = Socketry::UDP::Socket.bind("localhost", 12345)

recvfrom

You can now call #recvfrom to receive Socketry::UDP::Datagram messages from clients:

datagram = udp_server.recvfrom(512)

send

To send responses to clients, use the Socketry::UDP::Datagram#addr and #port methods to obtain the destination:

udp_server.send("Response!", host: datagram.remote_addr, port: datagram.remote_port)
Clone this wiki locally
0