Skip to content

Instantly share code, notes, and snippets.

Created November 15, 2015 20:22
Show Gist options
  • Save anonymous/8020700d79762713b398 to your computer and use it in GitHub Desktop.
Save anonymous/8020700d79762713b398 to your computer and use it in GitHub Desktop.
Beam.py - An utility script I use to send files wirelessly from my pc to my mobile phone via HTTP while I'm developing stuff
#!/usr/bin/env python
from sys import argv
from time import sleep
import socket
############## COMMAND-LINE ARGUMENTS #################
# Check if there is a correct number of arguments
if len(argv)<2 or len(argv)>3:
print "Usage: beam.py file [COUNT]"
print ""
print "If COUNT is specified, the file will be beamed COUNT times (for multiple devices)"
print ""
quit()
filename = str(argv[1])
beam_count = 1
if len(argv)==3:
beam_count = int(argv[2])
############# INITIALISATION STUFF ###############
PORT = 8343
HOST = ""
HEADER = "HTTP/1.1 200 OK\n"
HEADER+= "Content-Disposition: inline; filename=\""+filename+"\"\n"
HEADER+= "Connection: close\n\n"
file_content = open(filename).read()
############## IP LOG STUFF ########################
# Find out my IP
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("google.com",80))
myIP = s.getsockname()[0]
s.close()
print "Beaming %s to %s:%d" % (filename, myIP, PORT)
##################### ACTUAL WORK ###################
# Make a server socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = (HOST, PORT)
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
for beam_number in range(1, beam_count+1): # Beam the file beam_count times
print "Waiting for a connection... (%d/%d)" % (beam_number, beam_count)
connection, client_address = sock.accept() # Client connected
print "%s:%s connected" % client_address
connection.sendall(HEADER)
connection.sendall(file_content)
sleep(1)
print "Closing connection"
connection.close() # Close current connection
################# DONE #######################
sock.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment