Ruby, Ruby Tutorial

How to block port using Ruby for testing purposes

This post is about using a port so that other applications will not use it in test scenarios. For instance, you have some tests that use a mock web service, and you require ranges of port numbers. So, the idea is to make Ruby block those ports temporarily for ourselves.

Ruby version

For reference, the ruby version we use for this post is 2.3 for Windows.

Of course, we require to install Ruby first, which, unfortunately, is not covered here.

Ruby Codes To Block Ports

Consider the following Ruby codes that make up a simple program. The application accepts a port and opens it up using TCPServer. Since the program will remain running because of the endless loop, the port will remain unavailable for use by other applications.

We get the following output when we run the Ruby program with a random port number as its argument. Note that we can still terminate the program by pressing Ctrl + C.

What if we want Ruby to block more than one port at the same time? We could modify the codes to accept a list of port numbers to open up. Alternatively, we could hard-code those port numbers and run the program once using only one instance.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like

One comment

  1. 1

Comments are closed.