-1
私のコードに問題があります。 私は、単純なTCPパケットスニファを書き、私はこのコードでTCPパケットのフラグを表示する必要があります。Pythonでtcpフラグを使うには
import socket
import struct
server = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)
while True:
packet = server.recvfrom(65565)
packet = packet[0]
print "Packing data: "
print "\n", packet
ip_header = packet[0:20]
ip_unpack = struct.unpack('!BBHHHBBH4s4s' , ip_header)
print "\n Unpack ip header"
print ip_unpack
version_ihl = ip_unpack[0]
version = version_ihl >> 4
ihl = version_ihl & 0xF
print ihl
ip_ihl = ihl * 4
print ip_ihl
def getflags(packet):
Flag_URG = {1: "URG-Urgent flag)"}
Flag_ACK = {1: "ACK-Acknowledgment flag"}
Flag_PSH = {1: "PSH-Push flag"}
Flag_RST = {1: "RST-Reset flag"}
Flag_SYN = {1: "SYN-Synchronize flag"}
Flag_FIN = {1: "FIN-End of data flag"}
URG = packet & 0x020
URG >>= 5
ACK = packet & 0x010
ACK >>= 4
PSH = packet & 0x008
PSH >>= 3
RST = packet & 0x004
RST >>= 2
SYN = packet & 0x002
SYN >>= 1
FIN = packet & 0x001
FIN >>= 0
new_line = "\n"
Flags = Flag_URG[URG] + new_line + Flag_ACK[ACK] + new_line + Flag_PSH[PSH] + new_line + Flag_RST[RST] + new_line + Flag_SYN[SYN] + new_line + Flag_FIN[FIN]
return Flags
#tcp
tcp_header = packet[ip_ihl:ip_ihl+20]
tcp_unpack = struct.unpack("!HHLLBBHHH", tcp_header)
print "\nUnpack TCP header: "
print "\n", tcp_unpack
tcp_length = tcp_unpack[4] >> 4
print "source port: ", tcp_unpack[0]
print "destination port: ", tcp_unpack[1]
print "sequence number: ", tcp_unpack[2]
print "ack number: ", tcp_unpack[3]
print "dataoffset: ", tcp_unpack[4]
print "tcp length: ", tcp_length
print "flag: ", getflags(tcp_unpack[3])
header_size = ip_ihl + tcp_length * 4
data_size = len(packet) - header_size
data = packet[header_size:]
print "data:"
print "\n", data
が、私はこのエラーがあります:
Traceback (most recent call last):
File "tcp.py", line 67, in <module>
print "flag: ", getflags(tcp_unpack[3])
File "tcp.py", line 49, in getflags
Flags = Flag_URG[URG] + new_line + Flag_ACK[ACK] + new_line + Flag_PSH[PSH] + new_line + Flag_RST[RST] + new_line + Flag_SYN[SYN] + new_line + Flag_FIN[FIN]
KeyError: 0L
はどのようにこの問題を解決することができましたか?どのようにフラグとecnをtcpパケットに使用できますか?