while True: data, addr = server.recvfrom(4096) #print(addr, data) ip = IP(data) ip_len = ip.get_size() tcp = TCP(data[ip_len:]) if tcp.get_th_dport() == 1234: print('state', state) #buf = tcp.get_packet() #print([hex(n)[2:] for n in buf]) print(tcp, tcp.get_th_seq(), tcp.get_th_ack()) if state == 0: ip, tcp = reply(ip, tcp) tcp.set_th_ack(tcp.get_th_seq() + 1) tcp.set_th_seq(0) #print('###', tcp.get_th_seq()) tcp.set_ACK() tcp.calculate_checksum() buf = ip.get_packet() print(tcp, tcp.get_th_seq(), tcp.get_th_ack()) server.sendto(buf, ('127.0.0.1', 0)) state = 1 elif state == 1: if tcp.get_SYN() or not tcp.get_ACK(): break print('connected...') state = 2 elif state == 2: if tcp.get_FIN(): ip, tcp = reply(ip, tcp)