仅当协议为TCP时,Wireshark才能捕获原始套接字

时间:2019-05-31 09:46:45

标签: sockets tcp python-3.6 raw-sockets

我试图发送原始套接字数据包,编写自己的IP标头和TCP标头,当IP标头中的ip_protocol设置为除6(即TCP)以外的任何数字时,wireshark可以捕获数据包

我正在Windows 10和python 3.6.8上工作。 我的源IP和目标IP都是localhost。 我也尝试过关闭防火墙,但没有帮助。 IP协议不是6的任何数据包都可以正常捕获。 仅当我设置ip_protocol = 6时,Wireshark才能捕获数据包。

这是创建IP标头的一部分

def GenerateIPHeader(ip_source, ip_dest):
    ip_ver = 4              # ipv4
    ip_ihl = 5              # Header Length = 5, no option
    ip_dscp = 0             # dscp (type of service)
    ip_total_len = 0        # left for kernel to fill
    ip_id = 0               # fragment
    ip_frag_offset = 0      # fragment
    ip_ttl = 255            # Time to live
    ip_protocol = 6         # TCP = 6
    ip_checksum = 0         # left for kernel to fill
    ip_saddr = socket.inet_aton(ip_source)
    ip_daddr = socket.inet_aton(ip_dest)
    ip_ver_ihl = (ip_ver << 4) + ip_ihl 
    ip_header = struct.pack('!BBHHHBBH4s4s' , ip_ver_ihl, ip_dscp, ip_total_len, ip_id, ip_frag_offset, ip_ttl, ip_protocol, ip_checksum, ip_saddr, ip_daddr)
    return ip_header

这是创建数据包的一部分

def GeneratePacket(SrcAddr, SrcPort, DestAddr, DestPort, payload = ''):
    if len(payload) % 2 == 1:
        payload += " "
    IPHeader = GenerateIPHeader(SrcAddr, DestAddr)
    TCPHeader = GenerateTCPHeader(SrcPort, DestPort)
    PseudoIPHEader = GeneratePseudoIPHeader(SrcAddr, DestAddr, TCPHeader, payload)
    Checksum = b"".join([PseudoIPHEader, TCPHeader, payload.encode()])
    TCPChecksum = CalculateChecksum(Checksum)
    TCPHeader = GenerateTCPHeader(SrcPort, DestPort, TCPChecksum)
    TCPPacket = b"".join([TCPHeader, payload.encode()])
    packet = b"".join([IPHeader, TCPPacket])
    return packet

这是创建套接字的一部分

def StartClient(SrcAddr, SrcPort, DestAddr, DestPort):
    try:
        Client = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
    except socket.error as msg:
        print('Socket could not be created. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
        sys.exit()
    Client.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)  #Set it to include the header
    Client.bind((SrcAddr, SrcPort))

    Packet = GeneratePacket(SrcAddr, SrcPort, DestAddr, DestPort, 'Hello!')

    print(Packet)
    Client.sendto(Packet, (DestAddr, DestPort))

0 个答案:

没有答案