Skip to content

Instantly share code, notes, and snippets.

View cmol's full-sized avatar

Claus Lensbøl cmol

View GitHub Profile
require "socket"
CONNECT_ADDR = "localhost"
CONNECT_PORT = 12345
MSG_LENGTH = 256
FLAGS = 0
Addrinfo.udp(CONNECT_ADDR, CONNECT_PORT).connect do |socket|
socket.send("Connected via unspecified address family socket", FLAGS)
message, server = socket.recvfrom(MSG_LENGTH)
cmol@qui-gon:~$ ruby echo_client_udp.rb
[IPv6] Connected via unspecified address family socket
[IPv6] Connected via AF_INET6
[IPv4] Connected via AF_INET
Socket.getaddrinfo(CONNECT_ADDR,CONNECT_PORT, :AF_UNSPEC, :DGRAM).each do | con |
af, port, hostname, ip, pf, sock_type, ipproto = con
Addrinfo.udp(ip, port).connect do |socket|
socket.send("Connected via #{af}", FLAGS)
message, server = socket.recvfrom(MSG_LENGTH)
puts message
end
end
irb(main):003:0> Socket.getaddrinfo("localhost", 12345, :AF_UNSPEC, :DGRAM)
=> [
["AF_INET6", 12345, "::1", "::1", 10, 2, 17],
["AF_INET", 12345, "127.0.0.1", "127.0.0.1", 2, 2, 17]
]
@cmol
cmol / udp_log.rb
Last active October 1, 2020 18:22
addr_info = Addrinfo.new(client)
puts "Client connected from #{addr_info.ip_address} using " +
"#{addr_info.ipv6_v4mapped? ? "IPv4" : "IPv6"}"
require "socket"
LISTEN_ADDR = "::"
LISTEN_PORT = 12345
MSG_LENGTH = 256
FLAGS = 0
# Create socket and bind it to the listen on all addresses and the given port
server_socket = UDPSocket.new :INET6
server_socket.bind(LISTEN_ADDR, LISTEN_PORT)
cmol@qui-gon:~$ ruby src/chat_server_udp.rb
Client connected from ::ffff:127.0.0.1 using IPv4
Client connected from ::1 using IPv6
cmol@qui-gon:~$ nc -4 -u localhost 12345
Hello from IPv4!
[IPv4] Hello from IPv4!
cmol@qui-gon:~$ nc -6 -u localhost 12345
Hello from IPv6!
[IPv6] Hello from IPv6!
cmol@qui-gon:~$ ruby echo_client_udp.rb
[IPv6] Connected via unspecified address family socket
require "socket"
LISTEN_ADDR = "::"
LISTEN_PORT = 12345
MSG_LENGTH = 256
FLAGS = 0
# Create socket and bind it to the listen on all addresses and the given port
server_socket = UDPSocket.new :INET6
server_socket.bind(LISTEN_ADDR, LISTEN_PORT)