我想使用原始tcp包来ping地址。
我创建了一个TCP程序包,但我无法发送。
在Windows上出现操作系统错误。在Linux上,不支持该协议。
可能是什么问题?
class Packet:
def __init__(self, dest_ip, dest_port):
############
# IP segment
#############
# TCP segment
########
# packet
def calc_checksum(self, msg):
s = 0
for i in range(0, len(msg), 2):
w = (msg[i] << 8) + msg[i + 1]
s = s + w
s = (s >> 16) + (s & 0xffff)
s = ~s & 0xffff
return s
def generate_tmp_ip_header(self):
tmp_ip_header = pack("!BBHHHBBH4s4s", self.v_ihl, self.type_of_service, self.total_length,
self.identification, self.f_fo,
self.ttl, self.protocol, self.header_checksum,
self.src_addr,
self.dest_addr)
return tmp_ip_header
def generate_tmp_tcp_header(self):
tmp_tcp_header = pack("!HHLLHHHH", self.src_port, self.dest_port,
self.seq_no,
self.ack_no,
self.data_offset_res_flags, self.window_size,
self.checksum, self.urg_pointer)
return tmp_tcp_header
def generate_packet(self):
# IP header + checksum
final_ip_header = pack("!BBHHHBBH4s4s", self.v_ihl, self.type_of_service, self.total_length,
self.identification, self.f_fo,
self.ttl, self.protocol, self.calc_checksum(self.generate_tmp_ip_header()),
self.src_addr,
self.dest_addr)
# TCP header + checksum
tmp_tcp_header = self.generate_tmp_tcp_header()
pseudo_header = pack("!4s4sBBH", self.src_addr, self.dest_addr, self.checksum, self.protocol,
len(tmp_tcp_header))
psh = pseudo_header + tmp_tcp_header
final_tcp_header = pack("!HHLLHHHH", self.src_port, self.dest_port,
self.seq_no,
self.ack_no,
self.data_offset_res_flags, self.window_size,
self.calc_checksum(psh), self.urg_pointer)
self.ip_header = final_ip_header
self.tcp_header = final_tcp_header
self.packet = final_ip_header + final_tcp_header
def send_packet(self):
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)
s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
s.sendto(self.packet, (self.dest_ip, 1))
data = s.recv(1024)
s.close()
return data
我已经在ICMP软件包上写了ping,并且一切正常