我有一个Python项目,我需要将简单的TCP SYN消息发送到IPv6地址并使用原始套接字。我的脚本可以无误地执行,但没有发送syn包。我在我的脚本中不确定IPv6标头,TCP标头或IPv6原始套接字出错了。网络配置为IPv6,因此可以排除网络问题。
这是我的脚本,我在RHEL 5上使用Python 2.4:
import socket, sys
from struct import *
# checksum functions needed for calculation checksum
def checksum(msg):
s = 0
# loop taking 2 characters at a time
for i in range(0, len(msg), 2):
w = (ord(msg[i]) << 8) + (ord(msg[i+1]) )
s = s + w
s = (s>>16) + (s & 0xffff);
s = ~s & 0xffff
return s
def init_tcp_syn_packet_v6(source_port,dest_port, source_ip, dest_ip):
packet = '';
# ip header fields
version = 6 #4 bit
traffic_class = 0 #8 bit
flow_level = 1 #20 bit
payload_len = 20 #not true lenght, I just selected a random value #16 bit
next_header = socket.IPPROTO_TCP #8 bit
hop_limit = 255 #8 bit
saddr = socket.inet_pton ( socket.AF_INET6, source_ip ) #128 bit
daddr = socket.inet_pton ( socket.AF_INET6, dest_ip ) #128 bit
ver_traff_flow = (version << 8) + traffic_class
ver_traff_flow = (ver_traff_flow << 20) + flow_level
ip_header = pack( '!IHBB', ver_traff_flow, payload_len, next_header, hop_limit)
ip_header = ip_header + saddr + daddr
# tcp header fields
seq = 0
ack_seq = 0
doff = 5 #4 bit field, size of tcp header, 5*4 = 20 bytes
#tcp flags
fin = 0
syn = 1
rst = 0
psh = 0
ack = 0
urg = 0
window = socket.htons (5840) #maximum allowed window size
check = 0
urg_ptr = 0
offset_res = (doff << 4) + 0
tcp_flags = fin + (syn << 1) + (rst << 2) + (psh <<3) + (ack << 4) + (urg << 5)
tcp_header = pack('!HHLLBBHHH' , source_port, dest_port, seq, ack_seq, offset_res, tcp_flags, window, check, urg_ptr)
source_address = socket.inet_pton( socket.AF_INET6, source_ip )
dest_address = socket.inet_pton( socket.AF_INET6, dest_ip )
placeholder = 0
protocol = socket.IPPROTO_TCP
tcp_length = len(tcp_header)
psh = source_address + dest_address + pack('!BBH' , placeholder , protocol , tcp_length);
psh = psh + tcp_header;
tcp_checksum = checksum(psh)
# make the tcp header again and fill the correct checksum
tcp_header = pack('!HHLLBBHHH' , source_port, dest_port, seq, ack_seq, offset_res, tcp_flags, window, tcp_checksum , urg_ptr)
packet = ip_header + tcp_header
return packet
#main
#create raw socket v6
s = socket.socket(socket.AF_INET6, socket.SOCK_RAW, socket.IPPROTO_TCP)
s.setsockopt(socket.IPPROTO_IPV6, socket.IP_HDRINCL, 1)
#send syn packet
packet = init_tcp_syn_packet_v6( 1235, 80, '2001:172:22:5::31','2014:2008:0:c::284a:78a4')