Skip to content

Commit 12b91a9

Browse files
author
ldx
committed
Refactor Rule6.set_{src,dst}().
1 parent 0ba6bfc commit 12b91a9

File tree

1 file changed

+22
-28
lines changed

1 file changed

+22
-28
lines changed

iptc/ip6tc.py

Lines changed: 22 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -299,30 +299,37 @@ def get_src(self):
299299
src = "".join([src, str(plen)])
300300
return src
301301

302-
def set_src(self, src):
303-
if src[0] == "!":
304-
self.entry.ipv6.invflags |= ip6t_ip6.IP6T_INV_SRCIP
305-
src = src[1:]
306-
else:
307-
self.entry.ipv6.invflags &= (~ip6t_ip6.IP6T_INV_SRCIP &
308-
ip6t_ip6.IP6T_INV_MASK)
309-
310-
slash = src.find("/")
302+
def _get_address_netmask(self, a):
303+
slash = a.find("/")
311304
if slash == -1:
312-
addr = src
305+
addr = a
313306
netm = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"
314307
else:
315-
addr = src[:slash]
316-
netm = src[slash + 1:]
308+
addr = a[:slash]
309+
netm = a[slash + 1:]
310+
return addr, netm
317311

312+
def _addr2in6addr(self, addr):
318313
arr = ct.c_uint8 * 16
319314
ina = in6_addr()
320315
try:
321316
ina.s6_addr = arr.from_buffer_copy(
322317
socket.inet_pton(socket.AF_INET6, addr))
323318
except socket.error:
324319
raise ValueError("invalid address %s" % (addr))
325-
self.entry.ipv6.src = ina
320+
return arr, ina
321+
322+
def set_src(self, src):
323+
if src[0] == "!":
324+
self.entry.ipv6.invflags |= ip6t_ip6.IP6T_INV_SRCIP
325+
src = src[1:]
326+
else:
327+
self.entry.ipv6.invflags &= (~ip6t_ip6.IP6T_INV_SRCIP &
328+
ip6t_ip6.IP6T_INV_MASK)
329+
330+
addr, netm = self._get_address_netmask(src)
331+
332+
arr, self.entry.ipv6.src = self._addr2in6addr(addr)
326333

327334
# if we got a numeric prefix length
328335
if netm.isdigit():
@@ -376,22 +383,9 @@ def set_dst(self, dst):
376383
self.entry.ipv6.invflags &= (~ip6t_ip6.IP6T_INV_DSTIP &
377384
ip6t_ip6.IP6T_INV_MASK)
378385

379-
slash = dst.find("/")
380-
if slash == -1:
381-
addr = dst
382-
netm = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"
383-
else:
384-
addr = dst[:slash]
385-
netm = dst[slash + 1:]
386+
addr, netm = self._get_address_netmask(dst)
386387

387-
arr = ct.c_uint8 * 16
388-
ina = in6_addr()
389-
try:
390-
ina.s6_addr = arr.from_buffer_copy(
391-
socket.inet_pton(socket.AF_INET6, addr))
392-
except socket.error:
393-
raise ValueError("invalid address %s" % (addr))
394-
self.entry.ipv6.dst = ina
388+
arr, self.entry.ipv6.dst = self._addr2in6addr(addr)
395389

396390
# if we got a numeric prefix length
397391
if netm.isdigit():

0 commit comments

Comments
 (0)