4747
4848DECODE_EXCEPTIONS = (IndexError , struct .error , IncomingDecodeError )
4949
50+ UNPACK_3H = struct .Struct (b'!3H' ).unpack
51+ UNPACK_6H = struct .Struct (b'!6H' ).unpack
52+ UNPACK_HH = struct .Struct (b'!HH' ).unpack
53+ UNPACK_HHiH = struct .Struct (b'!HHiH' ).unpack
54+
5055
5156class DNSIncoming (DNSMessage , QuietLogger ):
5257
@@ -139,9 +144,9 @@ def __repr__(self) -> str:
139144 ]
140145 )
141146
142- def unpack (self , format_ : bytes , length : int ) -> tuple :
147+ def unpack (self , unpacker : Callable [[ bytes ], tuple ] , length : int ) -> tuple :
143148 self .offset += length
144- return struct . unpack ( format_ , self .data [self .offset - length : self .offset ])
149+ return unpacker ( self .data [self .offset - length : self .offset ])
145150
146151 def read_header (self ) -> None :
147152 """Reads header portion of packet"""
@@ -152,12 +157,12 @@ def read_header(self) -> None:
152157 self .num_answers ,
153158 self .num_authorities ,
154159 self .num_additionals ,
155- ) = self .unpack (b'!6H' , 12 )
160+ ) = self .unpack (UNPACK_6H , 12 )
156161
157162 def read_questions (self ) -> None :
158163 """Reads questions section of packet"""
159164 self .questions = [
160- DNSQuestion (self .read_name (), * self .unpack (b'!HH' , 4 )) for _ in range (self .num_questions )
165+ DNSQuestion (self .read_name (), * self .unpack (UNPACK_HH , 4 )) for _ in range (self .num_questions )
161166 ]
162167
163168 def read_character_string (self ) -> bytes :
@@ -172,18 +177,14 @@ def read_string(self, length: int) -> bytes:
172177 self .offset += length
173178 return info
174179
175- def read_unsigned_short (self ) -> int :
176- """Reads an unsigned short from the packet"""
177- return cast (int , self .unpack (b'!H' , 2 )[0 ])
178-
179180 def read_others (self ) -> None :
180181 """Reads the answers, authorities and additionals section of the
181182 packet"""
182183 self ._read_others = True
183184 n = self .num_answers + self .num_authorities + self .num_additionals
184185 for _ in range (n ):
185186 domain = self .read_name ()
186- type_ , class_ , ttl , length = self .unpack (b'!HHiH' , 10 )
187+ type_ , class_ , ttl , length = self .unpack (UNPACK_HHiH , 10 )
187188 end = self .offset + length
188189 rec = None
189190 try :
@@ -218,9 +219,7 @@ def read_record(self, domain: str, type_: int, class_: int, ttl: int, length: in
218219 type_ ,
219220 class_ ,
220221 ttl ,
221- self .read_unsigned_short (),
222- self .read_unsigned_short (),
223- self .read_unsigned_short (),
222+ * cast (Tuple [int , int , int ], self .unpack (UNPACK_3H , 6 )),
224223 self .read_name (),
225224 self .now ,
226225 )
0 commit comments