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 = ''
port = 80
message = "GET / HTTP/1.1\r\n\r\n"

for loop in [ '', '', 'www' ]:
    sckt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        #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

        #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

Do a Reverse Lookup for hostnames

for loop in  ['', '']:

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