I have a very simple Socket Server code running on port 9999. When I fire up my server and client, with netstat I can see that the server is running and the client is on the ephemeral port of 7180.
TCP 192.168.1.117:9999 0.0.0.0:0 LISTENING 7180
However, the output of client shows this error:
Traceback (most recent call last):
File "client.py", line 6, in <module>
clisock.connect((host, 9999))
File "C:\Python27\lib\socket.py", line 222, in meth
return getattr(self._sock,name)(*args)
socket.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
My server code:
import socket
import sys
import time
srvsock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
print 'Server Socket is Created'
host = socket.gethostname()
try:
srvsock.bind( (host, 9999) )
except socket.error , msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
srvsock.listen(5)
print 'Socket is now listening'
while True:
clisock, (remhost, remport) = srvsock.accept()
print 'Connected with ' + remhost + ':' + str(remport)
currentTime = time.ctime(time.time()) + "\r\n"
print currentTime
clisock.send(currentTime)
clisock.close()
srvsock.close()
And my Socket client program is as follow:
import socket
clisock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
print host
clisock.connect((host, 9999))
tm = clisock.recv(1024)
clisock.close()
print tm
What is the issue? Could it be a Firewall or something which cause the connection to drop?
There is no guarantee that socket.gethostname() will return a FQDN. Try to bind the server to '' (empty string is a symbolic name meaning all available interfaces), then connect your client to localhost or 127.0.0.1.
Python documentation includes a very useful example for creating a simple TCP server-client application using low-level socket API [1].
[1] https://docs.python.org/2/library/socket.html#example
Related
I am learning socket programing using Python with simple example. But in local PC client able to connect with server. When I want to test same code in two different computers below is the error.
File "C:\Python27\lib\socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 10060] A connection attempt failed because the connected pa
rty did not properly respond after a period of time, or established connection f
ailed because connected host has failed to respond
Server
import socket
s = socket.socket()
print("after socket creation")
s.bind(("",9999))
hostname = socket.gethostname()
IPAddr = socket.gethostbyname(hostname)
print("IPAddr: "+IPAddr);
print("listening")
s.listen(5)
while True:
clt,adr = s.accept()
print(f"connection to {adr} established")
clt.send(bytes("info from server", "utf-8"))
client
import socket
# host name is output of IPAddr = socket.gethostbyname(hostname) another PC
s = socket.socket()
s.connect((host,9999))
msg = s.recv(100)
print(msg.decode("utf-8"))
Please help me to resolve the issue,Thanks in advance
I am a beginner in socket communication and I wanted to test this code.
I wrote the same code but changed the host in the server to s.gethostname() when both the client and server were on my laptop and worked normally.
server: Laptop
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = ''
port = 62402
s.bind((host,port))
s.listen(5)
while True:
clientsocket, address = s.accept()
print(f"connection from {address} has been established!")
clientsocket.send(bytes("Welcome to the server!","utf-8"))
client: raspberry pi
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 62402
s.connect((host,port))
msg = s.recv(1024)
print(msg.decode('utf-8')
Error
Traceback(most recent call last):
File "/home/pi/Desktop/testting/client.py", line 6, in <module>
s.connect((host,port))
ConnectionRefusedError: [Error 111] Connection refused
Connection refused tells me that [the target] is not accepting the connection.
I don’t think ´socket.gethostname()´ can possibly return the laptop’s hostname in its current form.
´print()´ what it returns - I’d bet it’s the local machine’s hostname (the one creating the connection).
Once you know where you’re connecting to, Things that could go wrong:
Is your target listening for a connection on port 62402?
Will its firewall allow such traffic in?
Below is my server.py file which runs on cloud based ubuntu system.
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostbyname(socket.gethostname())
port = 5555
s.bind((host, port))
s.listen(1)
print("Server started host={} port={}".format(host, port))
while True:
print('>>>>>>>>>> inside the while')
c, addr = s.accept()
print("Got connection from", addr)
c.send(bytes("Thank you", "utf-8"))
Now the below is my local system client.py file :
import socket
s = socket.socket()
s.connect(('my_cloud_server_ip/ssh',5555))
s.recv(1024)
Error which I am getting this:
Traceback (most recent call last):
File "", line 1, in
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
So is there anything wrong with the code or something else?
Thanks in advance.
Try binding to all networks by setting host='0.0.0.0'.
In general I suggest you follow this tutorial Socket Programming in Python (Guide) to use with for starting connections and such.
I have written a client-server python program where the client can send the data to the server. But when the client is trying to connect with the server I am getting the following error.
[Errno 110] Connection timed out
Sending Key to Server
Traceback (most recent call last):
File "client.py", line 43, in <module>
s.send(str(id))
socket.error: [Errno 32] Broken pipe
I tried the following solutions
Broken Pipe error and How to prevent Broken pipe error but none of them solved the issue.
Here are my client and server code
client.py
import socket
import os
import subprocess
from optparse import OptionParser
from random import randint
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket has been successfully created"
except socket.error as err:
print "socket creation failed with error %s" %(err)
# The Manager Address and port
host_ip='192.168.43.123'
port =10106
# Generates a random number say xxxx then its client id becomes 'clxxxx' and home directory made at the server as '/home/clxxxx' with permissions 700
def random_with_N_digits(n):
range_start = 10**(n-1)
range_end = (10**n)-1
return randint(range_start, range_end)
id=random_with_N_digits(4)
id="cl"+ str(id)
# Looks for a public key in .ssh folder if temp.pub not present. If not found generates a ssh public private key and sends it to manager which then copies it to the server
subprocess.call(["bash","keygen.sh"])
#s = socket.socket()
try:
s.connect((host_ip,port))
print "the socket has successfully connected to Backup Server IP == %s" %(host_ip)
except socket.error as err:
print err
f = open('temp.pub','r')
print "Sending Key to Server"
j = "-"
s.send(str(id))
l=f.read(8192)
while(l):
print 'Sending...'
s.send(l)
l = f.read(8192)
try:
client_id=s.recv(1024)
data=s.recv(12)
ip=s.recv(24)
print client_id,
print data, ip
except:
print "An Unknown Error Occurred!"
f.close()
# Writes the parameters of client in the file 'backup_dir.txt'
with open('backup_dir.txt','w') as the_file:
the_file.write(client_id)
the_file.write('\n')
the_file.write(data)
the_file.write('\n')
the_file.write(ip)
the_file.write('\n')
f.close()
s.close()
server.py
import socket
import subprocess
import os
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket has been successfully created"
except socket.error as err:
print "socket creation failed with error %s" %(err)
port = 10106
s.bind(('', port))
print("socket binded to %s port" %port)
s.listen(10)
print("socket is listening")
while(True):
print("waiting for a connection")
c, addr = s.accept()
print("Got a connection from", addr,c)
clientID =(c.recv(8192))
key =(c.recv(8192))
print clientID
print key
with open("temp.pub", 'w') as fp:
fp.write(key)
note=subprocess.check_output("./test_user.sh "+ clientID, shell=True)
note = str(note)
print(len(note))
flag, path, serverIP = note.split(":")
print(flag)
print(path)
print(serverIP)
if flag:
c.send(clientID)
c.send(path)
c.send(serverIP)
os.remove("temp.pub")
else:
c.send("Unable to add Client.")
How do I fix this problem so that the client can send the data to the server without any error?
Thank You in advance.
The error resolved.
It was due to the firewall issue as #RaymondNijland was mentioning, Thanks.
I added the rule in the firewall to allow the following port for Socket Connection and it worked.
sudo ufw allow 10106
Simple client - server app.
#Server use decode
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
s.bind((host,port))
s.listen(5)
while True:
c,addr = s.accept()
print("Got connection from " + str(addr))
ret_val = s.send("Thank you".encode('utf-8'))
print ("ret_val={}".format(ret_val))
c.close()
Client:
#client use decode
from socket import gethostname, socket
serSocket = socket()
server = gethostname()
port = 12345
serSocket.connect((server, port))
data = serSocket.recv(1024)
msg = data.decode('utf-8')
print("Returned Msg from server: <{}>".format(msg))
serSocket.close()
when the server tries to send the following exception occurred
Traceback (most recent call last):
Got connection from ('192.168.177.1', 49755)
File "C:/Users/Oren/PycharmProjects/CientServer/ServerSide/Server2.py", line 16, in <module>
ret_val = s.send("Thank you".encode('utf-8'))
OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
Process finished with exit code 1
As can be seen the client connects the server successfully.
But send fails.
What is the problem?
The problem is that you are sending on the listening socket, not on the connected socket. connect returns a new socket which is the one you must use for data transfer. The listening socket can never be used for sending or receiving data.
Change the send to this and your program will work fine:
ret_val = c.send("Thank you".encode('utf-8'))
(Note c.send, not s.send)