I'm trying to make a client and server where the client sends a string to the server and the server sends a response back.
This is the method on my client
def send(self):
s = socket.socket()
s.connect(("127.0.0.1", 5012))
message = bytes("Send!", "utf-8")
s.send(message)
data = s.recv(1024)
data = str(data, "utf-8")
print(data)
s.close()
this is a method in the server which waits for client messages.
def listener(self):
print("Startet")
s = socket.socket()
s.bind(("127.0.0.1", 5012))
s.listen(1)
while True:
c, addr = s.accept()
while True:
data = c.recv(1024)
data = str(data, "utf-8")
print(data)
c.send(bytes("OK", "utf-8"))
c.close()
Running this I get:
Startet
Send!
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Anaconda3\lib\threading.py", line 914, in _bootstrap_inner
self.run()
File "C:\Anaconda3\lib\threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "C:\workspace\Server.py", line 41, in listener
data = c.recv(1024)
ConnectionAbortedError: [WinError 10053]
An established connection was disconnected by the software on the hostcomputer
It prints out the Send!, so at least it recieves the messages, but then abruptly stops. The server should be able to run at all times, and take an
arbitrary amount of messages from the clients send function.
The client does a send() and then immediately a recv() without checking if data is available (e.g. using accept()). If the socket is non-blocking the recv() immediately returns (or it excepts for some other reason). An empty string is printed and the socket is closed. That's why the server gives an ConnectionAbortedError, the client has already closed the connection. Check this by adding a try/except around the client recv().
Related
This is a simple TCP server that is made to run at localhost and is made to listen to the port 4160. However, when I execute the code, I get an issue.
The server code that I use is:
import socket
import threading
bind_ip = "127.0.0.1"
bind_port = 4160
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_ip,bind_port))
server.listen(5)
print('[*] Listening on %s:%d'% (bind_ip,bind_port))
def handle_client(client_socket):
request = client_socket.recv(1024)
print('[*] Received: %s' % request)
message = "ACK"
client_socket.sendto(message.encode('utf-8'),bind_ip,4160)
client_socket.close()
while True:
client,addr = server.accept()
print('[*] Accepted connection from: %s:%d' % (addr[0],addr[1]))
client_handler = threading.Thread(target=handle_client,args=(client,))
client_handler.start()
The Error that shows up is:
[*] Listening on 127.0.0.1:24166
[*] Accepted connection from: 127.0.0.1:57455
[*] Received: b'POST /key/1/health HTTP/1.1\r\nHost: localhost:4160\r\n.....
Exception in thread Thread-12:
Traceback (most recent call last):
File "C:\Program Files (x86)\Python35-32\lib\threading.py", line 914, in _bootstrap_inner
self.run()
File "C:\Program Files (x86)\Python35-32\lib\threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "F:/Project Folders/EthicalHacking/Server.py", line 20, in handle_client
client_socket.sendto(message.encode('utf-8'),bind_ip,4160)
TypeError: an integer is required (got type str)
Any help on this will be greatly appreciated.
I think you don't have to use sendto function just use send:
client_socket.send(message.encode('utf-8'))
First, I encountered sockets in Python and faced this problem: when some error in my python code occurs, for example some syntax error before conn.close() on the second script start port is in use. The script already finished, but the socket is still open, kind of like busy socket.
Here is an error just for example:
web#web-X501A1 /var/www $ cd /home/web/www/public/py
web#web-X501A1 ~/www/public/py $ python sockets.py
connected: ('127.0.0.1', 47168)
Traceback (most recent call last):
File "sockets.py", line 164, in <module>
data = re.find('(<onvif>.*<\/onvif>)')
AttributeError: 'module' object has no attribute 'find'
web#web-X501A1 ~/www/public/py $ python sockets.py
Traceback (most recent call last):
File "sockets.py", line 154, in <module>
sock.bind(('', 9090))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use
web#web-X501A1 ~/www/public/py $ python sockets.py
Traceback (most recent call last):
File "sockets.py", line 154, in <module>
sock.bind(('', 9090))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use
Code:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('', 9090))
sock.listen(1)
conn, addr = sock.accept()
try:
print 'connected:', addr
buffer = ''
while True:
buffer += conn.recv(1024)
data = re.find('(<code>.*<\/code>)', buffer)
print data
exit();
if not data:
continue
conn.send(data.upper())
except Exception:
pass
finally:
conn.close()
Enclose the usage of the socket in a try/finally clause. Close the socket in the finally part. Perhaps handle the exception in an except part. Something similar to this:
try:
result = x / y
except ZeroDivisionError:
print "division by zero!"
else:
print "result is", result
finally:
print "executing finally clause"
The problem here is the dirty socket closing which occurs when the script crashes without the proper TCP connection shutdown sequence. Thankfully there's a simple solution which tells the kernel to ignore the fact the socket is already in use (the port it's bound to):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
That's all, add that before the bind call and you're set. Debugging your other errors will be much simpler and less time consuming once that's done ;) See more in the docs https://docs.python.org/2/library/socket.html#socket.socket.setsockopt
If you use netstat -nutap you should notice that you connection seems like it's still up, on a state named TIME_WAIT.
That's part of TCP protocol, and according to wikipedia:
represents waiting for enough time to pass to be sure the remote TCP
received the acknowledgment of its connection termination request.
[According to RFC 793 a connection can stay in TIME-WAIT for a maximum
of four minutes known as a MSL (maximum segment lifetime).]
So, when you try to reconnect immediately to the same port, python complains that this port is still busy and cant be bound yet, saying:
socket.error: [Errno 98] Address already in use
See this old question, where it is asked how to avoid this waiting time.
I am trying to do simple code to send file from the client to the server after saving in t some data.
I am a beginner so I can't figure where the problem is or what is the missing function or line in my code
The Server :
import socket
server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 8000))
server_socket.listen(0)
BUFFER_SIZE = 1024
conn, addr = server_socket.accept()
print ('Got connection from', addr)
while 1:
data = conn.recv(BUFFER_SIZE)
if not data:
break
fileREC=open (data , 'rb')
The Client
import socket
client_socket = socket.socket()
client_socket.connect(("192.168.1.4", 8000))
BUFFER_SIZE = 1024
TextFile= open ("TextFile","w")
TextFile.write("Here is the file")
TextFile.write("Writing data")
TextFile.close()
f=open (TextFile , 'wb')
print ("Writing the file to binart ")
client_socket .send(f)
print ("Data Sent")
The Error
ERROR:Traceback (most recent call last):
File "tenmay.py", line 5, in <module>
client_socket.connect(("192.168.1.4", 8000))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused
Send the contents of the file not the filehandle:
f=open ("TextFile", 'rb')
client_socket.send(f.read())
The second time the client runs the server is waiting to recv data because the accept() command is outside of the loop.
The client could repeatedly send data from a loop, but not if the program ends and has to be restarted.
I'm really new to networking in general and I'm trying to set up a simple exchange between a python server and client.
This is the code for the server
import socket, ssl
def do_something(connstream, data):
print "HALLO"
def deal_with_client(connstream):
data = connstream.read()
# null data means the client is finished with us
while data:
if not do_something(connstream, data):
# we'll assume do_something returns False
# when we're finished with client
break
data = connstream.read()
# finished with client
bindsocket = socket.socket()
bindsocket.bind(('127.0.0.1', 10024))
bindsocket.listen(5)
while True:
newsocket, fromaddr = bindsocket.accept()
print "Setting up connection"
connstream = ssl.wrap_socket(newsocket,
server_side=True,
ca_certs=None,
certfile="cert.pem",
keyfile="privatekey.pem",
ssl_version=ssl.PROTOCOL_TLSv1)
try:
deal_with_client(connstream)
finally:
connstream.shutdown(socket.SHUT_RDWR)
connstream.close()
Here is the code for the client.py
import socket, ssl
clientsocket = socket.socket()
ssl_sock = ssl.wrap_socket(clientsocket,
certfile="cert.pem",
cert_reqs=ssl.CERT_REQUIRED)
ssl_sock.connect(('127.0.0.1', 10024))
print ssl_sock.getpeername()
print ssl_sock.getpeercert()
data = ssl_sock.recv(1024)
ssl_sock.close()
print 'Received', repr(data)
I generated the "cert.pem" and the "privatekey.pem" using openssl.
Traceback (most recent call last):
File "server.py", line 30, in <module>
ssl_version=ssl.PROTOCOL_TLSv1)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 344, in wrap_socket
ciphers=ciphers)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 121, in __init__
self.do_handshake()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 283, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [Errno 8] _ssl.c:499: EOF occurred in violation of protocol
I was wondering if somehow who knows more could point me in the right direction. I really want to do this using SSL btw, but I would be willing to switch to TLS if that is the better approach.
It could be that the sockets are not running with a compatible ssl version, you should put a "ssl.PROTOCOL_TLSv1" compatible version in your client too (or removing it from server and use the default value too).
Googling you can find many examples of socket comunication
The following receiveFile() function reads a filename and file data from the socket and splits it using the delimiter $.
But I am unable to close the socket and a Bad file descriptor error is raised. If I comment out the self.server_socket.close() statement then there is no error but the socket is listening forever.
Code:-
def listen(self):
self.server_socket.listen(10)
while True:
client_socket, address = self.server_socket.accept()
print 'connected to', address
self.receiveFile(client_socket)
def receiveFile(self,sock):
data = sock.recv(1024)
data = data.split("$");
print 'filename', data[0]
f = open(data[0], "wb")
#data = sock.recv(1024)
print 'the data is', data[1]
f.write(data[1])
data = sock.recv(1024)
while (data):
f.write(data)
data=sock.recv(1024)
f.close()
self.server_socket.close()
print 'the data is', data
print "File Downloaded"
Traceback:-
Traceback (most recent call last):
File "server.py", line 45, in <module>
a = Server(1111)
File "server.py", line 15, in __init__
self.listen()
File "server.py", line 20, in listen
client_socket, address = self.server_socket.accept()
File "c:\Python27\lib\socket.py", line 202, in accept
sock, addr = self._sock.accept()
File "c:\Python27\lib\socket.py", line 170, in _dummy
raise error(EBADF, 'Bad file descriptor')
socket.error: [Errno 9] Bad file descriptor
You are closing the server's listening socket, and after that calling again accept() on it.
To finish receiving one file you should close client connection's socket (sock in function receiveFile).
in this code i am trying to shut down the server once file is received
What you'll need is something to break out of the while True loop when you want to shut down the server. A simple solution would be to exploit the exception generated when you close the server socket...
def listen(self):
self.server_socket.listen(10)
while True:
try:
client_socket, address = self.server_socket.accept()
except socket.error:
break
print 'connected to', address
self.receiveFile(client_socket)
print 'shutting down'