Adding the Port Scanning Functionality
Powerful Command-Line Applications in Go — by Ricardo Gerardi (79 / 127)
👈 Testing the Manage Hosts Subcomman ds | TOC | Using Viper for Configuration Manag ement 👉
Your application is coming along nicely. You can manage hosts on which to execute a port scan. Let’s implement the port scanning functionality now. Let’s start by adding the functionality to the scan package. After that, we’ll implement the subcommand on the command-line tool. Switch to the scan subdirectory:
$ cd scan
$ pwd
/home/ricardo/pragprog.com/rggo/cobra/pScan/scan
Create and edit the file scanHosts.go to hold the code related to the scan functionality. Add the package definition and the import list. For this functionality, you’ll use the package fmt for formatted printing, the package net for network-related functions, and the package time to define timeouts:
cobra/pScan.v5/scan/scanHosts.go
// Package scan provides types and functions to perform TCP port
// scans on a list of hosts
package scan
import (
"fmt"
"net"
"time"
)
Next, define a new custom type PortState that represents the state for a single TCP port. This struct has two fields: Port of type int that corresponds to the TCP port and Open of type state that indicates whether the port is open or closed. You’ll define the type state shortly: