python socket Errno 10060 - python

I'm using python socket to connect to a server but sometimes I get this:
error: [Errno 10060] A connection attempt failed because the connected
party did not properly respond after a period of time, or established
connection failed because connected host has failed to respond
when I call the socket.connect method
s= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((self._ipv4address, host_port))
try:
s.connect((dest_ip, dest_port))
except:
raise
Why am I seeing this error? And how do I solve the problem?

You don't need to bind the socket (unless the remote server has an expectation of incoming socket) - it is extremely rare that this would actually be a requirement to connect.
Instead of using sockets to open a website, use urllib2 or mechanize if you need to twiddle forms. They manage cookies, sessions, page state, etc.. Much easier.
Also, if you fail to to connect.. don't give up! Try again, some sites can be pokey to respond. Some may not respond for a while depending - handle it better. Instead of just raising the error, wrap your connection method with an exponential backoff decorator.

Related

Python automatic connection in local network call for WinError 10061

I'm trying to make a program which can automatically connect to a computer in the local network based on the port inputted by the server. then the client, with the same port, tries by using the arp -a command to find every computer in the local network and try to connect to him.
This is the connection Method:
def connect(self):
devices = []
for device in os.popen('arp -a'): devices.append(device)
for ip in devices:
b = re.findall(r"(?:\s|\A)(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(?=\s|\Z)", ip)
try:
print(b[0])
client_socket = socket.socket()
client_socket.settimeout(3)
client_socket.connect((b[0], self.port))
if type(client_socket) != None:
return client_socket
except Exception as e:
print(e)
I get a pretty weird issue: when I try to be a server on one computer, it works out just fine. However, when I try to switch the roles and be the client on that computer, it suddenly cant find the target computer and when it tries its IP (which I know since I checked the IP address of the computer with ipconfig), it errors out:
[WinError 10061] No connection could be made because the target machine actively refused it
timed out
I'm trying this on 2 different computers and it connects perfectly when i try this with this computer as server. Any help would be appreciated.
Edit: Also, I thought it would be helpful to note that no matter how high i set the timeout to be on the socket, it just waits that amount of time with the correct IP, then says it timed out. This is despite the server binding the port already...
Edit 2.0: Thought about looking at connection errors of the connection program at the other computer... completely different. no 10061 errors, just timing out and list index errors which are perfectly understandable with the nature of the function. Why does it only does the 10061 error on one computer? why when its 2 different computers? I'd like to know.

Can't resolve URL until program is restarted

I've got a python script that basically looks something like this:
#############################
# MAIN LOOP
while True:
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
client_socket.connect((url, socketnum))
packet = somedata
client_socket.sendall(packet)
except Exception as e:
# an error occurred
logging.error("An error occurred: {}".format(e))
pass
finally:
logging.info("Closing socket...")
client_socket.close()
time.sleep(70)
What I find is that if this script is run before an internet connection is established on the computer (an embedded Linux system), naturally, when the socket tries to connect, I get "Errno -3 Temporary failure in name resolution". However, if the internet connection is then established, the program STILL cannot resolve the hostname - the only way to get it to work is to restart the python script.
Since this system is not one where I can guarantee the presence of an internet connection at all times, is there anyway to get python to realise that the internet connection now exists and that name resolution information is now available?
EDIT: Some further testing shows that this only happens if the python program is started before any successful internet connection is established on the machine after a boot up. If the python program is started AFTER an internet connection has previously been established on the machine (even if it's subsequently been disconnected), the program operates correctly and will successfully connect to the internet after internet connectivity is restored.
So:
Bootup->Python started->Internet connection established = program doesn't work
Bootup->Internet connection established->Internet disconnected->Python started = program works fine.
Try flushing DNS cache in every iteration.
import os
...
while True:
os.popen('nscd -I hosts',"r")
...
or try service nscd restart command instead.

Python 3.4 - failing to connect to http with urllib

I'm trying to run a simple Python script which connects to a website and reads a document on the website, but it fails. Any help, would be most welcome, thank you!
The code is as follows:
import urllib.request
fhand = urllib.request.urlopen('http://www.py4inf.com/code/romeo.txt')
for line in fhand:
print (line.strip())
And I'm getting the following two error messages:
TimeoutError: [WinError 10060] A connection attempt failed because the
connected party did not properly respond after a period of time, or
established connection failed because connected host has failed to
respond
urllib.error.URLError: {urlopen error [WinError 10060] A connection
attempt failed because the connected party did not properly respond
after a period of time, or established connection failed because
connected host has failed to respond}
This is the windows error, not urllib's one. The latter has a handy default timeout value of never, but the former depends on settings of your proxy (with default being 60 seconds for initial connection and 120 for any further GET requests.
I can't help much with windows, but at least now you know where to look.
I had this same issue, and tried specifying a timeout in the urllib.request.urlopen, but no dice.
What did work was including a header, as described here. The first answer worked, and so did the second, so I used the simpler, second solution.

How is connect() failure notified in epoll?

I am writing a simple test script(python) to test a web server's performance(all this server does is HTTP redirect). Socket is set to non-blocking, and registered to an epoll instance.
How can I know the connect() is failed because the server can't accept more connections? I am currently using EPOLLERR as the indicator. Is this correct?
Edit:
Assumptions:
1) IP layer network unreachability will not be considered.
That catches the case of Connection Refused and other socket errors. Since I assume you are registering for read/write availability (success) upon the pending socket as well, you should also manually time-out those connections which have failed to notify you of read, write, or error availability on the associated file descriptor within an acceptable time limit.
ECONNREFUSED is generally only returned when the server's accept() queue exceeds its limit or when the server isn't even bound to a socket at the remote port. ENETDOWN, EHOSTDOWN, ENETUNREACH, and EHOSTUNREACH are only returned when a lower layer than TCP (e.g., IP) knows it cannot reach the host for some reason, and so they are not particularly helpful for stress testing a web server's performance.
Thus, you need to also bound the time taken to establish a connection with a timeout to cover the full gamut of stress test failure scenarios. Choice of timeout value is up to you.
You can't know it 'failed because the server can't accept more connections', because there is no specific protocol for that condition. You can only know it failed for the usual reasons: ECONNREFUSED, connection timeout, EUNREACH, etc.

Errno 10060 and IMAP4_SSL

I'm trying to write a script that logs into my email server(yahoo) and checks for messages from a certain sender. This is my first time useing the IMAP module and I can't seem to get it to work. Right now I have only a few lines of code.
from imaplib import *
server = IMAP4_SSL('mail.yahoo.com')
server.login('myusername','mypassword')
mail_folders = server.list()
for folders in mail_folders:
print(folders)
at this point all I'm trying to do is login to the mail server and retrieve a list of folders. However I never get connected. the interpreter throws a
[Errno 10060] A connection attempt failed because the connected party did not properly
respond after a period of time, or established connection failed because connected host
has failed to respond
I'm not sure if this has something to do with SSL or what. I have managed to get a connection with httplib.HTTPSConnection, But I would rather use IMAP then webscrape.
I think the problem is just the server name that is wrong. Replacing 'mail.yahoo.com' with 'imap.mail.yahoo.com' worked for me.

Categories

Resources