varagrawal
varagrawal

Reputation: 3032

Unable to connect to TCP Server from external machine

I have written a basic TCP server in Rust but I am unable to access it from a different computer on the same network. It is not a network problem since I also wrote a similar Python TCP server and the test client is able to connect to that server successfully.

use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::thread;
use std::str;

fn handle_read(mut stream: TcpStream) {
    let mut buf;
    // clear out the buffer so we don't send garbage
    buf = [0; 512];

    // Read and discard any data from the client since this is a read only server.
    let _ = match stream.read(&mut buf) {
        Err(e) => panic!("Got an error: {}", e),
        Ok(m) => m,
    };

    println!("Got some data");

    // Write back the response to the TCP stream
    match stream.write("This works!".as_bytes()) {
        Err(e) => panic!("Read-Server: Error writing to stream {}", e),
        Ok(_) => (),
    }

}

pub fn read_server() {
    // Create TCP server
    let listener = TcpListener::bind("127.0.0.1:6009").unwrap();
    println!("Read server listening on port 6009 started, ready to accept");

    // Wait for incoming connections and respond accordingly
    for stream in listener.incoming() {
        match stream {
            Err(_) => {
                println!("Got an error");
            }
            Ok(stream) => {

                println!("Received a connection");
                // Spawn a new thread to respond to the connection request
                thread::spawn(move || {
                    handle_read(stream);

                });

            }    
        }

    }
}

fn main() {
    read_server();
}

Upvotes: 1

Views: 2023

Answers (1)

kennytm
kennytm

Reputation: 523734

let listener = TcpListener::bind("127.0.0.1:6009").unwrap();

If you bind to 127.0.0.1:xxxx, the socket can only listen from the localhost interface. To allow external connections, bind to 0.0.0.0 instead, so that it can accept connections from all network interfaces.

let listener = TcpListener::bind("0.0.0.0:6009").unwrap();

See Why would I bind on a different server than 127.0.0.1? for detail.


BTW, (1)

// not idiomatic
let _ = match stream.read(&mut buf) {
    Err(e) => panic!("Got an error: {}", e),
    Ok(m) => m,
};

You could use Result::expect for this.

// better
stream.read(&mut buf).expect("Got an error");

(2)

// not idiomatic
match stream.write("This works!".as_bytes()) {
    Err(e) => panic!("Read-Server: Error writing to stream {}", e),
    Ok(_) => (),
}

instead of "aaa".as_bytes() you could simply write b"aaa".

// better
stream.write(b"This works!").expect("Read-Server: Error writing to stream");

Upvotes: 8

Related Questions