Python – Socket module – DNS lookup, Reverse DNS lookup

Scripts that show some examples on how to use the SOCKET module.

Do a FQDN search through a series of IPs.

import socket
from netaddr import *
import pprint


#Creating a socket


#URLs and port is defined along with the message we want to send.
#url = 'www.google.com'
port = 80
message = "GET / HTTP/1.1\r\n\r\n"

for loop in [ 'www.google.com', 'www.yahoo.com', 'www' ]:
    sckt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        #The FQN is being resolved and the IP is being printed
        remote_ip = socket.gethostbyname(loop)
        #print remote_ip
        print "Able to resolve to %s " % loop
    except socket.error, msg:
        #print "ERROR1: %s %s" % (socket.error, msg)
        print "Unable to resolve %s " % loop

    try:
        #We are connecting with the remote site by using the IP
        sckt.connect((remote_ip, port))
        print "Able to connect to %s " % loop
    except socket.gaierror, msg:
        #print "ERROR2: %s %s" % (socket.error, msg)
        print "Cannot connect to %s " % remote_ip


    #You can send a reply regardless if the site is up or not.
    #This is not a good at all indicator for if a site is down or not.
  # try:
  #     #We are sending data worth of 4096 kbs
  #     sckt.sendall(message)
  #     reply = sckt.recv(4096)
  #     #print reply
  #     print "Able to send reply"

  # except socket.error, msg:
  #     #print "ERROR3: %s %s" % (socket.error, msg)
  #     print "Error3"


#We are closing our socket
        sckt.close()

Do a Reverse Lookup for hostnames

for loop in  ['10.0.0.6', '10.0.0.60']:

    try:
        dns = socket.gethostbyaddr(loop)
        print dns
    except socket.error, msg:
        print "%s" % msg
Share Button