1

I am new in socket programming,could someone please tell me what is wrong I am doing here.I am getting this error.This program works fine when I am not calling defining it as a function.The moment I called it from main it is giving me this error.Someone please help!

#!/usr/bin/env python
import socket
import sys
import urlparse
from urlparse import urlparse

def main(url):
  t=url
  o = urlparse(t)
  x=".".join(o.netloc.split(".")[-2:])
  head1= o.path
  host = o.netloc
  port = 80

  try:
     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  except socket.error, msg:
     sys.stderr.write("[ERROR] %s\n" % msg[1])
     sys.exit()
  try:
     sock.connect((host, port))
     except socket.error, msg:
     sys.stderr.write("[ERROR] %s\n" % msg[1])
     sys.exit()
  try:
     sock.send("HEAD %s HTTP/1.0\r\n\r\n" % head1)
  except sock.error:
     sys.exit()   

  s=sock.recv(600)
  sock.shutdown()
  import sys
  sys.exit
  sock.close()
  return s

 x=main("www.google.ca")
 print x

ERROR I get:
Traceback (most recent call last):
File "C:/myserver/cgi-bin/domainsockettest.py", line 47, in <module>
x=main("www.google.ca")
File "C:/myserver/cgi-bin/domainsockettest.py", line 40, in main
s=sock.recv(600)
error: [Errno 10054] An existing connection was forcibly closed by the remote host
Robin Clarke
  • 11
  • 1
  • 2

1 Answers1

1

I suggest you print out your intermediate values until you are sure of what you are doing. Right now it seems that your URL splitting logic is messed up:

>>> o = urlparse.urlparse('www.google.ca')
>>> o.path
'www.google.ca'
>>> o.netloc
''
>>>

Also:

  • Call to sys.exit() is missing parenthesis,
  • You are trying to do something after that exit,
  • Returning closed socket is totally useless.
Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171
  • Hi Nikolai,thanks for your help.I deleted o.netloc instead I am using t=url o = urlparse(t) x=".".join(t.split(".")[-2:])#x will be my domain name. – Robin Clarke Dec 03 '12 at 18:21
  • for returning the received string such as " http 1.1 200 ok" do you suggest any idea please.Thanks in advance. – Robin Clarke Dec 03 '12 at 18:27
  • I don't get your question. Explain more of what you're trying to do, maybe then people can help more. – Nikolai Fetissov Dec 03 '12 at 18:41
  • hi Nikolai,thanks for replying.I am trying to verify an url format.Suppose a user wants to add url in a bookmark page,my script will verify if the url has the right format such as for url "http://www.google.ca/" ,if the user put mistakenly "http/ww.google" or "www.google" ,is their any way I could verify this.I really appreciate your help. – Robin Clarke Dec 03 '12 at 22:07
  • Take a look at answers to this SO question http://stackoverflow.com/questions/7160737/python-how-to-validate-a-url-in-python-malformed-or-not – Nikolai Fetissov Dec 04 '12 at 01:46