Skip to content

Stream redirection in Python

September 6, 2006

Two computers are on the same network. A firewall segregates the internet from the intranet. Both computers can access everything on the intranet but only one of them is allowed to access the internet. The problem is to listen to a music stream from the computer that cannot access the internet.

A possible solution is to run a stream redirection software on the computer that can access the internet. Then the computer that cannot access the internet can get the stream from the intranet (figure below).

illustration of the redirection

Since I begin to play with Python, I tried to write such software with this language. Here is the code (preset for a Belgian radio, Pure FM):

#!/usr/bin/python
import socket
import traceback
import urllib2

# get the right input stream (in case it changes everyday)
# change the address to suit your need (yes: user input needed!)
address = "http://old.rtbf.be/rtbf_2000/radios/pure128.m3u"
content = urllib2.urlopen(address)
stream = content.readlines()
stream = stream[0][7:len(stream[0])-1]
inHost = stream[0:stream.index(":")]
inPort = int(stream[stream.index(":")+1:stream.index("/")])
inPath = stream[stream.index("/"):len(stream)]

# set output stream (default is localhost:50008)
outHost = ''
outPort = 50008

# get the in/out sockets
inSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
inSock.connect((inHost, inPort))
outSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
outSock.bind((outHost, outPort))

outSock.listen(1)
outNewSock, outAddress = outSock.accept()

# get the info from a *file*, not a simple host URL ...
inSock.send("GET " + inPath + " HTTP/1.0\r\nHost: " + inHost + "\r\n\r\n")

try:
    while 1:
        inData = inSock.recv(2048)
        if not inData:
            print "No data"
        else:
            print "Read ", len(inData), " bytes"
        outNewSock.send(inData)
        print "Sent data to out"
except Exception:
    traceback.print_exc()

# not really needed since program will stop by Ctrl+C or sth like that:
outNewSock.close()
outSock.close()
inSock.close()

Now the computer that doesn’t have access to the internet can connect to port 50008 on the other computer to get the stream and listen to music. It was quite simple.

Note that if you are trying this within IDLE on MS-Windows, you’ll get some errors because of problems in the synchronisation of the mpeg stream.

From → Projects

Comments are closed.

%d bloggers like this: