Cionnection Refused when running Python script - python

I am running the following python script within Oracle Virtualbox running Kali Linux and keep getting connection refused.
client.py
#!/usr/bin/python3
#client.py
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 8080
client.connect((host, port)) # Connect to our client
msg = client.recv(1024)
client.close()
print (msg.decode('ascii'))
┌──(kali㉿kali)-[~/Downloads]
└─$ python3 client.py
Traceback (most recent call last):
File "/home/kali/Downloads/client.py", line 10, in <module>
client.connect((host, port)) # Connect to our client
ConnectionRefusedError: [Errno 111] Connection refused

I have solved this, the code is correct but I have not created a listner on port 8080.
Create a new python file name server.py and ran it.
Then ran my client.py
#!/usr/bin/python3
#server.py
import socket
host = socket.gethostname()
port = 8080
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host,port))
server.listen(2)
print('Server is listening for incoming connections')
while True:
conn,addr = server.accept()
print("Connection Received from %s" % str(addr))
msg = 'Connection Established'+ "\r\n"
conn.send(msg.encode('ascii'))
conn.close()

Related

nonstop server client connection[Python]

I want to create a server-client connection that the client can always be connected to the server. How can I do it? Please help me. when I was trying, this error occurred.
"ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host"
- code -
server:
import socket
try:
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(1)
conn, addr=s.accept()
while True:
conn.send(("Test message").encode())
print((conn.recv(1024)).decode())
except Exception as error:
print(str(error))
client:
import socket
try:
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((server_host,port))
while True:
print((s.recv(1024)).decode())
s.send(("Test message").encode())
except Exception as error:
print(str(error))
Some reasons cause this error message:
Server reused the connection because it has been idle for too long.
May be Client IP address or Port number not same as Server.
The network between server and client may be temporarily going down.
Server not started at first.
Your code seems to be OK. Did you run the Server at first time then client? Please make sure it. The below code fully tested on my computer.
Server:
import socket
HOST = '127.0.0.1' # (localhost)
PORT = 65432 # Port to listen on
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
while True:
data = conn.recv(1024).decode()
if not data:
break
conn.send(data.encode())
Client
import socket
HOST = '127.0.0.1' # Server's IP address
PORT = 65432 # Server's port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
while True:
s.send(("Hi server, send me back this message please").encode())
data = s.recv(1024).decode()
print('(From Server) :', repr(data))
Note: Run the Server first then Client.
Output:

ConnectionRefusedError: [Errno 61] Connection refused

I am getting the following error message, when I try to execute the Client.py script using the command Python3.7 Client.py
ConnectionRefusedError: [Errno 61] Connection refused
I tried to change the gethostname with 127.0.0.1, but it did not work.
Bellow are my scripts for Client.py and Server.py
Client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(),1234))
msg = s.recv(1024)
print(msg.decode("utf-8"))
Server.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(),1234))
s.listen(5)
while True:
clientsocket,address = s.accept()
print(f"Connection from {address} has been established")
clientsocket.send(bytes("Hello","utf-8"))

Python Socket Programming - ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

I'm doing an assignment regarding socket programming in python using a client and server. I'm currently on windows 10. Before getting into the little details of the assignment, I've been trying to simply connect the server and client.
Every time I try to run the client file, I would get this error
File "tcpclient.py", line 9, in <module>
s.connect((host, port))
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
I have opened the firewall ports and still nothing. I've tried replacing host with '', 0.0.0.0, socket.gethostname() in both the client and server file but the error still persists. I've even tried different port numbers but it made no difference. I've tried running this code on Ubuntu and Max and I get the same error - connection refused. I've been researching for many solutions but I still have yet to find one that works. Any help would be greatly appreciated!
Note: this code was taken online but it's essentially the basis of what I need to accomplish.
tcpclient.py
import socket
host = '127.0.0.1'
port = 80
buffer_size = 1024
text = "Hello, World!"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.send(text)
data = s.recv(buffer_size)
s.close()
print("received data:", data)
tcpserver.py
import socket
host = '127.0.0.1'
port = 80
buffer_size = 20
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
print 'Connection address:', addr
while 1:
data = conn.recv(buffer_size)
if not data: break
print("received data:", data)
conn.send(data) # echo
conn.close()
Just use a different port. Both the client and server should have the same port and host if not it won't work. Make sure to run the server before the client script.
For client.py
import socket
host = '127.0.0.1'
port = 9879
buffer_size = 1024
text = "Hello, World!"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
text = text.encode('utf-8')
s.send(text)
data = s.recv(buffer_size)
s.close()
print("received data:", data)
For server.py
import socket
mysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
buffer_size = 1024
text = "Hello, World!"
mysocket.bind(('127.0.0.1', 9879))
mysocket.listen(5)
(client, (ip,port)) = mysocket.accept()
print(client, port)
client.send(b"knock knock knock, I'm the server")
data = client.recv(buffer_size)
print(data.decode())
mysocket.close()
Just change the port number and it will work and if you are in python3 then you will have to encode and decode as socket recieves and sends only binary strings.
I have succeed in my server!
My server python script is below:
import socket
host='0.0.0.0'
port=2345
s=socket.socket()
s.bind((host,port))
s.listen(2)
while True:
conn,addr=s.accept()
print("Connected by",addr)
data=conn.recv(1024)
print("received data:",data)
conn.send(data)
conn.close()
My Client python script is below:
import socket
s=socket.socket()
host="xx.xx.xx.xx" #This is your Server IP!
port=2345
s.connect((host,port))
s.send(b"hello")
rece=s.recv(1024)
print("Received",rece)
s.close()
There is two points needed to be careful in the script:
1.The host of the Server must is
'0.0.0.0'
So that the python script could user all interfaces in the server
2.I have find the question's error through the prompt:
TypeError: a bytes-like object is required, not 'str'
It means every string message in the 'send' method need to convert to 'bytes-like object',So the correct is
s.send(b"hello")
It is important that this is b'hello' not is 'hello'
I was following a tutorial that used threading to start the server. Once I removed the threading then I was able to connect to it.

Connection attempt failed in my socket client server program

I am new at socket programming. I am trying to make simple client server program, so I wrote this code:
This is the server program.
import socket
HOST = ''
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr=s.accept()
print('Connected by',addr)
while True:
data=conn.recv(1024)
if not data:
break
conn.send(data)
conn.close()
This is client program:
import socket
HOST = '10.87.24.139'
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send('Hello World')
s.close()
print('received', repr(data))
When I run this the client shows this error:
Traceback (most recent call last):
File "C:\Users\James Bond\Desktop\client.py", line 6, in <module>
s.connect((HOST, PORT))
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
Where is the problem? Why did this error occur?

Error: nodename nor servname provided, or not known (python sockets)

I am trying to learn how to use sockets using this tutorial:
https://www.tutorialspoint.com/python/python_networking.htm
I have copied the code from the site into my directory and ran it exactly as was done in the tutorial but got errors. Here is the code from the tutorial.
#!/usr/bin/python # This is server.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = 'localhost' # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print("asdf")
c.send('Thank you for connecting')
c.close() # Close the connection
and client.py
#!/usr/bin/python # This is client.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.connect((host, port))
print s.recv(1024)
s.close # Close the socket when done
These are the console commands I ran:
python server.py &
python client.py
I got this errors after running the command:
Traceback (most recent call last):
File "client.py", line 9, in <module>
s.connect((host, port))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/soc ket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.gaierror: [Errno 8] nodename nor servname provided, or not known
In case this is helpful, the version of python I am using is Python 2.7.10 and I use a mac that is version 10.12.6
Thanks in advance
From the docs of socket.gethostname:
Return a string containing the hostname of the machine where the
Python interpreter is currently executing.
Note: gethostname() doesn’t always return the fully qualified domain
name; use getfqdn() for that.
The host IP is not the same as the hostname. You have a couple of options:
You can either manually assign host to 0.0.0.0 or localhost
You can also query socket.gethostbyname:
host = socket.gethostbyname(socket.gethostname()) # or socket.getfqdn() if the former doesn't work
I did some changes in your code. Here's the server.py
#!/usr/bin/python # This is server.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5)
c,addr= s.accept()
print "Got connection from the ", addr
c.send('Thank you for connecting')
c.close() # Close the connection
Here's the client.py
#!/usr/bin/python # This is client.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.connect((host, port))
msg = (s.recv(1024))
print msg
s.close # Close the socket when done
I hope it will help

Categories