Re: [PATCH] Correct netmask conversion in iface_netmask2prefix()

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 





David Cantrell wrote:
Found by Hans de Goede <hdegoede@xxxxxxxxxx>.  The netmask to
prefix conversion code was not correct.  Adapted this patch from
a patch Hans made to mkinitrd.
---
 isys/iface.c |   12 +++++++-----
 1 files changed, 7 insertions(+), 5 deletions(-)

diff --git a/isys/iface.c b/isys/iface.c
index eb3a20b..2a67817 100644
--- a/isys/iface.c
+++ b/isys/iface.c
@@ -300,7 +300,8 @@ struct in_addr *iface_prefix2netmask(int prefix) {
  * Convert an IPv4 netmask to an IPv4 CIDR prefix.  Return -1 on failure.
  */
 int iface_netmask2prefix(struct in_addr *netmask) {
-    int ret = -1;
+    int prefix = 32;
+    unsigned int s_addr;
     struct in_addr mask;
if (netmask == NULL) {
@@ -308,13 +309,14 @@ int iface_netmask2prefix(struct in_addr *netmask) {
     }
memcpy(&mask, netmask, sizeof(struct in_addr));
+    s_addr = ntohl(mask.s_addr);
- while (mask.s_addr != 0) {
-        mask.s_addr = mask.s_addr >> 1;
-        ret++;
+    while (!(s_addr & 1)) {
+        s_addr >>= 1;
+        prefix--;
     }
- return ret;
+    return prefix;
 }
/*

The local copy "netmask" of the passed in in_addr struct is no longer needed as we no longer make any changes to the passed in argument. Also if you want to make sure functions do not changes things they get passed by a ptr, you should make the pointer const, so make the prototype:
int iface_netmask2prefix(const struct in_addr *netmask);

This will make the compiler check you do not accidentally still write to the memory pointed to, and indicates that this function will not changes the passed in struct to other programmers looking at the code and / or using the function.

Regards,

Hans

_______________________________________________
Anaconda-devel-list mailing list
Anaconda-devel-list@xxxxxxxxxx
https://www.redhat.com/mailman/listinfo/anaconda-devel-list

[Index of Archives]     [Kickstart]     [Fedora Users]     [Fedora Legacy List]     [Fedora Maintainers]     [Fedora Desktop]     [Fedora SELinux]     [Big List of Linux Books]     [Yosemite News]     [Yosemite Photos]     [KDE Users]     [Fedora Tools]
  Powered by Linux