Skip to content

Instantly share code, notes, and snippets.

@mkagenius
Created October 17, 2017 13:56
Show Gist options
  • Save mkagenius/cb3ebaadfa82fb0c8886de7a564a39e2 to your computer and use it in GitHub Desktop.
Save mkagenius/cb3ebaadfa82fb0c8886de7a564a39e2 to your computer and use it in GitHub Desktop.
import struct
import socket
import random
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('localhost', 1717))
def tryRead() :
flag = False
readBannerBytes = 0
bannerLength = 2
readFrameBytes = 0
frameBodyLengthRemaining = 0
frameBody = ''
banner = {
'version':0,
'length':0,
'pid':0,
'realWidth':0,
'realHeight':0,
'virtualWidth':0,
'virtualHeight':0,
'orientation':0,
'quirks':0
}
while True:
chunk = client_socket.recv(4084)
if len(chunk) == 0:
continue
print('chunk(length=%d)' % len(chunk))
cursor = 0
while cursor < len(chunk):
if (readBannerBytes < bannerLength) :
print(readBannerBytes,"---", bannerLength)
if readBannerBytes == 0:
banner['version'] = int(chunk[cursor].encode('hex'), 16)
elif readBannerBytes == 1:
banner['length'] = bannerLength = int(chunk[cursor].encode('hex'), 16)
elif readBannerBytes >= 2 and readBannerBytes <= 5:
banner['pid'] = int(chunk[cursor].encode('hex'), 16)
elif readBannerBytes == 23:
banner['quirks'] = int(chunk[cursor].encode('hex'), 16)
cursor += 1
readBannerBytes += 1
if readBannerBytes == bannerLength:
print('banner', banner)
elif readFrameBytes < 4:
frameBodyLengthRemaining += (int(chunk[cursor].encode('hex'), 16) << (readFrameBytes * 8))
frameBodyLengthRemaining_orig = frameBodyLengthRemaining
cursor += 1
readFrameBytes += 1
print('headerbyte%d(val=%d)' %(readFrameBytes, frameBodyLengthRemaining))
else:
# if this chunk has data of next image
if len(chunk) - cursor >= frameBodyLengthRemaining:
print('bodyfin(len=%d,cursor=%d)' % (frameBodyLengthRemaining, cursor))
frameBody = frameBody + chunk[cursor:(cursor+frameBodyLengthRemaining)]
if frameBody[0] != '\xff' or frameBody[1] != '\xd8':
print("Frame body does not strt with JPEG header", frameBody[0], frameBody[1])
exit()
arr.append(frameBody)
if len(arr) == 1:
return 0
cursor += frameBodyLengthRemaining
frameBodyLengthRemaining = 0
readFrameBytes = 0
frameBody = ''
else:
# else this chunk is still for the current image
print('body(len=%d)' % ( len(chunk) - cursor), 'remaining = %d' % frameBodyLengthRemaining)
frameBody = frameBody + chunk[cursor:len(chunk)]
frameBodyLengthRemaining -= (len(chunk) - cursor)
readFrameBytes += len(chunk) - cursor
cursor = len(chunk)
arr = []
tryRead()
for i in arr:
with open("ss_"+str(random.randint(0, 10000))+".jpeg", "wb") as f:
f.write(i)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment