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.
Related
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.
So I'm running socket.connect in Python to connect to a server like so (some parts removed cuz proprietary info):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.sock.connect(("XXX.XXX.XXX.XXX", XXXX))
except socket.timeout:
DO_SOMETHING
Anyway what's weird is that this only works like 1 out of 10 times. 9 out of 10 times I get an error saying:
"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"
I'm pretty sure I have the network configuration right for both server/client. The fact that it randomly works fine 1 out of 10 times seems to reinforce this. I think the problem is just timing. I think maybe 1 out of 10 times the timeout just so happens to happen after the server responds.
Anyway, I can't change how the server works in my case. Also changing the timeout fields of the socket object in Python does nothing to change this timeout (the timeout stays at a couple seconds, I want to change it to something much longer). This timeout seems to be some lower level Windows thing. Does anyone know how I would change the timeout related to WinError 10060?
I have a Python script to get hostname for a list of IP addresses. The script works when I run from one computer but same script returns error ([Errno 11004] host not found) when run from another computer.
Both computers are W10 (v1809) with same Python version (3.7.4), sitting next to each other and connected to same corporate network. I don't even know where to look at for potential difference. Would appreciate any hints where/what I should be looking or if there's a different way to get hostname from IP.
Here's my code
for ip in ipList:
try:
retVal = socket.gethostbyaddr(ip)
except socket.error as serr:
logger.debug('IP2Host for {} failed with Error {}'.format(ip, serr))
retVal = 'FAILED'
return retVal
This is probably related to network settings.The hostname resolution is usually done by DNS ethernet protocole or hosts file and compare your netwotrk settings (ipconfig /ALL)
check the result of system command nslookup ip in a terminal.
I ran a scan with Zenmap on my linux server and found the following ports to be open
So I went over my python script below and ran it
But I was given this output!
How would this be the case?
Thanks in advance.
Your try block covers a lot of functions, and except is catching everything and calling it "port closed." At minimum, it could be any of the following situations:
Failed to create a socket.
Failed to connect to the server.
Connected but the server disconnected before you tried to send.
Connected and sent, but server disconnected before you tried to recv
Nmap would consider either of the second two as "open" because the initial handshake succeeded. Your script considers them "closed" instead.
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.