python
import socket
import random
import struct
# 创建原始套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
# 设置目标地址和端口
target_address = ('127.0.0.1', 12345)
# 构造IP头部
ip_version = 4
ip_header_length = 5
ip_type_of_service = 0
ip_total_length = 40 # 总长度 = IP头部长度 + TCP头部长度
ip_identification = random.randint(1, 65535)
ip_flags = 0
ip_fragment_offset = 0
ip_ttl = 255
ip_protocol = socket.IPPROTO_TCP
ip_source_address = '127.0.0.1'
ip_destination_address = target_address[0]
ip_header = struct.pack('!BBHHHBBH4s4s',
(ip_version << 4) + ip_header_length,
ip_type_of_service,
ip_total_length,
ip_identification,
(ip_flags << 13) + ip_fragment_offset,
ip_ttl,
ip_protocol,
0,
socket.inet_aton(ip_source_address),
socket.inet_aton(ip_destination_address))
# 构造TCP头部
tcp_source_port = random.randint(1024, 65535)
tcp_destination_port = target_address[1]
tcp_sequence_number = 0
tcp_acknowledgment_number = 0
tcp_data_offset = 5
tcp_flags = 2 # 设置SYN标志
tcp_window = socket.htons(5840)
tcp_header = struct.pack('!HHLLBBSH',
tcp_source_port,
tcp_destination_port,
tcp_sequence_number,
tcp_acknowledgment_number,
(tcp_data_offset << 4) + 0,
tcp_flags,
tcp_window,
0)
# 计算校验和
pseudo_header = struct.pack('!4s4sBBH',
socket.inet_aton(ip_source_address),
socket.inet_aton(ip_destination_address),
0,
ip_protocol,
len(tcp_header))
checksum = 0
for i in range(0, len(pseudo_header), 2):
checksum += (pseudo_header[i] << 8) + pseudo_header[i + 1]
for i in range(0, len(tcp_header), 2):
checksum += (tcp_header[i] << 8) + tcp_header[i + 1]
checksum = (checksum >> 16) + (checksum & 0xffff)
checksum = ~checksum & 0xffff
tcp_header = struct.pack('!HHLLBBSH',
tcp_source_port,
tcp_destination_port,
tcp_sequence_number,
tcp_acknowledgment_number,
(tcp_data_offset << 4) + 0,
tcp_flags,
tcp_window,
checksum)
# 发送TCP SYN报文
sock.sendto(ip_header + tcp_header, target_address)
# 关闭socket
sock.close()