This snippet shows you how to detect which network ports are in use on the current machine from a Ruby script
When delpoying web applications that run their own web-servers, it is quite likely that the port you want (normally port 80) will be in use. At the very least, it is only good manners to check first.
Here’s a quick Ruby script that will loop through an array of port numbers and return the first one that is free:
require 'socket'
def find_unused_port
ports = [80, 8000, 8080, 8800, 8088, 8001, 8002, 8003, 8004, 8005, 8006, 8007, 8008]
port = 0
ports.each do |p|
begin
port = p
TCPServer.new('localhost', port) rescue port = 0
if (port > 0) then break; end
end
end
port
end
puts find_unused_port.to_s
It is Ruby because my own applications include a packaged version of the Ruby interpreter. This affords me a great deal of power, being able to execute .rb scripts as part of the install process. You can do similar things in other languages, or, if you don’t mind processing large amounts of text, using the command netstat -a -n, and parsing all that are “LISTENING”.
About
We are a small British company that produces business-oriented software and solutions. These articles are a product of our daily work - information that we think might be useful to share. We hope you find them useful.
Our Software
These are some of our products. Several are open source, some are web-based and others are proprietary:
Categories
- .NET (10)
- Apple (2)
- Business (5)
- CSS (1)
- HTML (2)
- Innovation (4)
- Java (4)
- Javascript (1)
- Leadership (1)
- MySQL (2)
- Oracle (6)
- Postgres (1)
- Programming (5)
- Rails (4)
- Ruby (10)
- SQL Server (9)
- Subversion (1)
- Web (5)
- Windows Server (2)
Archives
- July 2010 (2)
- September 2009 (5)
- August 2009 (1)
- July 2009 (12)
- June 2009 (16)
- May 2009 (3)