How to concatenate 3 separate UDP packets? - python

This question has probably been asked before but I can't seem to find it.
I am trying to send 3 individual packets between a client and a server. That part I can do, however I need to take those 3 packets and add them together and print the result.
That's the part I am having trouble with. I have never programmed before and have only really started so I am new to all this and please be gentle with what is probably awful coding on my part!
This is what I have for the client:
import socket
clientSock = socket.socket(socket.AF_INET , socket.SOCK_DGRAM)
UDP_IP = "localhost"
UDP_PORT = 6842
address = ("localhost" , 6842)
s1 = str(input("Please enter Packet number 1: "))
clientSock.sendto(bytes("s1", "utf-8"), (address))
s2 = str(input("Please enter Packet number 2: "))
clientSock.sendto(bytes("s2", "utf-8"), (address))
s3 = str(input("please enter Packet number 3: "))
clientSock.sendto(bytes("s3", "utf-8"), (address))
print ("Sent 3 packets to server")
print ("Waiting to receive message...")
And this is what I have for the server:
import socket
serverSocket = socket.socket(socket.AF_INET , socket.SOCK_DGRAM)
UDP_IP = "localhost"
UDP_PORT = 6842
address = ("localhost" , 6842)
serverSocket.bind(address)
print ("Waiting for client...")
while True:
data,addr = serverSocket.recvfrom(6842)
print ("Received:",data," from",addr)
n = len('s1' , 's2' , 's3')
R = "s1" + "#" + "s2" + "#" + "s3"
print (n)
print (R)
Again there are probably quite a few flaws in this but was wondering if anyone can point me in the right direction.

I think your server just wants to do something closer to:
while True:
values = []
for i in range(3):
values.append(float(sock.recv(1024)))
print(sum(values))
note that UDP is unreliable, so you might not always receive the three packets sent from the client
you can also compress the contents of the while loop into a single line, and hence avoid creating any list, but I'll leave that up to you!

Related

keep getting a session timeout, can't figure out why, the server should display the message right back

keep getting a session timeout, can't figure out why, the server should display the message right back. the code is displayed on the bottom, where the first set of code is the client and the second set is server, the first thing you'll see is the output, that is where is shown that there is a session timeout.
Client-Server
All Uppercase
All Lowercase
Initial Caps
Exit
Enter Choice: 1
Enter the sentence: the kid had sicknesss
Session timed out
This is the client:
import socket
from socket import AF_INET, SOCK_DGRAM
import time
# Address of UDP IP
UDP_IP_ADDRESS = '127.0.0.1' #server set as localhost
# UDP port number
UDP_PORT_NO = 9999
# Display the message
# print('Pinging',UDP_IP_ADDRESS,UDP_PORT_NO)
#create the socket
clientSocket = socket.socket(AF_INET,SOCK_DGRAM)
#sets the timeout at 1 sec
clientSocket.settimeout(1)
choice = 1
try:
print("Client-Server")
# Create a while loop to repeat the process continously
while True:
print()
print("1. All Uppercase")
print("2. All Lowercase")
print("3. Initial Caps")
print("4. Exit")
while(True):
choice=input("Enter Choice: ")
if(choice not in ["1","2","3","4"]):
print("Invalid Input!")
else:
break
if choice is "4":
print( 'Thank you!')
break
# Prompt the user to enter the sentence
sentence=input("Enter the sentence: ")
message=choice+"-"+sentence
# Sending sentence and command to the server.
clientSocket.sendto(message.encode('utf-8'),(UDP_IP_ADDRESS, UDP_PORT_NO))
#"Receiving login request from the server"
#print()
updated_sentence, server = clientSocket.recvfrom(4096)
updated_sentence = str(updated_sentence)
updated_sentence = updated_sentence[2:len(updated_sentence)-1]
print("Updated Sentence from the server: "+updated_sentence)
except socket.timeout:
print( 'Session timed out')
Here is the server code:
# The following module to generate randomized lost packets
import random
from socket import *
# Create a UDP socket
# Notice the use of SOCK_DGRAM for UDP packets
serverSocket = socket(AF_INET, SOCK_DGRAM)
# Assign IP address and port number to socket
serverSocket.bind(('', 9999))
print('The server is ready to receive on port: 9999')
# Create a 'while-loop' to run the process continoulsy
while True:
# Receive the client packet along with the address it is coming from
message,address = serverSocket.recvfrom(2048)
message = str(message)
message = message[2:len(message)-1]
command = message[0]
sentence = message[2:]
# Create an if-statement to check the command.
if(command == "1"):
sentence=sentence.upper()
elif(command == "2"):
sentence=sentence.lower()
else:
words=sentence.split()
sentence=""
for word in words:
sentence = sentence + word[0].upper()+word[1:]+" "
# Send the modified sentence to the client.
serverSocket.sendto(sentence.encode('utf-8'), address)

Socket Programming; File corrupts when transferring over multiple devices

The problem I'm having is to get a file from the server to client across devices. Everything works fine on localhost.
Lets say I want to "get ./testing.pdf" which sends the pdf from the server to the client. It sends but it is always missing bytes. Is there any problems with how I am sending the data. If so how can I fix it? I left out the code for my other functionalities since they are not used for this function.
sending a txt file with "hello" in it works perfectly
server.py
import socket, os, subprocess # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
#host = ''
port = 5000 # Reserve a port for your service.
bufsize = 4096
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
while True:
userInput = c.recv(1024)
.... CODE ABOUT OTHER FUNCTIONALITY
elif userInput.split(" ")[0] == "get":
print "inputed get"
somefile = userInput.split(" ")[1]
size = os.stat(somefile).st_size
print size
c.send(str(size))
bytes = open(somefile).read()
c.send(bytes)
print c.recv(1024)
c.close()
client.py
import socket, os # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
#host = '192.168.0.18'
port = 5000 # Reserve a port for your service.
bufsize = 1
s.connect((host, port))
print s.recv(1024)
print "Welcome to the server :)"
while 1 < 2:
userInput = raw_input()
.... CODE ABOUT OTHER FUNCTIONALITY
elif userInput.split(" ")[0] == "get":
print "inputed get"
s.send(userInput)
fName = os.path.basename(userInput.split(" ")[1])
myfile = open(fName, 'w')
size = s.recv(1024)
size = int(size)
data = ""
while True:
data += s.recv(bufsize)
size -= bufsize
if size < 0: break
print 'writing file .... %d' % size
myfile = open('Testing.pdf', 'w')
myfile.write(data)
myfile.close()
s.send('success')
s.close
I can see two problems right away. I don't know if these are the problems you are having, but they are problems. Both of them relate to the fact that TCP is a byte stream, not a packet stream. That is, recv calls do not necessarily match one-for-one with the send calls.
size = s.recv(1024) It is possible that this recv could return only some of the size digits. It is also possible that this recv could return all of the size digits plus some of the data. I'll leave it for you to fix this case.
data += s.recv(bufsize) / size -= bufsize There is no guarantee that that the recv call returns bufsize bytes. It may return a buffer much smaller than bufsize. The fix for this case is simple: datum = s.recv(bufsize) / size -= len(datum) / data += datum.

Python UDP Port Knocker - Not Working

I want to code a UDP Port Knocker. I have 5 possible UDP ports 2222,3333,4444,5555,6666 and I should knock this ports on a certain IP address, if the knock sequence is correct (e.g. 3333,4444,2222) I can talk to the server via TCP and it will give me an answer. Otherwise no answer and no connection.
Why does my code not work? The 'x' in the code mark places where normally private information are put in - no syntax errors.
import socket
import time
UDP_IP = "xxxxx"
TCP_IP = 'xxxxx'
TCP_PORT = 1111
request = "xxx"
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
d = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def my_range(start, end, step):
while start <= end:
yield start
start += step
for x in my_range(2222, 6666, 1111):
for y in my_range(2222, 6666, 1111):
for z in my_range(2222, 6666, 1111):
print "Port knock: ",x,y,z
s.sendto(request,(UDP_IP, x))
s.sendto(request,(UDP_IP, y))
s.sendto(request,(UDP_IP, z))
print "Waiting..."
time.sleep(1)
try:
d.connect((TCP_IP, TCP_PORT))
print "SUCCESS:",x,y,z
time.sleep(1)
data = d.recv(1024)
print "Servers says: " + data
except socket.error:
print "False combination of ports"
continue
s.close()
d.close()
UDP is a stateless protocol. The order of the udp-packages is not guaranteed. E.g. x,y,z can reach the server as y,x,z or any other combination.

IPID field unexpected increase

