import os, socket, struct

BASE = bytes.fromhex(
    "0000000000000000"          # init cookie placeholder
    "0000000000000000"          # resp cookie
    "01100200"                  # np=1 SA, ver 10, main mode, flags 0
    "00000000"                  # msgid
    "00000058"                  # length 88
    "0000003c"                  # SA np=0 res=0 len=60
    "00000001" "00000001"       # DOI, situation
    "00000030"                  # prop np=0 res=0 len=48
    "01010001"                  # num=1 proto=1 spi=0 ntrans=1
    "00000028"                  # transform np=0 res=0 len=40
    "01010000"                  # num=1 id=1
    "80010007" "80020002" "80030003" "80040002" "800e0100"
    "800b0001" "000c0004" "00007080"
)


def send(pkt, ip="60.248.18.205"):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind(("0.0.0.0", 500))
    s.settimeout(4)
    s.sendto(pkt, (ip, 500))
    try:
        d, _ = s.recvfrom(8192)
        return "len=%d exch=%d" % (len(d), d[18])
    except Exception as e:
        return "ERR %s" % type(e).__name__
    finally:
        s.close()


def mk(cookie, life_flag=0x000c, res=0x00):
    p = bytearray(BASE)
    p[0:8] = cookie
    p[19] = res          # reserved byte of SA payload header (offset 28+1)
    p[28 + 4 + 0] = 0
    p[28 + 36 + 4 + 14] = 0
    return bytes(p)


p0 = bytearray(BASE)
p0[0:8] = os.urandom(8)
print("exact  ike-scan-like:", send(bytes(p0)), p0[:4].hex())

p1 = bytearray(BASE)
p1[0:8] = os.urandom(8)
p1[29] = 0x01   # reserved byte of SA payload header = 1 (my earlier style)
print("sa res=1            :", send(bytes(p1)))

p2 = bytearray(BASE)
p2[0:8] = os.urandom(8)
p2[-6:-4] = b"\x80\x0c"
print("life 0x800c         :", send(bytes(p2)))
