Apr-05-2017, 04:51 PM
Hello, I am trying to figure out how to properly print the data from a UDP packet. For homework our professor has a server running that when it receives the string 'time' formatted as ascii (which from my understanding I don't need to actually do anything. It will automatically be formatted to that) that the server will then send a datagram containing the time since epoch in milliseconds as an unsigned int long long. He wanted us to use structs to unpack the datagram. The datagram will be 8 bytes, but if the server receives anything but 'time' it will send a one byte datagram containing \x00. So my problem here is, I can not figure out how to properly unpack and print the datagram. When I unpack it as a unsigned long long, it is just a bunch of numbers and I know that is not correct. I do believe I am connecting correctly, because I checked the size of the datagrams and they were either 8 bytes or 1 byte. So I am receiving them, but can't figure out how to properly unpack them to read them. Also the sad part is that this only works if you are on the same network. So none of you can actually test the code :/
import socket import sys from struct import * address = socket.gethostbyname('hawk.champlain.edu') port = 9999 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) message = 'time' sock.sendto(message, (address, port)) data, server = sock.recvfrom(4096) length = len(data) if length == 8 : print unpack('Q',data)