如何在Python中使用原始套接字

时间:2016-01-12 13:09:59

标签: python python-3.x tcp-ip

我尝试通过python3中的原始套接字发送自制的tcp-packet(使用windows 10)。在ip-header内部我想将协议设置为TCP(= 6)。

我发送的paket是:

E\x00\x00\x00\xd41\x00\x00\xff\x06\x00\x00\xc0\xa8\xb29\xc0\xa8\xb2\x01 

但是我收到了(和wireshark检测到相同的)

E\x00\x00FN\xe7\x00\x00\x80\xff\x00\x00\n\xac\x02e\n\xac

现在它是255(未知)

srcport = 11001

def sendTCP(dest_ip, dest_port,fin, syn, rst, psh, ack, urg):

    payload = b'[TESTING]\n'

    ip = make_ip(socket.IPPROTO_TCP, source_ip, dest_ip)
    tcp = make_tcp(srcport, dest_port, payload, 123, 0, fin, syn, rst, psh, ack, urg)
    packet = ip + tcp + payload

    s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
    s.sendto(packet, (dest_ip, 0))

    ans = s.recv(1024)
    print(ans)


def make_ip(proto, srcip, dstip, ident=54321):
    saddr = socket.inet_aton(srcip)
    daddr = socket.inet_aton(dstip)
    ihl_ver = (4 << 4) | 5
    return struct.pack('!BBHHHBBH4s4s' , 
                   ihl_ver, 0, 0, ident, 0, 255, proto, 0, saddr, daddr)

def make_tcp(srcport, dstport, payload, seq=123, ackseq=0,
         fin=False, syn=False, rst=False, psh=False, ack=False, urg=False,
         window=5840):
    offset_res = (5 << 4) | 0
    flags = (fin | (syn << 1) | (rst << 2) | 
         (psh <<3) | (ack << 4) | (urg << 5))
    return struct.pack('!HHLLBBHHH', 
                   srcport, dstport, seq, ackseq, offset_res, 
                   flags, window, 0, 0)

if __name__ == '__main__':
    sendTCP('10.172.2.101',80, False, True, False, False, False, False)

0 个答案:

没有答案