In this article, we will explore how to build a simple port scanner in Ruby. Port scanning is a technique used to discover open ports on a target system, which can be useful for network security assessments or troubleshooting network connectivity issues.
Before we start building our port scanner, make sure you have Ruby installed on your system. You can check if Ruby is installed by running the following command in your terminal:
ruby -v
If Ruby is not installed, you can download and install it from the official Ruby website.
Now that we have Ruby installed, let's start building our port scanner. We will use the `socket` library in Ruby to create a TCP connection to each port we want to scan. Here's a simple implementation of a port scanner in Ruby:
require 'socket' def scan_port(host, port) begin Timeout.timeout(1) do s = TCPSocket.new(host, port) puts "Port #{port} is open" s.close end rescue Errno::ECONNREFUSED, Errno::ETIMEDOUT puts "Port #{port} is closed" rescue Timeout::Error puts "Port #{port} is filtered" end end host = 'localhost' (1..1024).each do |port| scan_port(host, port) end
In the code above, we define a `scan_port` method that takes a `host` and `port` as arguments. We use the `TCPSocket` class to create a TCP connection to the specified `host` and `port`. If the connection is successful, we print that the port is open. If the connection is refused or times out, we print that the port is closed. If a timeout error occurs, we print that the port is filtered.
To run the port scanner, save the code above to a file (e.g., `port_scanner.rb`) and run it in your terminal:
ruby port_scanner.rb
The port scanner will start scanning ports 1 to 1024 on the localhost. You can modify the `host` and port range to scan ports on a different host or a different range of ports.
Congratulations! You have successfully built a simple port scanner in Ruby. Port scanning is a powerful tool for network administrators and security professionals to identify potential vulnerabilities in their network. Feel free to explore more advanced port scanning techniques and customize the port scanner to suit your specific needs.
© 2024 RailsInsights. All rights reserved.