import os, socket, struct, sys

CP = bytes.fromhex("F4ED19E0C114EB516FAAAC0EE37DAF2807B4381F")
CCC = bytes.fromhex("DEFB99E69A9F1F6E06F15006B1F166AE")
FRAG = bytes.fromhex("4048B7D56EBCE88525E7DE7F00D6C2D3")


def pl(nxt, body):
    return struct.pack(">BBH", nxt, 0, 4 + len(body)) + body


def attrs(enc=7, klen=256, hashv=2, auth=3, dh=2, life=True):
    a = struct.pack(">HH", 0x8000 | 1, enc)
    a += struct.pack(">HH", 0x8000 | 2, hashv)
    a += struct.pack(">HH", 0x8000 | 3, auth)
    a += struct.pack(">HH", 0x8000 | 4, dh)
    a += struct.pack(">HH", 0x8000 | 14, klen)
    if life:
        a += struct.pack(">HH", 0x8000 | 11, 1)
        a += struct.pack(">HH", 0x0000 | 12, 4) + struct.pack(">I", 28800)
    return a


def sa_payload():
    a = attrs()
    tr = struct.pack(">BBH", 0, 0, 8 + len(a)) + struct.pack(">BBBB", 1, 1, 0, 0) + a
    prop = struct.pack(">BBHBBBB", 0, 0, 8 + len(tr), 1, 1, 0, 1) + tr
    return struct.pack(">II", 1, 1) + prop


def build(vids=True):
    parts = [sa_payload()]
    if vids:
        parts.append(CP + struct.pack(">IIIII", 2, 0, 0, 0, 0))
        parts.append(CCC)
        parts.append(FRAG)
    types = [1, 13, 13, 13][:len(parts)]
    body = b""
    for i, b in enumerate(parts):
        nxt = types[i + 1] if i + 1 < len(parts) else 0
        body += pl(nxt, b)
    return struct.pack(">QQBBBBII", int.from_bytes(os.urandom(8), "big"), 0, 1, 0x10, 2, 0, 0, 28 + len(body)) + body


def vids_of(d):
    out = []
    off, cur = 28, d[16]
    while cur and off + 4 <= len(d):
        nxt, _, ln = struct.unpack(">BBH", d[off:off + 4])
        if ln < 4 or off + ln > len(d):
            break
        if cur == 13:
            out.append(d[off + 4:off + ln].hex()[:40])
        cur = nxt
        off += ln
    return out


for ip in sys.argv[1:]:
    for label, v in (("novid", False), ("vid", True)):
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.bind(("0.0.0.0", 500))
        s.settimeout(4)
        s.sendto(build(v), (ip, 500))
        try:
            d, _ = s.recvfrom(8192)
            print("%s %s len=%d exch=%d np=%d vids=%s" % (ip, label, len(d), d[18], d[16], ",".join(vids_of(d))), flush=True)
        except Exception as e:
            print("%s %s ERR %s" % (ip, label, type(e).__name__), flush=True)
        s.close()
