#!/usr/bin/python import socket def get_headers(sock): buff = "" cnt = 0 while(cnt != 4): byte = sock.recv(1) bytenum = ord(byte) if bytenum == 10 or bytenum == 13: cnt = cnt + 1 else: cnt = 0 buff += byte headers = {} lines = buff.split("\n") for line in lines: line = line.rstrip() lineprts = line.split(":") if len(lineprts) == 2: headers[lineprts[0]] = lineprts[1] return headers def get_fixed_bytes(sock, num): buff = "" got = 0 while(got < num): toget = num - got data = sock.recv(toget) got = got + len(data) buff = buff + data return buff def parse_meta(str): rtv = {} metas = str.split(";") for meta in metas: meta = meta.rstrip() if len(meta) > 2: metaprts = meta.split("=") if len(metaprts) == 2: rtv[metaprts[0]] = metaprts[1].lstrip("'").rstrip("'").replace("\\'", "'") return rtv def get_shoutcast_meta(host, port): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, port)) sock.send("GET / HTTP/1.0\nIcy-MetaData:1\n\n") headers = get_headers(sock) metaint = int(headers['icy-metaint']) data = get_fixed_bytes(sock, metaint) metalenstr = sock.recv(1) metalen = ord(metalenstr) * 16 meta = get_fixed_bytes(sock, metalen) metas = parse_meta(meta) sock.close() sockopen = False return {'headers': headers, 'metas': metas} host = "stream.example.com" port = 8008 print get_shoutcast_meta(host, port)