Page cover

Network Host Scan/Discovery

Resolve Hostnames to IPs (Linux example)

You can use tools like nslookup, dig, or host to resolve hostnames into IP addresses.

Automating the Process with a Script:

If you have many hostnames, you can write a simple script to resolve them into IP addresses and output a clean list. It ensures that output is in IPv4 format filtering for valid IPv4 addresses from the nslookup result, ensuring only IPv4 addresses are written to the output file.

Here’s a bash script to do that:

resolve_ips.sh
#!/bin/bash

# Check if both input and output files were provided
if [ $# -ne 2 ]; then
    echo "Usage: $0 <hostname_file> <output_file>"
    exit 1
fi

input_file="$1"
output_file="$2"

# Empty the output file if it already exists
> "$output_file"

# Read each line from the input file
while IFS= read -r line; do
    # Skip empty lines
    if [[ -z "$line" ]]; then
        continue
    fi

    # Check if the line is already a valid IPv4 address
    if [[ $line =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
        echo "$line" >> "$output_file"
    else
        # Resolve the hostname to an IPv4 address using nslookup
        ip=$(nslookup "$line" | grep 'Address:' | grep -oE '([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)' | tail -n 1)
        
        # Check if we got a valid IPv4 address
        if [[ -n $ip ]]; then
            echo "$ip" >> "$output_file"
        else
            echo "Failed to resolve $line to an IPv4 address" >&2
        fi
    fi
done < "$input_file"

echo "Resolved IPs saved to $output_file"

How to Use the Script:

  1. Save the script as resolve_ips.sh:

    nano resolve_ips.sh
  2. Make it executable:

    chmod +x resolve_ips.sh
  3. Run the script with your hostname list file as a parameter:

    ./resolve_ips.sh hostnames.txt resolved_ips.txt
  • This script now takes the file hostnames.txt (or any other file you provide as a parameter) and resolves the hostnames into IPs.

  • The output will be saved to resolved_ips.txt.

Last updated