Cannot read message from client : UDP python 3 - python

I tried to send message to server from client with manual input, with 10 limits input. its succesfully work on client side but when i tried to run server it's shows nothing
here's the code from client side
import socket
UDP_IP = "localhost"
UDP_PORT = 50026
print ("Destination IP:", UDP_IP)
print ("Destination port:", UDP_PORT)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for x in range (10):
data = input("Message: ")
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print(data)
else :
print("lebih dari 10!!")
s.sendto(data.encode('utf-8'), (UDP_IP, UDP_PORT))
s.close()
here's result and code from server side
import socket
UDP_IP = "localhost"
UDP_PORT = 50026
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((UDP_IP, UDP_PORT))
while True:
data, address = s.recvfrom(1024)
print(data)
print(address)
s.close()
when i run the program, nothing happen. here's the running program

Your main problem is the else statement you added there which is not executing. If want to put a limit of 10 after accepting the input, you are supposed to print the statement after the loop.
This is the client code:
import socket
UDP_IP = "127.0.0.1" # It is the same as localhost.
UDP_PORT = 50026
print ("Destination IP:", UDP_IP)
print ("Destination port:", UDP_PORT)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for x in range (10):
data = input("Message: ")
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print(data)
s.sendto(data.encode('utf-8'), (UDP_IP, UDP_PORT))
print("lebih dari 10!!")
s.close()
Edit:
I am not really understanding your problem but as far as I understand you want to show the limit on the server. Thus you can do this, try adding a loop on the server and receive input from the client's address only to avoid receiving extra messages.
Server Code:
import socket
UDP_IP = "127.0.0.1" # It is the same as localhost.
UDP_PORT = 50026
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((UDP_IP, UDP_PORT))
x = 0
while True:
data, address = s.recvfrom(1024)
# This block will make sure that the packets you are receiving are from expected address
# The address[0] returns the ip of the packet's address, address is actually = ('the ip address', port)
if address[0] != '127.0.0.1':
continue
# The logic block ends
print(data)
print(address)
x = x + 1 # This shows that one more message is received.
if x == 10:
break # This breaks out of the loop and then the remaining statements will execute ending the program
print("10 messages are received and now the socket is closing.")
s.close()
print("Socket closed")
I have commented the code so I hope you understand the code

Related

Loop not occurring using python socket

I am using my server code on a raspberry pi and my client code on my laptop. I also off the firewall on my computer. After connecting to the server, I manage to run the loop for once from the client side by keying the word "data" and when I keyed in another command it just came out of the loop. If i key in Quit it says that it have an OS error98 address already in used. May I know how to keep the loop on going ? Below I is my client.py and server.py code.
Server.py code:
import socket
import numpy as np
import encodings
HOST = '192.168.1.65'
PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
def random_data(): # ANY DATA YOU WANT TO SEND WRITE YOUR SENSOR CODE HERE
x1 = np.random.randint(0, 55, None) # Dummy temperature
y1 = np.random.randint(0, 45, None) # Dummy humidigy
my_sensor = "{},{}".format(x1,y1)
return my_sensor # return data seperated by comma
def my_server():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
print("Server Started waiting for client to connect ")
s.bind((HOST, PORT))
s.listen(5)
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024).decode('utf-8')
if str(data) == "Data":
print("Ok Sending data ")
my_data = random_data()
x_encoded_data = my_data.encode('utf-8')
conn.sendall(x_encoded_data)
elif str(data) == "Quit":
print("shutting down server ")
break
else:
pass
if __name__ == '__main__':
while 1:
my_server()
Client.py Code:
import socket
import threading
import time
HOST = '192.168.1.65' # The server's hostname or IP address
PORT = 65432 # The port used by the server
def process_data_from_server(x):
x1, y1 = x.split(",")
return x1,y1
def my_client():
threading.Timer(11, my_client).start()
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
my = input("Enter command ")
my_inp = my.encode('utf-8')
s.sendall(my_inp)
data = s.recv(1024).decode('utf-8')
x_temperature,y_humidity = process_data_from_server(data)
print("Temperature {}".format(x_temperature))
print("Humidity {}".format(y_humidity))
s.close()
time.sleep(5)
if __name__ == "__main__":
while 1:
my_client()
address already used
you need to use socket.setsockopt to set socket.SO_REUSEADDR in i think both client and server.py
def my_server():
# with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print("Server Started waiting for client to connect ")
s.bind((HOST, PORT))
s.listen(5)
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024).decode('utf-8')
if str(data) == "Data":
...

Spoofing IP address on same machine running 127.0.0.1 server

I am hosting a server listening for UDP packets on local host with IP address '127.0.0.1'. On the same machine, how would I be able to send packets to this server with spoofed IP address '1.2.3.4' and not '127.0.0.1'?
import socket
UDP_IP = "127.0.0.1"
UDP_PORT = 5005
if __name__ == "__main__":
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_PORT))
sizes = {}
for size in range(512):
sizes[size] = 0
while True:
data, addr = sock.recvfrom(8092)
if addr[0] != "1.2.3.4":
print("Acess denied")
#print(addr[0])
#print(len(data))
continue
else:
print("hello")
print ("length:", len(data))
sizes[len(data)] += 1
Currently this is the code I am using to send UDP packets.
import socket
import ipaddress
UDP_IP = "127.0.0.1"
UDP_PORT = 5005
if __name__ == "__main__":
ipaddress.ip_address(unicode('1.2.3.4', "utf-8"))
Message = "H"
clientSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
clientSock.sendto(Message, (UDP_IP, UDP_PORT))

