Writing a Go-Based CLI Tool for IP Address Lookup

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Project Setup
  4. Creating the CLI Tool
  5. Usage
  6. Conclusion

Introduction

In this tutorial, we will learn how to create a command-line interface (CLI) tool using the Go programming language. The tool will allow users to perform IP address lookup, retrieving geolocation information associated with the IP address. By the end of this tutorial, you will have a working Go-based CLI tool that can be used to gather information about IP addresses.

Prerequisites

Before getting started, make sure you have the following prerequisites:

  • Basic knowledge of Go programming language
  • Go installed on your machine
  • Familiarity with the command line

Project Setup

Let’s begin by setting up the project structure. Follow the steps below:

  1. Create a new directory for your project:

     mkdir ip-lookup-tool
     cd ip-lookup-tool
    
  2. Initialize a new Go module:

     go mod init github.com/your-username/ip-lookup-tool
    
  3. Create a new Go file named main.go:

     touch main.go
    
  4. Open main.go in a text editor of your choice.

Creating the CLI Tool

In this section, we will write the code to create our CLI tool for IP address lookup.

package main

import (
	"log"
	"os"
	"fmt"
	"net"
)

func main() {
	if len(os.Args) < 2 {
		fmt.Println("Please provide an IP address.")
		os.Exit(1)
	}

	ip := os.Args[1]

	addr, err := net.LookupAddr(ip)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("IP Address: %s\n", ip)
	fmt.Printf("Hostname: %s\n", addr[0])
}

Let’s go through the code step by step:

  • We first check if the user has provided an IP address as a command line argument. If not, we display an error message and exit the program.
  • We store the IP address provided by the user in the ip variable.
  • Using the net.LookupAddr function, we perform an IP address lookup to retrieve the hostname associated with the given IP address.
  • If the lookup is successful, we print the IP address and hostname to the console.

Usage

To use the CLI tool, follow the steps below:

  1. Build the Go executable:

     go build
    
  2. Run the CLI tool with an IP address as an argument:

     ./ip-lookup-tool 8.8.8.8
    

    You should see the output similar to the following:

     IP Address: 8.8.8.8
     Hostname: dns.google
    

    Feel free to replace 8.8.8.8 with any other IP address you want to perform a lookup for.

Conclusion

Congratulations! You have successfully created a Go-based CLI tool for IP address lookup. Throughout this tutorial, we learned how to set up a Go project, write code to perform IP address lookup, and use command-line arguments to provide input to the tool. You can further enhance this tool by adding additional features or error handling mechanisms.

Feel free to explore more functionalities and customize the tool to suit your needs. Happy coding!