Python s.recv() returns empty string - python

I've got a simple client and server I found on an online tutorial
#server.py
import socket # Import socket module
s = socket.socket() # Create a socket object
host = 'localhost' # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close() # Close the connection
#client # This is client.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = 'localhost'
port = 12345 # Reserve a port for your service.
s.connect((host, port))
print s.recv(1024)
s.close # Close the socket when done
When I run my client.py all it does is print an empty string when it should print ('Thank you for connecting'). When I connect localhost 12345 from telnet it sends the message fine so I don't know why my client isn't receiving the message
Any thoughts. I'm very new to socket programming and would love to find a solution so I can move on.

While running your script as is, I got this error:
Waiting connections ...
Got connection from ('127.0.0.1', 63875)
Traceback (most recent call last):
File "serv.py", line 14, in <module>
c.send('Thank you for connecting')
TypeError: a bytes-like object is required, not 'str'
Few things here:
Ensure you're sending bytes instead of str. you could do this by replacing line 14 with:
c.send(b'Thank you for connecting')
Also, it's always useful to declare your sockets s like this:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Further read:
Py2: https://docs.python.org/2/library/socket.html
Py3: https://docs.python.org/3/library/socket.html
Hope it works! :)

Related

Print is not showing result when executing this simple socket connection code in python. Why is the print not showing result?

I have the following client/server python code. The print line from the server where i used f-string interpolation does not show anything when the code is executed and I would like to know why?
I followed this tutorial and on their end the print line shows result.
tutorial: https://www.tutorialspoint.com/python/python_networking.htm
line: Got connection from ('127.0.0.1', 48437)
my server code:
#!/usr/bin/python
# Server.py
# Import socket module
import socket
# Create a socket object
s = socket.socket()
# Get local machine name
host = socket.gethostname()
# Reserve a port number for the socket service
port = 22226
# Bind the host address and the port number
s.bind((host, port))
# Listens for the client connections made for the socket.
# The argument shows maximum number of queued connections and it is 1 at minimum
s.listen(5)
while True:
# Establish connection with client.
c, addr = s.accept()
print(f"Got connection from {addr}")
c.send(b'Thank you for connecting')
c.close() # Close the connection
my client code:
#!/usr/bin/python
# client.py
# Import socket module
import socket
# Create a socket object
s = socket.socket()
# Get local machine name
host = socket.gethostname()
# Reserve a port number for the socket service
port = 22226
# Connect the host address and the port number
s.connect((host, port))
# Read at most 1024 bytes
print(s.recv(1024))
s.close() # Close the socket when done

Making an outbound connection

I've recently been tinkering around with the python socket module and I have come across an issue.
Here is my python server side script (im using python3.8.2)
import socket
#defin socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 0))
s.listen(5)
while True:
clientsocket, address = s.accept()
print(f"connection from client has been established")
clientsocket.send(bytes("welcome to the server!", "utf-8"))
My server side script runs fine, however when i run the client script
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(127.0.0.1), 0))
msg = s.recv(1024)
print(msg.decode("utf-8"))
i get the following:
File "client.py", line 3
s.connect((socket.gethostname(127.0.0.1), 0))
^
SyntaxError: invalid syntax
I've tried changing the IP to my computer host name and gives the following:
raceback (most recent call last):
File "client.py", line 3, in <module>
s.connect(socket.gethostname((LAPTOP-XXXXXXX), 0))
NameError: name 'LAPTOP' is not defined
There are multiple issues:
when specifying IP addresses and hostnames, they must be formatted as strings (e.g. "127.0.0.1" and "LAPTOP-XXXXXXX"). Specifying them without quotes causes Python to attempt to interpret them as other tokens, such as variable names, reserved keyword, numbers, etc., which fails causing erros such as SyntaxError and NameError.
socket.gethostname() does not take an argument
specifying port 0 in the socket.bind() call results in a random high numbered port being assigned, so you either need to hardcode the port you use or dynamically specify the correct port in your client (e.g. by specifying it as an argument when executing the program)
in the server code, socket.gethostname() may not end up using the loopback address. One option here is using an empty string, which results in accepting connections on any IPv4 address.
Here's a working implementation:
server.py
import socket
HOST = ''
PORT = 45555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
host_addr = s.getsockname()
print("listening on {}:{}".format(host_addr[0], host_addr[1]))
s.listen(5)
while True:
client_socket, client_addr = s.accept()
print("connection from {}:{} established".format(client_addr[0], client_addr[1]))
client_socket.send(bytes("welcome to the server!", "utf-8"))
client.py
import socket
HOST = '127.0.0.1'
PORT = 45555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
msg = s.recv(1024)
print(msg.decode("utf-8"))
Output from the server:
$ python3 server.py
listening on 0.0.0.0:45555
connection from 127.0.0.1:51188 established
connection from 127.0.0.1:51244 established
Output from client:
$ python3 client.py
welcome to the server!
$ python3 client.py
welcome to the server!
Put the 127.0.0.1 as string in gethostname
In the /etc/hosts file content, You will have an IP address mapping with '127.0.1.1' to your hostname. This will cause the name resolution to get 127.0.1.1. Just comment this line. So Every one in your LAN can receive the data when they connect with your ip (192.168.1.*). Used threading to manage multiple Clients.
Here's the Server and Client Code:
Server Code:
import socket
import os
from threading import Thread
import threading
import time
import datetime
def listener(client, address):
print ("Accepted connection from: ", address)
with clients_lock:
clients.add(client)
try:
while True:
client.send(a)
time.sleep(2)
finally:
with clients_lock:
clients.remove(client)
client.close()
clients = set()
clients_lock = threading.Lock()
host = socket.getfqdn() # it gets ip of lan
port = 10016
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host,port))
s.listen(3)
th = []
print ("Server is listening for connections...")
while True:
client, address = s.accept()
timestamp = datetime.datetime.now().strftime("%b %d %Y,%a, %I:%M:%S %p")
a = ("Hi Steven!!!" + timestamp).encode()
th.append(Thread(target=listener, args = (client,address)).start())
s.close()
Client Code:
import socket
import os
import time
s = socket.socket()
host = '192.168.1.43' #my server ip
port = 10016
print(host)
print(port)
s.connect((host, port))
while True:
print((s.recv(1024)).decode())
s.close()
Output:
(base) paulsteven#smackcoders:~$ python server.py
Server is listening for connections...
Accepted connection from: ('192.168.1.43', 38716)
(base) paulsteven#smackcoders:~$ python client.py
192.168.1.43
10016
Hi Steven!!!Feb 19 2020,Wed, 11:13:17 AM
Hi Steven!!!Feb 19 2020,Wed, 11:13:17 AM
Hi Steven!!!Feb 19 2020,Wed, 11:13:17 AM

