Socket Error: 111 [.connect((host, port))] - python

I am doing a course and it is teaching me socket right now but this code they are showing is not working for me?
import socket
def main():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "localhost"
port = 5000
s.connect((host, port))
print("It works!")
if __name__ == "__main__":
main()
Error:
Traceback (most recent call last):
File "create_connection.py", line 14, in <module>
main()
File "create_connection.py", line 9, in main
s.connect((host, port))
ConnectionRefusedError: [Errno 111] Connection refused
EDIT:
On this video there is nothing listening but there is no error?

Connect request failed with connection refused.
You need a TCP server which is listening on 5000 port.

There should be a server waiting for connection in port 5000, only then it will work. Otherwise this error is expected

Related

WinError 10061 and WinError 10022 in socket programming only on Windows

I have a very simple Python code for bind or connect to a port. it works without any error on Ubuntu and CentOs but I have an error on Windows 10. I turned off the firewall and antivirus but it didn't help.
my code:
import socket
port = 9999
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
try:
s.connect((host,port))
except:
s.bind((host, port))
s.listen(1)
print("I'm a server")
clientsocket, address = s.accept()
else:
print("I'm a client")
error on windows 10:
Traceback (most recent call last):
File "win.py", line 11, in <module>
s.connect((host,port))
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
During the handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "win.py", line 13, in <module>
s.bind((host, port))
OSError: [WinError 10022] An invalid argument was supplied
Edit:
I found my problem is in Try... Except part, if I put this code in two files my problem will solve. But Why? try except don't work correctly in Windows?
The connect() fails because there is no server socket listening at (host,port).
The bind() fails because you can't bind to a hostname, only to an IP address. Unless you want to listen on just a specific network interface, you should bind to 0.0.0.0 to listen on all interfaces.

Socket WinError 10022 but only as an executable on a Networkdrive

I've got an XML file from which I parse a host adress + port. My script is supposed to establish a connection to every host over the given port (only port 22 ATM) to check the availability of the devices. Every host with which a connection is not possible is to be noted in a List.
file = minidom.parse('Sessions.XML')
sessiondata_all = file.getElementsByTagName('SessionData')
failed_ips = []
def check_port(host, port):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind(('', 22))
sock.listen(1)
sock.accept()
if not sock.connect_ex((host, int(port))) == 0:
failed_ips.append(host)
sock.close()
def main():
try:
for sessiondata in sessiondata_all:
host = sessiondata.attributes['Host'].value
port = sessiondata.attributes['Port'].value
print(host + ":" + port)
check_port(host, port)
except Exception as e:
logging.error(traceback.format_exc())
print(failed_ips)
if __name__ == '__main__':
main()
This code is successful if I run it as a .py or .exe (pyinstaller --onefile [Filename.py]) locally. It also works on a networkdrive as a .py but as soon as I try it as an executable I get the following Error:
PS [Directory on the Networkdrive] .\FailedIps.exe
1.1.1.1
ERROR:root:Traceback (most recent call last):
File "FailedIps.py", line 101, in main
File "FailedIps.py", line 68, in check_port
File "socket.py", line 232, in __init__
OSError: [WinError 10022] An invalid argument was supplied
[]
Anybody got an idea what's the matter here? I can't figure it out
Python and Pyinstaller are on current versions
You should swap out
socket.bind(('',22))
to
socket.bind((host,22))

I cant make my python server run with my IPV 4 address

import socket
PORT = 5050
SERVER = "Insert my public IPV4 address here"
ADDR = (SERVER, PORT)
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR) #here is the line I get the error for
The error says:
Traceback (most recent call last):
File "The Directory", line 15, in <module>
server.bind(ADDR)
OSError: [WinError 10049] The requested address is not valid in its context
Can I not use my IPV4 to make the server public?
If not then what do I use?

How to connect to a socket server in my network?

After doing port forwarding on port 50000 on my router now i can connect to my server using a computer from another network :
SERVER CODE :
import socket
s = socket.socket(socket.AF_INET , socket.SOCK_STREAM)
s.bind(("0.0.0.0" , 50000))
s.listen(5)
c , a = s.accept()
CLIENT CODE (that is connected to another network) :
import socket
s = socket.socket(socket.AF_INET , socket.SOCK_STREAM)
s.connect(("my_public_ip" , 50000))
but the problem is that if i try to connect from my network to the server that is on my network (after doing port forwarding) i get an error :
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

socket server on a thread not releasing the port after the process terminates

The following code runs a socket server on a thread. The client socket sends 'client: hello' to the server, and the server socket receives and replies 'server: world'.
import socket
import threading
def server():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('127.0.0.1', 12345))
sock.listen(1)
req, addr = sock.accept()
print req.recv(1024)
req.sendall('server: world')
def client():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('127.0.0.1', 12345))
sock.sendall('client: hello')
print sock.recv(1024)
def main():
t = threading.Thread(target=server)
t.start()
client()
if __name__ == '__main__':
main()
It runs ok as expected the first time, but from the second time, if you do not wait for a good few seconds for the server to release the socket, and if you try this on a Linux machine or Mac (Windows do not get it somehow) you will run into this error:
Traceback (most recent call last):
File "socket_send_receive.py", line 24, in <module>
main()
File "socket_send_receive.py", line 21, in main
client()
File "socket_send_receive.py", line 14, in client
sock.connect(('127.0.0.1', 12345))
File "<string>", line 1, in connect
socket.error: [Errno 111] Connection refused
Exception in thread Thread-1:
Traceback (most recent call last):
File "/home/cxuan/python/2.6/lib/python2.6/threading.py", line 532, in __bootstrap_inner
self.run()
File "/home/cxuan/python/2.6/lib/python2.6/threading.py", line 484, in run
self.__target(*self.__args, **self.__kwargs)
File "socket_send_receive.py", line 6, in server
sock.bind(('127.0.0.1', 12345))
File "<string>", line 1, in bind
error: [Errno 98] Address already in use
I am looking for some insight into why this is happening and if it is possible to be genuinely resolved or what best practice should be adopted.
I know already using this option can be a workaround thanks to the other posts here on stackoverflow.
socket.SO_REUSEADDR
When a socket is closed, it ends up in a state called STATE_WAIT (see this diagram). While the socket is in this state, no one else can use the same address (ip-number/port pair) unless the SO_REUSEADDR option is set on the socket.
See e.g. the Wikipedia article on TCP for more information about how TCP works and the different states.

Categories

Resources