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'))
Related
so I'm trying to create a server and client system that takes in inputs from the clients and displays it on the server-side , but I'm running into an issue that I can only send 1 input signal per client and then I get
File "client.py", line 25, in <module>
send(input())
File "client.py", line 20, in send
client.send(message)
BrokenPipeError: [Errno 32] Broken pipe
and on the server side i get the following message when sending an input message
[STARTING] server is starting ...
[LISTENING] server is listening on 127.0.1.1
[NEW CONNECTION] ('127.0.0.1', 60468) connected.
[active connections] 1
[('127.0.0.1', 60468)] hello
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/usr/lib/python3.8/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "server.py", line 21, in handle_client
msg_length = connection.recv(HEADER).decode(FORMAT)
OSError: [Errno 9] Bad file descriptor
the server file
import socket
import threading
PORT = 5054
HEADER = 64
SERVER = socket.gethostbyname(socket.gethostname())
ADDRESS = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MSG= "DISCONNECT"
serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serv.bind(ADDRESS)
def handle_client(connection,addr):
print(f"[NEW CONNECTION] {addr} connected.")
connected = True
while connected:
msg_length = connection.recv(HEADER).decode(FORMAT)
if msg_length :
msg_length = int(msg_length)
msg = connection.recv(msg_length).decode(FORMAT)
if msg == DISCONNECT_MSG:
connected = False
print(f"[{addr}] {msg}")
connection.close()
def start():
serv.listen()
print(f"[LISTENING] server is listening on {SERVER}")
while True:
connection,addr = serv.accept()
thread = threading.Thread(target=handle_client, args=(connection,addr))
thread.start()
print(f"[active connections] {threading.active_count()-1}")
print("[STARTING] server is starting ...")
start()
and the client file is
import socket
PORT = 5054
HEADER = 64
SERVER = socket.gethostbyname(socket.gethostname())
ADDRESS = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MSG= "DISCONNECT"
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDRESS)
def send(msg):
message = msg.encode(FORMAT)
msg_length = len (message)
send_length = str(msg_length).encode(FORMAT)
send_length += b' ' * (HEADER - len(send_length))
client.send(send_length)
client.send(message)
while True:
send(input())
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().
I wrote this code that functions properly on Windows but gives a few errors on my Ubuntu 12.04. Although the code performs well its intended function but its given some errors which I don't want.. Kindly help me in this regard..
from socket import *
from threading import Thread
from Crypto.Cipher import AES
import os
import base64
import timeit
# Receiveing + Decoding the Information, symmetrical key isi
def clientHandler():
conn, addr = s.accept()
print addr, "is connected"
while 1:
data = conn.recv(1024)
if not data:
break
print "Metering Data Received: Processing..."
#creating decoding unpadding
PADDING ="{"
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)
#creating a default key
obj2 = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
decrypted_data = DecodeAES(obj2,data)
print decrypted_data
HOST = "" #localhost
PORT = 12000
s = socket(AF_INET, SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(4)
print "Server is runnig"
#Thread(target=clientHandler).start()
#Thread(target=clientHandler).start()
#Thread(target=clientHandler).start()
for i in range(4):
Thread(target=clientHandler).start()
s.close()
And this is what appears on the terminal of Ubuntu but not on Windows based...
Server is runnig
Exception in thread Thread-4:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 551, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 504, in run
self.__target(*self.__args, **self.__kwargs)
File "chat_encrypt.py", line 10, in clientHandler
conn, addr = s.accept()
File "/usr/lib/python2.7/socket.py", line 202, in accept
sock, addr = self._sock.accept()
File "/usr/lib/python2.7/socket.py", line 170, in _dummy
raise error(EBADF, 'Bad file descriptor')
error: [Errno 9] Bad file descriptor
for i in range(4):
Thread(target=clientHandler).start()
s.close()
The last line closes the socket ... which each thread then tries to 'accept'.
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'
I am getting error when trying to run Python socket http server.
import SocketServer
class MyTCPHandler(SocketServer.BaseRequestHandler):
"""
The RequestHandler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print "{} wrote:".format(self.client_address[0])
print self.data
# just send back the same data, but upper-cased
self.request.send(self.data.upper())
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
# Create the server, binding to localhost on port 9999
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
Error:
C:\Python25>python index.py
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 2506)
Traceback (most recent call last):
File "C:\Python25\lib\SocketServer.py", line 222, in handle_request
self.process_request(request, client_address)
File "C:\Python25\lib\SocketServer.py", line 241, in process_request
self.finish_request(request, client_address)
File "C:\Python25\lib\SocketServer.py", line 254, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "C:\Python25\lib\SocketServer.py", line 521, in __init__
self.handle()
File "index.py", line 15, in handle
print "{} wrote:".format(self.client_address[0])
AttributeError: 'str' object has no attribute 'format'
----------------------------------------
And my client:
import socket
import sys
HOST, PORT = "localhost", 9999
data = " ".join(sys.argv[1:])
# Create a socket (SOCK_STREAM means a TCP socket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connect to server and send data
sock.connect((HOST, PORT))
sock.send(data + "\n")
# Receive data from the server and shut down
received = sock.recv(1024)
finally:
sock.close()
print "Sent: {}".format(data)
print "Received: {}".format(received)
This is example given on Python official website
What is wrong here?
From the Python website:
format(value[, format_spec]) Convert a value to a “formatted”
representation, as controlled by format_spec. The interpretation of
format_spec will depend on the type of the value argument, however
there is a standard formatting syntax that is used by most built-in
types: Format Specification Mini-Language.
New in version 2.6.
So I guess you should upgrade your Python version.
Or use another syntax:
print "%s wrote:" % self.client_address[0]
If self.client_address[0] can be converted to a string.