Python - show path, simple socket problem

I recently ventured into python in 3.7
I want to make a server / client whose client will show the path I put in input (macOS):
Server
import socket
HOST = '' # Symbolic name meaning all available interfaces
PORT = 1337 # Arbitrary non-privileged port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
with conn:
print('Connected by', addr)
info = conn.recv(1024)
print(info)
raw_input("Push to exit")
s.close()
Client :
import socket
import os
HOST = '' # The remote host
PORT = 1337 # The same port as used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
print('Connected')
info = os.listdir("/Users/jhon")
s.send(str(info))
s.close()
Server start and it's listening...
python client.py Connected Traceback (most recent call last): File
"client.py", line 10, in
s.send(str(info)) TypeError: a bytes-like object is required, not 'str' (not understand this), and after client start, in server show:
Connected by ('127.0.0.1', 52155) b'' Traceback (most recent call
last): File "server.py", line 13, in
raw_input("press for exit") NameError: name 'raw_input' is not defined (venv) MBP-di-Jhon:untitled1 jhon$
You may want to change the client code to:
HOST = '' # The remote host
PORT = 1337 # The same port as used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
print('Connected')
info = "\n".join(os.listdir("/Users/jhon"))
s.send(info.encode())
s.send(info)
s.close()
os.listdir("/Users/jhon") returns a list, we use join and encode to make it byte object, which is needed for s.send()
You ventured into 3.7 from some 2.x version without modifying the 2.x code. Read something about the differences before continuing. To help you get started:
Replace raw_input with input. (One could replace 2.x input() with eval(input()), but one should nearly always use a more specific evaluator, such as int(input()).)
In 3.x, strings are unicode, whereas sockets still require bytes. Change send and recv to
s.send(str(info).encode())
info = conn.recv(1024).decode()

How to send a message from client to server in python

I'm reading two programs in Python 2.7.10 with client and server. How can I modify these programs in order to send a message from client to server?
server.py:
#!/usr/bin/python # This is server.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close() # Close the connection
client.py:
#!/usr/bin/python # This is client.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 80 # Reserve a port for your service.
s.connect((host, port))
print s.recv(1024)
s.close # Close the socket when done
TCP sockets are bi-directional. So, after connection, there is no difference between server and client, you only have two ends of a stream:
import socket # Import socket module
s = socket.socket() # Create a socket object
s.bind(('0.0.0.0', 12345)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
print c.recv(1024)
c.close() # Close the connection
and the client:
import socket # Import socket module
s = socket.socket() # Create a socket object
s.connect(('localhost', 12345))
s.sendall('Here I am!')
s.close() # Close the socket when done
The above answer throws an error: TypeError: a bytes-like object is required, not 'str'
However, the following code worked for me:
server.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 3125
s.bind(('0.0.0.0', port))
print ('Socket binded to port 3125')
s.listen(3)
print ('socket is listening')
while True:
c, addr = s.accept()
print ('Got connection from ', addr)
print (c.recv(1024))
c.close()
client.py:
import socket
s = socket.socket()
port = 3125
s.connect(('localhost', port))
z = 'Your string'
s.sendall(z.encode())
s.close()

How to use client socket as a server socket python

I like to have one port that first use for connect to another server and after that this port use to be a server and another clients connect to it.
I used python socket for client now I want to use it for server socket.
my code :
#!/usr/bin/python # This is server.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12349
portt = 12341 # Reserve a port for your service.
s.bind((host, portt)) # Bind to the port
s.connect((host, port))
s.listen(5) # Now wait for client connection.
c, addr = s.accept() # Establish connection with client.
print c
print 'Got connection from', addr
print s.recv(1024)
s.close
and the output is
Traceback (most recent call last):
File "client.py", line 12, in <module>
s.listen(5) # Now wait for client connection.
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 22] Invalid argument
How can I do that.
thank you for your answers!
Not sure what you are trying to do here. Seems to me that you are mixing client and server code in the same app.
For reference, you can create a simple echo server like this:
import socket
HOST = ''
PORT = 12349
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(5)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
conn.close()
And a simple echo client like this:
import socket
HOST = 'localhost'
PORT = 12349
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)

Categories

Resources