【问题标题】:"OSError: [WinError 10022] An invalid argument was supplied" when trying to send TCP SYN packet (python)“OSError:[WinError 10022] 提供了无效参数”尝试发送 TCP SYN 数据包(python)
【发布时间】:2022-01-07 23:05:18
【问题描述】:

目前尝试使用原始套接字在 python 上进行握手过程,但由于某种原因,我无法发送任何带有 TCP 协议接收 OSError: [WinError 10022] 提供的参数无效的数据包。这是我的代码:

s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)
s.sendto(packet, ('8.8.8.8', 80))

作为数据包,我尝试使用 scapy 的 TCP 数据包,在与其他库成功发送后来自wireshark 的 TCP 字节以及手工制作的字节字符串:

def chksum(packet: bytes) -> int:
    if len(packet) % 2 != 0:
        packet += b'\0'

    res = sum(array.array("H", packet))
    res = (res >> 16) + (res & 0xffff)
    res += res >> 16

    return (~res) & 0xffff


class TCPPacket:
    def __init__(self,
                 src_host:  str,
                 src_port:  int,
                 dst_host:  str,
                 dst_port:  int,
                 flags:     int = 0):
        self.src_host = src_host
        self.src_port = src_port
        self.dst_host = dst_host
        self.dst_port = dst_port
        self.flags = flags

    def build(self) -> bytes:
        packet = struct.pack(
            '!HHIIBBHHH',
            self.src_port,  # Source Port
            self.dst_port,  # Destination Port
            0,              # Sequence Number
            0,              # Acknoledgement Number
            5 << 4,         # Data Offset
            self.flags,     # Flags
            8192,           # Window
            0,              # Checksum (initial value)
            0               # Urgent pointer
        )

        pseudo_hdr = struct.pack(
            '!4s4sHH',
            socket.inet_aton(self.src_host),    # Source Address
            socket.inet_aton(self.dst_host),    # Destination Address
            socket.IPPROTO_TCP,                 # PTCL
            len(packet)                         # TCP Length
        )

        checksum = chksum(pseudo_hdr + packet)

        packet = packet[:16] + struct.pack('H', checksum) + packet[18:]

        return packet

所以真的不知道为什么我的套接字不喜欢任何数据包

【问题讨论】:

标签: python sockets tcp protocols handshake


【解决方案1】:

我发现出了什么问题。 Windows 不允许使用原始套接字发送 TCP 数据包,因此此代码将永远无法工作。可能可以使用 scapy 或使用其他库来编写相同的内容,但这不是我需要的,因此使其工作的唯一方法是在 linux 上运行。仍然不确定数据包创建是否正确,但带有原始套接字的 TCP 协议在 linux 上确实可以正常工作。

【讨论】:

    猜你喜欢
    • 2017-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    • 2017-03-19
    • 2016-08-12
    • 1970-01-01
    • 2016-10-25
    相关资源
    最近更新 更多