On Wed, May 15, 2019 at 09:01:19AM -0400, Christos Sfakianakis wrote:
----- Original Message -----
> From: "Jan Tluka" <jtluka(a)redhat.com>
> To: csfakian(a)redhat.com
> Cc: lnst-developers(a)lists.fedorahosted.org
> Sent: Wednesday, May 15, 2019 2:42:53 PM
> Subject: Re: [PATCH-next 03/12] lnst.Common: edit IpAddress
>
> Wed, May 15, 2019 at 01:44:00PM CEST, csfakian(a)redhat.com wrote:
> >From: Christos Sfakianakis <csfakian(a)redhat.com>
> >
> >Add multicast address verification (to be used with vxlan recipes).
> >
> >Signed-off-by: Christos Sfakianakis <csfakian(a)redhat.com>
> >---
> > lnst/Common/IpAddress.py | 13 ++++++++++++-
> > 1 file changed, 12 insertions(+), 1 deletion(-)
> >
> >diff --git a/lnst/Common/IpAddress.py b/lnst/Common/IpAddress.py
> >index 53dc047..b9fc949 100644
> >--- a/lnst/Common/IpAddress.py
> >+++ b/lnst/Common/IpAddress.py
> >@@ -13,7 +13,7 @@ olichtne(a)redhat.com (Ondrej Lichtner)
> > import re
> > from socket import inet_pton, inet_ntop, AF_INET, AF_INET6
> > from binascii import hexlify
> >-import socket
> >+import socket, struct
> > from lnst.Common.LnstError import LnstError
> >
> > #TODO create various generators for IPNetworks and IPaddresses in the same
> >@@ -74,6 +74,13 @@ class Ip4Address(BaseIpAddress):
> >
> > return addr, prefixlen
> >
> >+ def is_multicast(self):
> >+ pack = socket.inet_aton
> >+ unpack = struct.unpack
> >+ triade = ["224.0.0.0", str(self),
"239.255.255.255"]
> >+ triade = [unpack("!L", pack(val))[0] for val in triade]
> >+ return sorted(triade) == triade
> >+
>
> I'd like to get some explanation of the code above.
> Could you explain how this works?
>
Since a multicast ipv4 address needs to lie in the range from 224.0.0.0 through
239.255.255.255,
I use the imported modules to convert such dotted strings to a numeric equivalent (!L
stands for long).
Then I sort the result list (in this case numerical sort) and compare it with itsself.
Here are 2 examples:
- Example of a multicast address (224.0.1.0):
triade = ["224.0.0.0", "224.0.1.0",
"239.255.255.255"]
triade = [unpack("!L", pack(val))[0] for val in triade]
triade
[3758096384, 3758096640, 4026531839]
sorted(triade) == triade
True --> Return Value
- Example of non-multicast address (201.0.0.0):
triade = ["224.0.0.0", "201.0.0.0", "239.255.255.255"]
triade = [unpack("!L", pack(val))[0] for val in triade]
triade
[3758096384, 3372220416, 4026531839]
sorted(triade) == triade
False --> Return Value
So... why not just do this?
aton = socket.inet_aton
return aton("224.0.0.0") <= self.addr <=
aton("239.255.255.255")
-Ondrej