create a udp server on a specific port in rust

To create a UDP server on a specific port in Rust, first, we need to import the necessary libraries:

main.rs
use std::net::UdpSocket;
use std::str;
39 chars
3 lines

Next, we need to create a function that will listen for incoming data on the specified UDP port. We can do this using the UdpSocket module. The code for the function is as follows:

main.rs
fn main() -> std::io::Result<()> {
    let socket = UdpSocket::bind("127.0.0.1:8000")?;
    let mut buffer = [0u8; 1024];

    loop {
        let (number_of_bytes, src_addr) = socket.recv_from(&mut buffer)?;

        let received_string = str::from_utf8(&buffer[..number_of_bytes])?;
        println!("Received {} bytes from {}", number_of_bytes, src_addr);
        println!("{}", received_string);
    }
}
407 chars
13 lines

In this code, we first create a UDP socket and bind it to the IP address and port specified in the bind function call. We then create a buffer of 1024 bytes to hold the incoming data.

We then enter an infinite loop, where we call the recv_from function on the socket to listen for incoming data. The function returns the number of bytes received and the source address of the data.

Next, we convert the received data to a UTF-8 string using str::from_utf8 and print out the number of bytes received as well as the source address and data.

That's it! With this code, you should now have a UDP server listening for incoming data on the specified port in Rust.

related categories

gistlibby LogSnag