from socket import sockaddr
except:
    sockaddr = lambda x: x

UPNP_MCAST_IP = "239.255.255.250"
UPNP_PORT = 1900

M_SEARCH = b"""\
M-SEARCH * HTTP/1.1\r
Host: 239.255.255.250:1900\r
MAN: ssdp:discover\r
ST: upnp:rootdevice\r
MX: 2\r
\r
"""
#ST: ssdp:all\r

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

addrs = socket.getaddrinfo(UPNP_MCAST_IP, UPNP_PORT, socket.AF_INET, socket.SOCK_DGRAM)
#for a in addrs:
#    print(a)

s.sendto(M_SEARCH, addrs[0][4])

while True:
    data, addr = s.recvfrom(1024)
    print("Received from:", sockaddr(addr))
    #print(hexlify(addr))
    print(str(data, "utf-8"))
import socket

print("AF_INET: {} -- AF_INET6: {}".format(socket.AF_INET, socket.AF_INET6))

addrs = socket.getaddrinfo("google.com", 123)
for a in addrs:
    print(a[0], a[3], socket.inet_ntop(socket.AF_INET,
                                       socket.sockaddr(a[4])[1]))
    print(a[0], a[3], socket.sockaddr(a[4]))
def get_hostport(addr):
    if isinstance(addr, tuple):
        return addr

    af, addr, port = socket.sockaddr(addr)
    return inet_ntop(af, addr), port
示例#4
0
def get_hostport(addr):
    if isinstance(addr, tuple):
        return addr

    af, addr, port = socket.sockaddr(addr)
    return inet_ntop(af, addr), port
# for responses.
REUSE_SOCKET = 0

UPNP_RESPONSE = b"""HTTP/1.1 200 OK\r
CACHE-CONTROL: max-age=100\r
EXT:\r
Location: http://localhost:8080/description.xml\r
Server: dummy/1.0, UPnP/1.0\r
ST: upnp:rootdevice\r
USN: uuid:12345678-9abc-1111-2222-foo::upnp:rootdevice\r
\r
"""


serv_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

addr = socket.getaddrinfo(BIND_IP, UPNP_PORT, socket.AF_INET, socket.SOCK_DGRAM)[0][4]
serv_sock.bind(addr)
serv_sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(UPNP_MCAST_IP) + socket.inet_aton(BIND_IP));
if REUSE_SOCKET:
    resp_sock = serv_sock
else:
    resp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

while True:
    data, addr = serv_sock.recvfrom(1024)
    if data.startswith(b"M-SEARCH"):
        print("From: ", sockaddr(addr))
        print(data)
        resp_sock.sendto(UPNP_RESPONSE, addr)