Intro:
I have an exercise where I need to send a file from S to D through a third party T only.
T is run on port 10000 or 11000 depending if i use UDP or TCP; i use UDP, and T's ip is given both to S and D.
T is given and all it does is echo messages it got back to the sender.
One of the fields in the header of T's echo message is called ip_id - a counter that goes up by one with each message T receives; in order to view the ip_id value i need to use raw sockets.
S/D sends a message to T and is then supposed to receive back a message. S/D needs to check that the ip and port that it got the message from matches the one it sent to (that is, if S/D sends a message to 1.1.1.1:5 it should receive a message from 1.1.1.1:5).
First I open a socket and a raw socket once
self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.raw_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP)
I then get my port by doing:
self.s.sendto("1", (self.remote_server, UDP_PORT))
self.myPort = self.s.getsockname()[1]
UDP_PORT is 10000 and is the port to send messages to.
remote_server is the ip to send messages to.
I also have the following method:
def send_value(self, number_of_packets):
for i in range(0,number_of_packets):
self.s.sendto(BOGUS_DATA, (self.remote_server, UDP_PORT))
self.raw_socket.recvfrom(1024)
#self.raw_socket.recv(1024)
And as well as this one:
def recieve_ip_id(self):
try:
sent = 0
continueFlag = True
while continueFlag:
self.s.sendto(BOGUS_DATA, (self.remote_server, UDP_PORT))
#mypacket = self.raw_socket.recv(1024)
mypacket = self.raw_socket.recvfrom(1024)
mypacket = mypacket[0]
continueFlag = False
if (256*ord(mypacket[20])+ord(mypacket[21]) != UDP_PORT):
continueFlag = True
if (256*ord(mypacket[22])+ord(mypacket[23]) != self.myPort):
continueFlag = True
sent = sent + 1
ip_id = 256 * ord(mypacket[4]) + ord(mypacket[5])
print "packet 20 21 " + str(256*ord(mypacket[20])+ord(mypacket[21])) + " packet 4 5 " + str(256 * ord(mypacket[4]) + ord(mypacket[5])) + " packet 22 23 " + str(256*ord(mypacket[22])+ord(mypacket[23]))
print ip_id
return (ip_id, 0)
except socket.timeout:
# dummy
return (0, 0)
It works good enough in the sense that it checks correctly who it got the message from; The problem is that the ip_id wont advance as expected. after some time the programs are running they each get ip_id as if it was not shared anymore.
am i not checking something correctly, or is it something else?
Thanks.

Python server-client relationship over network problems

I wrote a program for my networking class that measures upload and download speeds by sending a file over a socket and timing the transfer, and I used Python. The problem I'm having is that the server and client can talk just fine when running on the same machine, but as soon as I put the server program on another machine on my network, no file transfer happens. They talk to each other (Client says "connected to server" and server says "connection from xxx.xxx.xxx.xxx") but the file transfer size and speed are shown as 0 and 0.
Here's the server code:
import util
import socket
import os
import shutil
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = ""
port = 12345
f = open("receivedfromclient.txt", "r+")
print "Waiting for clients..."
s.bind((host, port))
s.listen(5)
c, addr = s.accept()
print "Client connected:", addr
start = time.clock()
msg = c.recv(257024)
stop = time.clock()
duration = stop-start
f.write(str(msg))
b = os.path.getsize("receivedfromclient.txt")
print "File size = ", b, "bits"
print "Time to transfer from client = ", duration, " seconds"
bw = (b/duration)/1048576
print "The upload bit rate is ", bw, "Mpbs"
f.close()
shutil.copy("receivedfromclient.txt", "sendtoclient.txt")
f.open("sendtoclient.txt")
c.send(f.read())
f.close()
c.close()
s.close()
and the client code is similar:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = raw_input("Please enter host address: ")#socket.gethostname()
port = 12345
sendfile = raw_input("Please enter name of file to transfer: ")
f = open(sendfile,"rb")
g = open("receivedfromserver.txt","w")
print "Connecting to ", host, port
s.connect((host, port))
s.send(f.read())
and so on. Can anybody tell me what I'm doing wrong here?
Hmm - there are at least some problems:
The major one is, that IMHO it is not clear what you really want to do.
Here is your code with some remarks:
# import util <-- NOT NEEDED
import socket
import os
import shutil
import time # <-- Added
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = ""
port = 12345
f = open("receivedfromclient.txt", "r+")
print "Waiting for clients..."
s.bind((host, port))
s.listen(5)
c, addr = s.accept() # <-- FORGOTTEN ()
print "Client connected:", addr
start = time.clock()
msg = c.recv(257024) # <-- You need some loop here to get the whole file
stop = time.clock()
duration = stop-start
f.write(str(msg))
b = os.path.getsize("receivedfromclient.txt") # <-- = instead of .
print "File size = ", b, "bits"
print "Time to transfer from client = ", duration, " seconds"
bw = (b/duration)/1048576
print "The upload bit rate is ", bw, "Mpbs"
f.close()
shutil.copy("receivedfromclient.txt", "sendtoclient.txt")
f.open("sendtoclient.txt")
c.send(f.read())
f.close()
c.close()
s.close()
One problem here is, that start is in mostly all cases equal to stop - so you get a Division By Zero error in (b/duration).
In the client part at least a import socket is missing; the g is not needed at all.
Please explain further, what you want to do.
If you want to transfer files, there are a lot of ways to do (sftp, rsync, nc, ...).

Categories

Resources