6060
6161DECODE_EXCEPTIONS = (IndexError , struct .error , IncomingDecodeError )
6262
63- UNPACK_3H = struct .Struct (b'!3H' ).unpack_from
64- UNPACK_6H = struct .Struct (b'!6H' ).unpack_from
65- UNPACK_HH = struct .Struct (b'!HH' ).unpack_from
66- UNPACK_HHiH = struct .Struct (b'!HHiH' ).unpack_from
6763
6864_seen_logs : Dict [str , Union [int , tuple ]] = {}
6965_str = str
@@ -207,24 +203,35 @@ def __repr__(self) -> str:
207203 ]
208204 )
209205
206+ def _read_short (self ) -> _int :
207+ """Reads an unsigned short in network order from the packet."""
208+ offset = self .offset
209+ view = self .view
210+ self .offset += 2
211+ return view [offset ] << 8 | view [offset + 1 ]
212+
213+ def _read_long (self ) -> _int :
214+ """Reads an unsigned long in network order from the packet."""
215+ offset = self .offset
216+ view = self .view
217+ self .offset += 4
218+ return view [offset ] << 24 | view [offset + 1 ] << 16 | view [offset + 2 ] << 8 | view [offset + 3 ]
219+
210220 def _read_header (self ) -> None :
211221 """Reads header portion of packet"""
212- (
213- self .id ,
214- self .flags ,
215- self .num_questions ,
216- self .num_answers ,
217- self .num_authorities ,
218- self .num_additionals ,
219- ) = UNPACK_6H (self .data )
220- self .offset += 12
222+ self .id = self ._read_short ()
223+ self .flags = self ._read_short ()
224+ self .num_questions = self ._read_short ()
225+ self .num_answers = self ._read_short ()
226+ self .num_authorities = self ._read_short ()
227+ self .num_additionals = self ._read_short ()
221228
222229 def _read_questions (self ) -> None :
223230 """Reads questions section of packet"""
224231 for _ in range (self .num_questions ):
225232 name = self ._read_name ()
226- type_ , class_ = UNPACK_HH ( self .data , self . offset )
227- self . offset += 4
233+ type_ = self ._read_short ( )
234+ class_ = self . _read_short ()
228235 question = DNSQuestion (name , type_ , class_ )
229236 self .questions .append (question )
230237
@@ -249,8 +256,10 @@ def _read_others(self) -> None:
249256 n = self .num_answers + self .num_authorities + self .num_additionals
250257 for _ in range (n ):
251258 domain = self ._read_name ()
252- type_ , class_ , ttl , length = UNPACK_HHiH (self .data , self .offset )
253- self .offset += 10
259+ type_ = self ._read_short ()
260+ class_ = self ._read_short ()
261+ ttl = self ._read_long ()
262+ length = self ._read_short ()
254263 end = self .offset + length
255264 rec = None
256265 try :
@@ -284,7 +293,9 @@ def _read_record(
284293 if type_ == _TYPE_TXT :
285294 return DNSText (domain , type_ , class_ , ttl , self ._read_string (length ), self .now )
286295 if type_ == _TYPE_SRV :
287- priority , weight , port = UNPACK_3H (self .data , self .offset )
296+ priority = self ._read_short ()
297+ weight = self ._read_short ()
298+ port = self ._read_short ()
288299 self .offset += 6
289300 return DNSService (
290301 domain ,
0 commit comments