def ip_packet(payload, src_ip, dst_ip, protocol=chr(ip_constants.IPV4_PROTOCOL_UDP)):
    """
    Create an IPv4 packet.

    :type payload: str
    :param payload: Contents of next layer up.

    :type src_ip: str
    :param src_ip: 4-byte source IP address.

    :type dst_ip: str
    :param dst_ip: 4-byte destination IP address.

    :type protocol: str
    :param protocol: Single-byte string identifying next layer's protocol. Default "\x11" UDP.

    :return: IPv4 packet.
    :rtype: str
    """
    ip_header = "\x45"  # Version | Header Length
    ip_header += "\x00"  # "Differentiated Services Field"
    ip_header += struct.pack(">H", IP_HEADER_LEN + len(payload))  # Length
    ip_header += "\x00\x01"  # ID Field
    ip_header += "\x40\x00"  # Flags, Fragment Offset
    ip_header += "\x40"  # Time to live
    ip_header += protocol
    ip_header += "\x00\x00"  # Header checksum (fill in zeros in order to compute checksum)
    ip_header += src_ip
    ip_header += dst_ip

    checksum = struct.pack(">H", helpers.ipv4_checksum(ip_header))
    ip_header = ip_header[:10] + checksum + ip_header[12:]

    return ip_header + payload
Beispiel #2
0
def ip_packet(payload, src_ip, dst_ip, protocol=six.int2byte(ip_constants.IPV4_PROTOCOL_UDP)):
    """
    Create an IPv4 packet.

    :type payload: bytes
    :param payload: Contents of next layer up.

    :type src_ip: bytes
    :param src_ip: 4-byte source IP address.

    :type dst_ip: bytes
    :param dst_ip: 4-byte destination IP address.

    :type protocol: bytes
    :param protocol: Single-byte string identifying next layer's protocol. Default "\x11" UDP.

    :return: IPv4 packet.
    :rtype: bytes
    """
    ip_header = b"\x45"  # Version | Header Length
    ip_header += b"\x00"  # "Differentiated Services Field"
    ip_header += struct.pack(">H", IP_HEADER_LEN + len(payload))  # Length
    ip_header += b"\x00\x01"  # ID Field
    ip_header += b"\x40\x00"  # Flags, Fragment Offset
    ip_header += b"\x40"  # Time to live
    ip_header += protocol
    ip_header += b"\x00\x00"  # Header checksum (fill in zeros in order to compute checksum)
    ip_header += src_ip
    ip_header += dst_ip

    checksum = struct.pack(">H", helpers.ipv4_checksum(ip_header))
    ip_header = ip_header[:10] + checksum + ip_header[12:]

    return ip_header + payload