Skip to content

Instantly share code, notes, and snippets.

@bestie
Last active September 25, 2019 15:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bestie/a6a29109015ce13e54ba17eed2bf821d to your computer and use it in GitHub Desktop.
Save bestie/a6a29109015ce13e54ba17eed2bf821d to your computer and use it in GitHub Desktop.
Help me fix this Rust UDP problem :)
require "socket"
rx_port = 2222
tx_port = 2223
host = "localhost"
socket = UDPSocket.new
socket.bind(host, rx_port)
socket.connect(host, tx_port)
puts "Just gonna chill until you send me something"
received = socket.recv(1024)
puts "Yay a packet! #{received}"
require "socket"
rx_port = 2223
tx_port = 2222
host = "localhost"
socket = UDPSocket.new
socket.bind(host, rx_port)
socket.connect(host, tx_port)
socket.send("Hey dorks!", 0)
use std::net::UdpSocket;
fn main() {
let rx_port = 2222;
let tx_port = 2223;
let host = "localhost";
let socket = UdpSocket::bind(format!("{}:{}", host, rx_port))
.expect("Could not bind socket");
socket.connect(format!("{}:{}", host, tx_port))
.expect("Could not connect socket");
let mut buffer = [0; 10];
println!("{:?}", socket);
println!("Just chillin' on the block");
let data = socket.recv(&mut buffer);
println!("Yay a packet! {:?}", data);
}

Rubyist attempts to port code to Rust. Send help.

Question

Why doesn't the Rust UDP listener programme work?

Context

I'm playing with some UDP socket code and also learning Rust.

What you're looking at

In this toy exmaple the listener programme should block waiting to receive a packet and when it does, print the result and exit.

The Ruby code works as I expect but the Rust version of the listener blocks forever apparently not receiving anything.

I've attempted to make these code samples as concise as possible.

Help appreciated!

@bestie
Copy link
Author

bestie commented Sep 25, 2019

It turns out that this is an IPv4 vs IPv6 issue. Rust creates an AF_INET6 socket even with localhost:2222 as the bind address.

Setting the bind address like so makes it work:

    let rx_socket_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), rx_port);

    let socket = UdpSocket::bind(rx_socket_address)
        .expect("Could not bind socket");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment