Search code examples
telnet

How can telnet connect to an arbitrary port?


Through telnet I am able to connect to any server at any port, how does it work? Is there a telnet server daemon running on that server? If there is, shouldn't the daemon listen on a specific port? why can I connect to an arbitrary port on that server? Why can I telnet to 127.0.0.1 at 80 port and get a response from my Nginx without a telnet daemon running on my Ubuntu?


Solution

  • The telnet client doesn't do any special processing. It opens a TCP connection to the remote server on any port you specify, forwards through this connection anything you type and puts on screen anything that it receives from the server.

    When you telnet 127.0.0.1 80 it opens a connection to port 80 of localhost where usually a web server is already listening (nginx in your case).

    An HTTP client knows how to craft an HTTP request and send it through the connection. The telnet client doesn't know anything about HTTP but if you know the protocol you can manually craft a request and type it and the telnet client will happily send it for you through the connection. If the program at the other end (the web server) understands the request it will send a response back. Again, the telnet client doesn't understand a bit of the response (it's just data to it) but it happily puts the response on screen.

    You can use telnet to connect to any port of a (remote or local) computer, as long as there is a server application that is listening on that port.

    There is a telnet server, it usually listens on port 23 if I remember correctly and when a connection is established to it it launches a pseudo-terminal program that handles a login session on the server (the exact program it launches to handle the session depends on the OS). If the login succeeds, the telnet client then talks with the pseudo-terminal program that passes the keys you type to a remote shell; the output produced by the shell goes back to you through the pseudo-terminal -> TCP connection -> telnet client.

    The telnet server is deprecated by the SSH protocol that does the same thing (and many others) but everything that goes through the connection is encrypted on each end before sending and decrypted on the other end before being used. This adds privacy and security to the services already provided by the telnet server.

    The telnet client, however, is still useful because it can be used to test the functionality of servers that use unencrypted text protocols like HTTP, SMTP, POP3, IMAP etc.