Python socket getting the error “connection refused error 111” - python

I have a problem connecting with the socket.
I wrote a code whose purpose is to get the serial number of the hard disk from a client and send it to the server.
If I run the server and the client code on my local machine, it works fine.
When I try to run the server on the real server and the client on the real client (2 different machines) I’m getting the error:
“Connection refused error 111”
This is my client code:
#!/usr/bin/python3
import os, socket
from time import sleep
def serialNumber():
"""Find the product serial number"""
serialtest = "smartctl -a -i /dev/sda2 > /root/Desktop/serialTest.txt"
grepp = "grep 'Serial Number:' /root/Desktop/serialTest.txt > /root/Desktop/NewserialTest.txt"
sedd = "sed -i 's/Serial Number: //g' /root/Desktop/NewserialTest.txt"
os.system(serialtest)
os.system(grepp)
os.system(sedd)
try:
with open (r"/root/Desktop/NewserialTest.txt","r") as data:
global newserial
newserial = data.readline().strip()
except:
return "File not found!"
try:
os.rename(r'/root/Desktop/NewserialTest.txt',rf'/root/Desktop/{newserial}.txt')
os.remove(r"/root/Desktop/serialTest.txt")
except:
return "File not found!"
return ""
print(serialNumber())
try:
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
ip = socket.gethostname()
port = 5555
s.connect((ip,port))
except socket.error as e:
print(f"UNABLE to connect! you got error:\n{e}.")
exit(-1)
try:
with open(rf'/root/Desktop/{newserial}.txt', "rb") as fd:
toSend = fd.read()
s.send(toSend)
except socket.error as e:
print(f"you got error:\n{e}.")
This is my Server code:
#!/usr/bin/python3
import os, socket
from _thread import *
server_socket = socket.socket()
host = socket.gethostname()
port = 5555
try:
server_socket.bind((host, port))
except socket.error as e:
print(f"You have a error:\n{str(e)}")
print("\nWaiting for connection....\n")
server_socket.listen(100)
while True:
# Recive the serial number from the client
sc, address = server_socket.accept()
print(address)
f = open(r'/root/Desktop/LAB_Test/NewserialTest.txt' ,'wb') #open in binary
while (True):
l = sc.recv(1024)
f.write(l)
if not l:
break
f.close()
sc.close()
try:
with open (r'/root/Desktop/LAB_Test/NewserialTest.txt',"r") as data:
global newserial
newserial = data.readline().strip()
except:
print("File not found!")
os.rename(r'/root/Desktop/LAB_Test/NewserialTest.txt',rf'/root/Desktop/LAB_Test/{newserial}.txt')
what could be the problem?

I changed the bind to 0.0.0.0, and now it works.

Related

Python 2.7 UDP Port Scanner

Can you help me with the program now the problem is that when I enter localhost my program cannot find the open port or the closed one, if you really want to help me and you know how to solve it or fix it, please just compile my code separately just for me right now the program for some reason can’t get to receive a message from the host, I searched the entire Internet and can’t find anywhere the scanner has multiple UDP ports
import socket
import sys
# Ask for input
remoteServer = raw_input('Enter a remote host to scan: ')
remoteServerIP = socket.gethostbyname(remoteServer)
print( "-" * 60)
print ('Please wait, scanning remote host', remoteServerIP)
print( "-" * 60)
for port in range(1,1025):
try:
sock=socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
sock.sendto('hello',(remoteServerIP,port))
#sock.settimeout(1)
data, address = sock.recvfrom(1024)
if data != None:
print ('Port {}: Open'.format(port))
else:
print ('Port {}: Closed'.format(port))
sock.close()
except socket.error as sock_err:
if(sock_err.errno == socket.errno.ECONNREFUSED):
print sock_err('Connection refused')
except socket.gaierror:
print 'Hostname could not be resolved. Exiting'
except socket.error:
print "Couldn't connect to server"
except KeyboardInterrupt:
print 'You pressed Ctrl+C'
Need to use ICMP packet.For the program to work, you need to enter python
I publish my code because the answer to this question is practically nonexistent and the task is actually difficult.
import socket
import sys
import subprocess
def getServiceName(port, proto):
try:
name = socket.getservbyport(int(port), proto)
except:
return None
return name
UDP_IP = sys.argv[1]
for RPORT in range(int(sys.argv[2]), int(sys.argv[3])):
MESSAGE = "ping"
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
if client == -1:
print("udp socket creation failed")
sock1 = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
if sock1 == -1:
print("icmp socket creation failed")
try:
client.sendto(MESSAGE.encode('utf_8'), (UDP_IP, RPORT))
sock1.settimeout(1)
data, addr = sock1.recvfrom(1024)
except socket.timeout:
serv = getServiceName(RPORT, 'udp')
if not serv:
pass
else:
print('Port {}: Open'.format(RPORT))
except socket.error as sock_err:
if (sock_err.errno == socket.errno.ECONNREFUSED):
print(sock_err('Connection refused'))
client.close()
sock1.close()

client socket not able to get connected to server socket, [Errno 32] Broken pipe error

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

Send Hex Command in python to instruct a machine to execute an order using TCP/IP Protocol

i am trying to send a Hex commmand "ABBA05B80000AF11" to a machine using TCP/ IP communication , to instruct the machine to execute an order.seems like , the Hex Command i have sent was unable to go through, Can anyone please help me . thank you
import socket
import sys
import struct
import time
import binascii
host = '192.168.1.40'
port = 800
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
inputHex = binascii.unhexlify("ABBA05B80000AF11")
try:
remote_ip = socket.gethostbyname(host)
s.connect((host, port))
except socket.gaierror:
print('Hostname could not be resolved Exiting')
sys.exit()
print('Socket connected to ' + host + ' on ip '+remote_ip)
try:
while True:
s.send(inputHex)
print('Message sent Successfully')
time.sleep(1)
print('sending')
except socket.error:
print('send fail')
` enter code here`sys.exit()
s.close()

