Getting an encoding error using sockets in Python - python

I have created two scripts which establish a client socket and server socket in localhost.
Server socket
import socket
from time import ctime
HOST = ''
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST,PORT)
tcpsersoc = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
tcpsersoc.bind(ADDR)
tcpsersoc.listen(5)
while True:
print('waiting for connection .... ')
print(ADDR)
tcpClisoc,addr = tcpsersoc.accept()
print('......connected from', addr)
while True:
data = tcpClisoc.recv(BUFSIZ)
if not data:
break
tcpClisoc.send('[%s]%s'%(bytes(ctime(),'UTF-8'),data))
tcpClisoc.close()
tcpsersoc.close()
Client socket
from socket import *
HOST= '127.0.0.1'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST,PORT)
tcpCliSock = socket(AF_INET,SOCK_STREAM)
tcpCliSock.connect(ADDR)
while True:
data = input('>')
if not data:
break
tcpCliSock.send(data.encode('utf-8'))
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
print(data.decode('utf-8'))
tcpCliSock.close()
I'm still getting the below error despite converting the data into a bytes object. I'm using python 3.x
this is the error raised by the server socket
waiting for connection ....
('', 21567)
......connected from ('127.0.0.1', 52859)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
import exampletcpserver
File "C:/Python34\exampletcpserver.py", line 23, in <module>
tcpClisoc.send('[%s]%s'%(bytes(ctime(),'UTF-8'),data))
TypeError: 'str' does not support the buffer interface
Please let me know where i'm going wrong.

You are trying to send a string, but sockets require you to send bytes. Use
tcpClisoc.send(('[%s]%s' % (ctime(), data.decode("UTF-8"))).encode("UTF-8"))
Python 3.5 will support the alternative
tcpClisoc.send(b'[%s]%s' % (bytes(ctime(), 'UTF-8'), data))

Related

server.send(join.encode('utf-8')) gives me this error

I get this error when i connect on the client.
felix+
Traceback (most recent call last):
File "c:\Users\felix\Documents\CODE\Uno02\uno02_server.py", line 23, in <module>
server.send(join.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
The client simply receives some information from the user, and connects to the server. I am not sure what I typed wrong
Client code:
import socket
server_ip = input("Enter the server IP: ")
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((server_ip,42069))
name = input("Please enter a username: ")
client.send(name.encode())
while True:
server_msg = client.recv(1024)
print(server_msg.decode())
and server code:
name_list = []
ip_list = []
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("127.0.0.1",42069))
server.listen()
while(True):
(clientConnected, clientAddress) = server.accept()
print("connection gained %s:%s"%(clientAddress[0], clientAddress[1]))
clientdata = clientConnected.recv(1024)
name = clientdata.decode()
join = name + " joined"
name_list.append(clientdata)
ip_list.append(clientAddress[0])
print(name+"+")
server.send(join.encode('utf-8'))
Replace
server.send(join.encode('utf-8'))
by
clientConnected.send(join.encode('utf-8'))
check Python TCP Communication for further details

Python Error ConnectionAbortedError: [WinError 10053]

I am experimenting with import sockets in python and I have a client.py and a server.py and when server.py receives a message from client.py I get this error
Traceback (most recent call last):
File "C:/Users/Owner/PycharmProjects/pythonProject/echo_server.py", line 13, in <module>
data = conn.recv(1024)
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine
My full code is:
import socket
host = ''
port = 12345
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
print(host , port)
s.listen(1)
conn, addr = s.accept()
print('Connected by', addr)
while True:
data = conn.recv(1024)
data = str(data)
if not data: break
print("Client Says: "+data)
conn.sendall(b"Server Says:Message Received")
input(">")
conn.close()
Can someone tell me what this error is and what I can do to fix it?
The if statement if not data is equivalent to writing if data != "", while the empty string your server receives is b''. You have several options to fix it.
data = conn.recv(1024).decode() is the proper way to allocate the data sent by the client. You can now print(data) or compare data to an empty string.
If you still don't want to decode() your message you could change your if statement to if data != b'' or if data is not None.
Update
If it wasn't clear, your str(data) conversion causes the if statement to work unproperly, which is set to False without allowing you to break when a client disconnects.

Python socket bind ((host, port))

