IP パケットが書き込まれたバイナリ ファイルがあります。IP パケットの各フィールドを検証する必要がある Python プログラムを作成する必要があるため、ファイル (Ip パケット) から各フィールドを解析しようとしています。私が抱えている問題は、長さが 4 ビットの 2 つのフィールド (パケットの最初の 2 つのフィールド) があることですが、アンパックできる最小のデータ (struct.pack) は 1 バイトです。したがって、パケットからビットを抽出するためにビットをビットマスクしようとしていましたが、ビットのフローが文字列と見なされ、ビットマスクで実行している AND 演算が整数。誰かが、長いビット列から最初と 2 番目の 4 ビット ワードを抽出する方法の手がかりを持っていますか?
これまでの私のコードは次のとおりです。
while True:
try:
filename=raw_input('Enter the name of the file where the packet is: ')
break
except EOFError as e:
pass
print "You didn't enter a valid file name"
#Reading packet from file and converting to little endian accordingly
with open(filename, 'rb') as f:
for line in f.readlines():
mask1=0b1111
mask2=0b00001111
bit_hl=line & mask1
bit_v= line & mask2
pk_hl= struct.unpack('@B', bit_hl) #ip_hl
print('\n',pk_hl)
pk_v = struct.unpack('@B', bit_v) #ip_v
print('\n',pk_v)
....
パケットは C++ プログラムから生成され、パケットの構造は次のとおりです。
struct cip {
uint8_t ip_hl:4, /* both fields are 4 bits */
ip_v:4;
uint8_t ip_tos;
uint16_t ip_len;
uint16_t ip_id;
uint16_t ip_off;
uint8_t ip_ttl;
uint8_t ip_p;
uint16_t ip_sum;
struct in_addr ip_src;
struct in_addr ip_dst;
char head[100];
};
ありがとうございました。