Sending JSON object to a tcp listener port in use Python

I have a listener on a tcp localhost:
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 8192 # The port used by the server
def client_socket():
while 1:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP,TCP_PORT))
s.listen(1)
while 1:
print 'Listening for client...'
conn, addr = s.accept()
print 'Connection address:', addr
data = conn.recv(BUFFER_SIZE)
if data == ";" :
conn.close()
print "Received all the data"
i=0
for x in param:
print x
#break
elif data:
print "received data: ", data
param.insert(i,data)
i+=1
#print "End of transmission"
s.close()
I am trying to send a JSON object to the same port on the local host:
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 8192 # The port used by the server
def json_message(direction):
local_ip = socket.gethostbyname(socket.gethostname())
data = {
'sender' : local_ip,
'instruction' : direction
}
json_data = json.dumps(data, sort_keys=False, indent=2)
print("data %s" % json_data)
send_message(json_data)
return json_data
def send_message(data):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(data)
data = s.recv(1024)
print('Received', repr(data))
However, I get a socket error:
socket.error: [Errno 98] Address already in use
What am I doing wrong? Will this work or do I need to serialize the JSON object?
There are a few problems with your code, but the one that will likely address your issue is setting the SO_REUSEADDR socket option with:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
after you create the socket (with socket.socket(...) but before you attempt to bind to an address (with s.bind().
In terms of other things, the two "halves" of the code are pretty inconsistent -- like you copied and pasted code from two different places and tried to use them?
(One uses a context manager and Python 3 print syntax while the other uses Python 2 print syntax...)
But I've written enough socket programs that I can decipher pretty much anything, so here's a working version of your code (with some pretty suboptimal parameters e.g. a buffer size of 1, but how else would you expect to catch a single ;?)
Server:
import socket
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 8192 # The port used by the server
BUFFER_SIZE = 1
def server_socket():
data = []
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST,PORT))
s.listen()
while 1: # Accept connections from multiple clients
print('Listening for client...')
conn, addr = s.accept()
print('Connection address:', addr)
while 1: # Accept multiple messages from each client
buffer = conn.recv(BUFFER_SIZE)
buffer = buffer.decode()
if buffer == ";":
conn.close()
print("Received all the data")
for x in data:
print(x)
break
elif buffer:
print("received data: ", buffer)
data.append(buffer)
else:
break
server_socket()
Client:
import socket
import json
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 8192 # The port used by the server
def json_message(direction):
local_ip = socket.gethostbyname(socket.gethostname())
data = {
'sender': local_ip,
'instruction': direction
}
json_data = json.dumps(data, sort_keys=False, indent=2)
print("data %s" % json_data)
send_message(json_data + ";")
return json_data
def send_message(data):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(data.encode())
data = s.recv(1024)
print('Received', repr(data))
json_message("SOME_DIRECTION")

Reading data from a python socket received from multiple clients

I am writing a python program (master.py) to read the data received from 2 separate clients. This is the code example:
master.py:
data_agg = ''
HOST = '172.31.31.207'
PORT = 50008
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(2)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(65535)
data_agg += data
if not data: break
data_arr = json.loads(data_agg.decode('utf-8'))
data_arr = sorted(data_arr)
print "Sorted attay: \n"
print data_arr
Two clients have the following code:
HOST = '172.31.31.207'
PORT = 50008
s0 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s0.connect((HOST, PORT))
s0.send(sorted_data_string)
s0.close()
However i only receive data from a single client. What would be a proper way to read the data from a socket arriving from multiple receivers?
If you want your server th handle multiple clients, you can put accept() in a loop and add new clients to a list of connected clients. Then you can read - write to each of those clients.
HOST = '172.31.31.207'
PORT = 50008
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(2)
clients = []
while True:
conn, addr = s.accept()
clients += [{'conn':conn, 'addr':addr}]
print 'Connected by', addr
data_agg = ''
while True:
data = conn.recv(65535)
if not data:
break
data_agg += data
data_arr = sorted(json.loads(data_agg.decode('utf-8')))
print "Sorted attay: \n"
print data_arr
conn.close()
s.close()
You could improve the above code by using thread, so that you can handle multiple clients at the same time. You can do this by defining a handle_client function, and run it on a new thread.
while True:
conn, addr = s.accept()
print 'Connected by', addr
start_new_thread(handle_client, (conn,))

how to create a UDP server that will listen on multiple ports in python?

this is my server:
import socket
for port in range(33,128):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(('0.0.0.0', port))
while True:
(client_name, client_adress) = server_socket.recvfrom(1024)
print chr(port)
server_socket.close()
this is my client:
import socket
message = raw_input("Enter a message: ")
for letter in message:
my_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
my_socket.sendto("", ('127.0.0.1', ord(letter)))
(data, remote_adress) = my_socket.recvfrom(1024)
my_socket.close()
print 'The server sent: ' + data
I'm not very good in python, but I think you should save your sockets to list inside for and then use select function in infinite loop outside for
import socket
import select
sockets = []
for port in range(33,128):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(('0.0.0.0', port))
sockets.append(server_socket)
empty = []
while True:
readable, writable, exceptional = select.select(sockets, empty, empty)
for s in readable:
(client_data, client_address) = s.recvfrom(1024)
print client_address, client_data
for s in sockets:
s.close()

Categories