How do you find a free TCP server port using Ruby?

I'm trying to create a use-once HTTP server to handle a single callback and need help with finding a free TCP port in Ruby.

This is the skeleton of what I'm doing:

require 'socket'
t = STDIN.read
port = 8081
while s = TCPServer.new('127.0.0.1', port).accept
  puts s.gets
  s.print "HTTP/1.1 200/OK\rContent-type: text/plain\r\n\r\n" + t
  s.close
  exit
end

(It echoes standard input to the first connection and then dies.)

How can I automatically find a free port to listen on?

This seems to be the only way to start a job on a remote server which then calls back with a unique job ID. This job ID can then be queried for status info. Why the original designers couldn't just return the job ID when scheduling the job I'll never know. A single port cannot be used because conflicts with multiple callbacks may occur; in this way the ports are only used for +- 5 seconds.

I guess you could try all ports > 5000 (for example) in sequence. But how will you communicate to the client program what port you are listening to? It seems simpler to decide on a port, and then make it easily configurable, if you need to move your script between different enviroments.

For HTTP, the standard port is 80. Alternative ports i've seen used are 8080, 880 and 8000.

How to Write a Port Scanner in Ruby, Writing a port scanner is a great way to learn the basics of the TCP protocol, which is the transport layer used by Get Free Ruby CheatSheet ports, these are the ports used by the client side of the connection to receive data from the server. Ruby class TCPSocket provides open function to open such a socket. The TCPSocket.open (hosname, port ) opens a TCP connection to hostname on the port. Once you have a socket open, you can read from it like any IO object. When done, remember to close it, as you would close a file.

Pass 0 in for the port number. This will cause the system to pick a port for you out of the ephemeral port range. Once you create the server, you can ask it for its addr, which will contain the port that the server is bound to.

server = TCPServer.new('127.0.0.1', 0)
port = server.addr[1]

How do high traffic sites service more than 65535 TCP connections , , SSH servers use port 22, and so on. Ports from 1024 to 49151 are registered ports. They can be registered with ICANN by organizations for use with their software. Since you’re using a TcpClient, that means you’re checking open TCP ports. There are lots of good objects available in the System.Net.NetworkInformation namespace. Use the IPGlobalProperties object to get to an array of TcpConnectionInformation objects, which you can then interrogate about endpoint IP and port.

It is actually quite easy when you don't try to do everything in one line :-/

require 'socket'
t = STDIN.read

port = 8080 # preferred port
begin
  server = TCPServer.new('127.0.0.1', port)    
rescue Errno::EADDRINUSE
  port = rand(65000 - 1024) + 1024
  retry
end

# Start remote process with the value of port

socket = server.accept
puts socket.gets
socket.print "HTTP/1.1 200/OK\rContent-type: text/plain\r\n\r\n" + t
socket.close

This accomplishes (strong word) the same as the snippet in the question.

Server Basics: What Is A Network Port?, You will learn how to use TCP sockets in Ruby to interact with other servers on the Get Free Ruby CheatSheet To create a TCP socket you can use the TCPSocket class, as parameters you will need the destination IP address and port. You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

You can try random-port, a simple Ruby gem (I'm the author):

require 'random-port'
port = RandomPort::Pool.new.aquire

The best way, though, is to release it afterward:

RandomPort::Pool::SINGLETON.new.acquire do |port|
  # Use the port, it will be returned back
  # to the pool afterward.
end

The pool is thread-safe and it guarantees that the port won't be used by another thread or anywhere else in the app, until it's released.

What Is a Socket? (The Java™ Tutorials > Custom Networking > All , Understand TCP: clients, servers, ports, and sockets. Log in or subscribe for free to enjoy all this course has to offer! We're going to write a Ruby program that takes requests from a browser and returns a web Here's how web servers work​:  You can combine the netstat and tasklist commands to determine what process is using a port on the Windows Server. The following command will show what network traffic is in use at the port level

Maybe you want test weather one port is listening, following is worked for me system('(6<>/dev/tcp/127.0.0.1/9292) &>/dev/null'), return true if 9292 is listening, otherwise, return false.

Ruby Network Programming, An Integer, interpreted as a binary address in host byte order. 5. port. Each server listens for clients calling on one or more ports. A port may be a Fixnum port  The column at the far right lists PIDs, so just find the one that’s bound to the port that you’re trying to troubleshoot. Next, open up Task Manager by right-clicking any open space on your taskbar and choosing “Task Manager.” If you’re using Windows 8 or 10, switch to the “Details” tab in Task Manager.

Understand TCP: clients, servers, ports, and sockets, TCP ruby chat application using ruby and the Socket standard library. The server receives a port which will be our channel for establishing a connection between Get 'PHP & MySQL: Novice to Ninja, 6th Edition' for free. This video shows you how to find the port used by your SQL Server instance. SQL Server is used with The Raiser's Edge, The Financial Edge, The Education Edge, and Blackbaud Student Information System.

Ruby - Socket Programming, socket.listen will listen for connection on the port. As you can see, we could achieve all this in just one line with TCPServer.new . We, ruby  Make the web root directory and port configurable. Add support for POST requests. You could implement CGI by executing a script when it matches the path, or implement the Rack spec to let the server serve Rack apps with call. Reimplement the request loop using GServer (Ruby’s generic threaded server)

Ruby TCP Chat, Here I present code for a TCP server that has proved actually useful in a This is free software ### Placed in the public domain by Joachim Wuttke 2012 require that does _not_ use Ruby threads def initialize( port, timeout, verbose ) @port  1: You should't use anonymous ports (a.k.a. ephemeral ports) to implement a UDP or TCP service. By default, these ports are in the range 32768 - 65535. # ndd /dev/tcp tcp_smallest_anon_port 32768 # ndd /dev/tcp tcp_largest_anon_port 65535 2: Unless your service is running as root or has the required RBAC privilege, you shouldn't use a

Comments
  • See (new) last paragraph of question.
  • This should not be the accepted answer; see stackoverflow.com/a/201528/3528 below.
  • I'm using a basic Socket (not TCPSocket), which doesn't have the addr method. Would you happen to know how I can get the port in this case?
  • Answering my own question, use socket.getsockname.unpack("snA*")[1]
  • Just to nit-pick... Picking randomly like this is an unbounded loop, and can theoretically run for an undefined amount of time on a server; a situation that gets worse the more ports already in use.
  • The question was how to find a free port to use, not whether or not it is a good idea to use a random port.
  • Not all TCP/IP traffic flows through firewalls.