an empty file after sending it to tcp server in python

I am new to python and i am trying to make a multithreded tcp server and client to be able to send files between them. I did write some simple codes for these two programs but every time I get empty file on server's site. The file does create in the folder but when I open it it is blank inside. I also tried to send .png files but windows photoviewer doesn't open them saying they are empty. I didn't find anyone encourting such problem so that's why i am asking
Client.py
import socket # Import socket module
HOST = "localhost" # Host address / name
PORT = 2137 # Reserves port for the service
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((HOST, PORT))
fileToSend = open('test.txt', 'rb')
print "File ready to be sent"
l = fileToSend.read(1024)
while l:
print "Sending the file"
client.send(l)
l = fileToSend.read(1024)
fileToSend.close() print "done"
client.close()
Server.py
import socket
from threading import Thread
from SocketServer import ThreadingMixIn
import sys
TCPHOST = "localhost"
TCPPORT = 2137
BUFFER_SIZE = 20
class ClientThread(Thread):
def __init__(self, HOST, PORT):
Thread.__init__(self)
self.HOST = HOST
self.PORT = PORT
print "New thread started for " + HOST + " on port " + str(PORT)
def run(self):
f = open('received.py', 'wb')
while True:
try:
data = conn.recv(1024)
except socket.error, e:
print "Error receiving data: %s" % e
sys.exit(1)
while data:
print "Receiving"
f.write(data)
data = conn.recv(1024)
f.close()
try:
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((TCPHOST, TCPPORT))
print "Socket created"
except socket.error, err:
print "Failed to create socket" % err
threads = []
while True:
server.listen(4)
print "Waiting for connections"
(conn, (HOST, PORT)) = server.accept()
thread = ClientThread(HOST, PORT)
thread.start()
threads.append(thread)
for t in threads:
t.join()
I am not sure what you actually want to do, because I see that you import SocketServer however you are not using it all.
If you are trying to run a simple socket server then the class ClientThread and all the other stuff about threads in that file are not necessary.
The following code in server.py will do the job
import socket
import sys
TCPHOST = "localhost"
TCPPORT = 2137
BUFFER_SIZE = 20
try:
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((TCPHOST, TCPPORT))
server.listen(4)
print "Socket created"
except socket.error, err:
print "Failed to create socket" % err
while True:
print "Waiting for connections"
(conn, (TCPHOST, TCPPORT)) = server.accept()
try:
while True:
data = conn.recv(1024)
f = open('received.py', 'wb')
if data:
print "Receiving " + data
f.write(data)
else:
f.close()
break;
except socket.error, e:
#pass
print "Error receiving data: %s" % e
#sys.exit(1)
finally:
conn.close()
However if you are trying to implement a threaded TCPServer using the ThreadingMixIn then you need to create a class that subclasses SocketServer and override its handle() function
Python documentation is quite helpful on this
https://docs.python.org/3.5/library/socketserver.html
(ThreadingMixin is at the bottom of the page)

Python Server send data not working

I am currently working on a server in Python, the problem I am facing is the client could not retrieve the sent data from server.
The code of the server is:
import sys
import socket
from threading import Thread
allClients=[]
class Client(Thread):
def __init__(self,clientSocket):
Thread.__init__(self)
self.sockfd = clientSocket #socket client
self.name = ""
self.nickName = ""
def newClientConnect(self):
allClients.append(self.sockfd)
while True:
while True:
try:
rm= self.sockfd.recv(1024)
print rm
try:
self.sockfd.sendall("\n Test text to check send.")
print "Data send successfull"
break
except socket.error, e:
print "Could not send data"
break
except ValueError:
self.sockfd.send("\n Could not connect properly")
def run(self):
self.newClientConnect()
self.sockfd.close()
while True:
buff = self.sockfd.recv(1024)
if buff.strip() == 'quit':
self.sockfd.close()
break # Exit when break
else:
self.sendAll(buff)
#Main
if __name__ == "__main__":
#Server Connection to socket:
IP = '127.0.0.1'
PORT = 80
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
print ("Server Started")
try:
serversocket.bind(('',5000))
except ValueError,e:
print e
serversocket.listen(5)
while True:
(clientSocket, address) = serversocket.accept()
print 'New connection from ', address
ct = Client(clientSocket)
ct.start()
__all__ = ['allClients','Client']
#--
And the client connecting is:
import socket
HOST = '192.168.1.4' # The remote host
PORT = 5000 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
data = s.recv(1024)
s.close()
print 'Received', data#repr(data)
In need of a quick solution....
Thanks,
I tested out your code, and when I commented out
rm= self.sockfd.recv(1024)
print rm
it worked fine. Basically the server stopped there to wait for a message that never came. If it still does not work for you, there might be two problems. Either you have a firewall that blocks the connection somehow, or you have old servers running in the background from previous tries that actually wasn't killed. Check your processes if pythonw.exe or equivalent is running when it shouldn't be, and kill it.
To wait for response:
with s.makefile('rb') as f:
data = f.read() # block until the whole response is read
s.close()
There are multiple issues in your code:
nested while True without break
finally: ..close() is executed before except ValueError: ..send
multiple self.sockfd.close()
etc
Also you should probably use .sendall() instead of .send().
your server code is excepting client send something first,
rm= self.sockfd.recv(1024)
but I don't see any in your code
please try send something in your client code
s.connect((HOST, PORT))
s.send("hello")
Short solution
Add a short sleep after connect.
import time
time.sleep(3)

Categories

Resources