im making a Reverse Shell. and in the server.py file i got this error.
i has trying in de socket_bind() s.bind((host, port))
My code:
def socket_bind():
try:
global host
global port
global s
print("Binding socket to port: " + str(port))
s.bind((host, port))
s.listen(5)
except socket.error as msg:
print("Socket binding error: " + str(msg) + "\n" + "retrying...")
socket_bind()
my error:
Binding socket to port: 90
Traceback (most recent call last):
File "c:/ReverseShell/server.py", line 50, in <module>
main()
File "c:/ReverseShell/server.py", line 47, in main
socket_bind()
File "c:/ReverseShell/server.py", line 21, in socket_bind
s.bind((host, port))
TypeError: an integer is required (got type str)
how can i fix this error?
I know where you get this code. I don't know how to fix it, but you could use the code below for server.
# first import all require module
import socket # For building tcp connection
import os # Using this module for basic operation
os.system ("clear || cls") # it clear the terminal screen
def connect ():
s = socket.socket (socket.AF_INET, socket.SOCK_STREAM) # START a socket subject s
s.bind (("192.168.0.200", 9999)) # Define IP and Port
s.listen (1) # listen METHOD for pass the parameter as 1
print ('[+] Listening for incoming TCP connection on port 8080')
conn, addr = s.accept () #I want my server to accept CLIENT AND IP ADRESS BY ACCEPT METHOD
print ('[+] We got a connection from: ', addr)# After accpeted, print out the result
ter = 'terminate'
while True: #while connection is true
command = input ("\nShell>") # Get user input and store it in command variable
if ter in command: # If we type terminate command, so close te connection and break the loop
conn.send (ter.encode('utf-8')) #to send data to client with conn.send()
conn.close ()
break
else:
conn.send(str.encode (command)) #here we will send the command to the target send commands from server to client using python socket
client = str(conn.recv(1024).decode("utf-8"))
print (client) # print the result that we got back
def main():
connect()
main ()

module 'socket' has no attribute 'getsockname'

This is a simple file server file using TCP sockets,
when i'm running this i'm getting the following error.
Can anyone tell me the solution to this
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = socket.getsockname() # Reserve a port for your service.
block_size = 1024 #file is divided into 1kb size
s.bind((host, port)) # Bind to the port
#f = open('paris.png','wb')
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print('Got connection from', addr)
print("Receiving...")
l = c.recv(block_size)
while (l):
print("Receiving...")
l = c.recv(block_size)
#f.close()
print("Done Receiving")
mssg = 'Thank You For Connecting'
c.send(mssg.encode())
c.close() # Close the connection
Traceback (most recent call last):
File "C:\Users\Hp\Documents\Python codes\file_transfer_simple_server.py",line 5, in <module>
port = socket.getsockname() # Reserve a port for your service.
AttributeError: module 'socket' has no attribute 'getsockname'
As #Mark Tolonen mentioned in the comment, You were calling getsockname() on the socket module. getsockname is a method on the socket instance s
import socket
s = socket.socket()
s.bind(('localhost',12345))
host, port = s.getsockname() # unpack tuple
block_size = 1024
print(port)
# output
12345

Receiving custom Scapy packet in a Python socket [duplicate]

This question already has an answer here:
Extract received data in a tcp socket in Python
(1 answer)
Closed 7 years ago.
I am trying to send a custom packet (with a custom layer) using Scapy in python socket.
Here's the code of the client
#!/usr/bin/env python
import socket
from scapy.all import *
TCP_PORT = 5000
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('192.168.240.1', TCP_PORT))
class Reservation(Packet):
name = "ReservationPacket"
fields_desc=[ ByteField("id", 0),
BitField("type",None, 0),
X3BytesField("update", 0),
ByteField("rssiap", 0)]
k = IP(dst="192.168.240.1")/Reservation()
k.show()
send(k)
print "Reservation Message Sent"
s.close()
and the packet k appears to be successfully created and sent.
Here's the server which is responsible to receive the packet:
#!/usr/bin/python
import socket
from scapy.all import *
class Reservation(Packet):
name = "ReservationPacket"
fields_desc=[ ByteField("id", 0),
BitField("type",None, 0),
X3BytesField("update", 0),
ByteField("rssiap", 0)]
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('192.168.240.1', 5000))
s.listen(1)
while True :
conn, addr = s.accept()
print 'Connection address:', addr
print ''
data = conn.recv(1024)
data.show()
conn.close
s.close()
and this is the output I get from the server:
Connection address: ('192.168.240.5', 58454)
Traceback (most recent call last):
File "server.py", line 36, in <module>
data.show()
AttributeError: 'str' object has no attribute 'show'
How can I receive my packet and decode it to read its custom layer?
Data became a string in this line:
data = conn.recv(1024)
Checking the doc https://docs.python.org/2/library/socket.html
socket.recv(bufsize[, flags]) Receive data from the socket. The
return value is a string representing the data received. The maximum
amount of data to be received at once is specified by bufsize. See the
Unix manual page recv(2) for the meaning of the optional argument
flags; it defaults to zero.
What are you trying to do with data.show(), you just could print the data with:
print data
Also follow this link to decode the string:
Python - converting sock.recv to string
stringdata = data.decode('utf-8')

Categories