DNS resolution, or Domain Name System resolution, is the process of translating human-readable domain names into IP addresses that computers can use to identify each other on a network. The DNS is a hierarchical and distributed naming system for computers, services, or other resources connected to the Internet or a private network.
- User Input:
- A user enters a domain name (e.g., www.example.com) into a web browser or another application.
- Local DNS Cache Check:
- The local device (computer or router) checks its local DNS cache to see if it already has the IP address associated with the requested domain. If the information is found, it can skip the rest of the resolution process.
- Operating System DNS Resolver:
- If the information is not in the local cache, the device’s operating system DNS resolver initiates a query to a DNS server.
- Recursive DNS Server:
- The DNS resolver contacts a recursive DNS server (often provided by the Internet Service Provider or another designated DNS resolver). This server is responsible for resolving the DNS query and might have its own cache of recent resolutions.
- Root DNS Servers:
- If the recursive DNS server doesn’t have the IP address for the requested domain, it queries the root DNS servers. These servers provide information about top-level domains (TLDs) such as “.com,” “.org,” etc.
- TLD DNS Servers:
- The root DNS servers direct the recursive DNS server to the TLD DNS servers responsible for the specific top-level domain of the requested domain (e.g., “.com” for www.example.com).
- Authoritative DNS Servers:
- The TLD DNS servers direct the recursive DNS server to the authoritative DNS servers for the second-level domain (e.g., “example.com”). These authoritative servers have the specific information about the IP address associated with the requested domain.
- IP Address Response:
- The authoritative DNS servers respond to the recursive DNS server with the IP address for the requested domain.
- Caching:
- The recursive DNS server caches the IP address for a certain duration (Time-To-Live or TTL). Subsequent queries for the same domain within the TTL period can be answered directly from the cache.
- Response to Client:
- The recursive DNS server responds to the original DNS resolver with the IP address.
- Client Response:
- The DNS resolver on the local device provides the resolved IP address to the requesting application or device.
- Connection Establishment:
- The client application uses the obtained IP address to establish a connection with the desired server or service.
This hierarchical and distributed nature of DNS resolution helps distribute the load and ensures efficient and reliable domain-to-IP address mappings across the Internet.
Gathering information with sockets involves obtaining details about IP addresses, hostnames, port numbers, and service names.
1. Obtaining IP Address from Hostname:
import socket
hostname = "www.example.com"
ip_address = socket.gethostbyname(hostname)
print(f"IP Address for {hostname}: {ip_address}")2. Obtaining Hostname from IP Address:
import socket
ip_address = "93.184.216.34"
hostname, _, _ = socket.gethostbyaddr(ip_address)
print(f"Hostname for {ip_address}: {hostname}")3. Resolving Service Name to Port Number:
import socket
service_name = "http"
port_number = socket.getservbyname(service_name)
print(f"Port number for {service_name}: {port_number}")4. Resolving Port Number to Service Name:
import socket
port_number = 80
service_name = socket.getservbyport(port_number)
print(f"Service name for port {port_number}: {service_name}")5. Checking Open Ports on a Remote Host:
import socket
def check_open_ports(target_host):
for port_number in range(1, 1025):
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.settimeout(1)
result = client_socket.connect_ex((target_host, port_number))
if result == 0:
service_name = socket.getservbyport(port_number)
print(f"Port {port_number} ({service_name}) is open")
client_socket.close()
target_host = "example.com"
check_open_ports(target_host)These examples showcase how to use the socket module in Python to gather information about IP addresses, hostnames, port numbers, and service names. Keep in mind that some operations, such as port scanning, may require proper authorization and compliance with relevant laws and policies.
Obtain Information from Google DNS
#!/usr/bin/python
import socket
try:
# Get Hostname
print("gethostname:", socket.gethostname())
# Get IP Address by Hostname
print("gethostbyname:", socket.gethostbyname('www.google.com'))
# Get Detailed IP Address Information by Hostname
print("gethostbyname_ex:", socket.gethostbyname_ex('www.google.com'))
# Get Hostname by IP Address
print("gethostbyaddr:", socket.gethostbyaddr('8.8.8.8'))
# Get Fully Qualified Domain Name (FQDN) by Hostname
print("getfqdn:", socket.getfqdn('www.google.com'))
# Get Address Information by Hostname
print("getaddrinfo:", socket.getaddrinfo("www.google.com", None, 0, socket.SOCK_STREAM))
except socket.error as error:
print(str(error))
print("Connection error")Explanation:
- Get Hostname (
socket.gethostname()):- Retrieves the standard host name for the current machine.
- Get IP Address by Hostname (
socket.gethostbyname('www.google.com')):- Resolves a hostname to its corresponding IP address.
- Get Detailed IP Address Information by Hostname (
socket.gethostbyname_ex('www.google.com')):- Provides detailed information about the IP address, including aliases.
- Get Hostname by IP Address (
socket.gethostbyaddr('8.8.8.8')):- Retrieves the primary domain associated with a given IP address.
- Get Fully Qualified Domain Name (FQDN) by Hostname (
socket.getfqdn('www.google.com')):- Returns the fully qualified domain name for a given hostname.
- Get Address Information by Hostname (
socket.getaddrinfo("www.google.com", None, 0, socket.SOCK_STREAM)):- Returns a list of 5-tuples containing information about the address, including family, type, protocol, canonical name, and address.
- Exception Handling:
- Catches any socket-related errors and prints an error message in case of connection issues.
This code demonstrates various socket functions in Python to obtain information about hostnames, IP addresses, and address details. The try-except block helps handle potential socket errors during execution.
Reverse Lookup:
- Definition: Reverse DNS lookup is the process of querying the Domain Name System (DNS) to retrieve a domain name associated with an IP address. In other words, given an IP address, reverse lookup provides the corresponding domain name.
- Use Case: It is commonly used for security and monitoring purposes. For example, if you have an IP address that you want to identify or verify, reverse lookup allows you to find the associated domain or hostname.
- Example: If you have the IP address
8.8.8.8, a reverse lookup would reveal that it is associated with the domain namedns.google.
Direct DNS Resolution:
- Definition: Direct DNS resolution is the process of querying the DNS to obtain information directly related to a given domain name, such as retrieving the corresponding IP address(es) or obtaining other DNS records associated with the domain.
- Use Case: Direct DNS resolution is fundamental for translating human-readable domain names (e.g., www.example.com) into machine-readable IP addresses (e.g., 203.0.113.42). This process is crucial for connecting to servers on the internet using domain names.
- Example: Given the domain name
www.example.com, direct DNS resolution would provide the corresponding IP address(es) associated with that domain.
Reverse lookup involves querying DNS to find the domain name associated with an IP address, while direct DNS resolution involves querying DNS to obtain information directly related to a given domain name, such as its IP address. Both processes are integral parts of how the Domain Name System functions.
Reverse Lookup command
- Shebang Line:
#!/usr/bin/env python- This line is a shebang line, indicating that the script should be executed using the Python interpreter.
- Importing the
socketModule:
import socket- The script imports the
socketmodule, which provides low-level networking support in Python.
- Try-Except Block for Reverse DNS Lookup:
try:
result = socket.gethostbyaddr("8.8.8.8")
print("The host name is:", result[0])
print("Ip addresses:")
for item in result[2]:
print(" " + item)
except socket.error as e:
print("Error for resolving ip address:", e)- The script attempts to perform a reverse DNS lookup for the IP address
8.8.8.8usingsocket.gethostbyaddr. - If successful, it prints the host name and associated IP addresses.
- If an error occurs (e.g., if the IP address cannot be resolved), it catches the
socket.errorexception and prints an error message.
#!/usr/bin/env python
import socket
try :
result = socket.gethostbyaddr("8.8.8.8")
print("The host name is:",result[0])
print("Ip addresses:")
for item in result[2]:
print(" "+item)
except socket.error as e:
print("Error for resolving ip address:",e)This script demonstrates a reverse DNS lookup using the socket.gethostbyaddr function. It takes an IP address (8.8.8.8 in this case), attempts to resolve it to a host name, and prints the result. If there is an error during the resolution process, it catches the exception and prints an error message. The output includes the host name and the associated IP addresses.
Manage socket exceptions
Different type of exceptions are defined in python socket library for different errors.
- Shebang Line:
#!/usr/bin/env python- The shebang line specifies that the script should be executed using the Python interpreter.
- Importing
socketandsysModules:
import socket, sys- The script imports the
socketmodule for socket-related operations and thesysmodule for system-specific functionality.
- Setting Host and Port:
host = "domain/ip_address"
port = 80- The variables
hostandportdefine the target domain or IP address and the port number to connect to, respectively.
- Creating a Socket:
try:
mysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print(mysocket)
mysocket.settimeout(5)
except socket.error as e:
print("Socket create error: %s" % e)
sys.exit(1)- A socket is created using
socket.socketwithsocket.AF_INETindicating IPv4 andsocket.SOCK_STREAMindicating a TCP socket. - The
settimeout(5)sets a timeout of 5 seconds for socket operations.
- Connecting to the Server:
try:
mysocket.connect((host, port))
print(mysocket)
except socket.timeout as e:
print("Timeout %s" % e)
sys.exit(1)
except socket.gaierror as e:
print("Connection error to the server: %s" % e)
sys.exit(1)
except socket.error as e:
print("Connection error: %s" % e)
sys.exit(1)- The script attempts to connect to the specified host and port using
mysocket.connect((host, port)). - It handles potential exceptions, such as
socket.timeoutfor a connection timeout,socket.gaierrorfor a name resolution error, andsocket.errorfor other connection errors. - If an exception occurs, an error message is printed, and the script exits with a status of 1.
#!/usr/bin/env python
import socket,sys
host = "domain/ip_address"
port = 80
try:
mysocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print(mysocket)
mysocket.settimeout(5)
except socket.error as e:
print("socket create error: %s" %e)
sys.exit(1)
try:
mysocket.connect((host,port))
print(mysocket)
except socket.timeout as e :
print("Timeout %s" %e)
sys.exit(1)
except socket.gaierror as e:
print("connection error to the server:%s" %e)
sys.exit(1)
except socket.error as e:
print("Connection error: %s" %e)
sys.exit(1)This script demonstrates the basic steps for creating a socket, setting a timeout, and connecting to a server. It handles various socket-related exceptions and provides error messages in case of issues during the connection process. The output includes the created socket and information about the connection status.