VirtualBox

Ignore:
Timestamp:
Feb 1, 2017 9:32:38 PM (8 years ago)
Author:
vboxsync
svn:sync-xref-src-repo-rev:
113233
Message:

IPRT: RTNetMaskToPrefixIPv4 and RTNetPrefixToMaskIPv4.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/VBox/Runtime/common/net/netaddrstr2.cpp

    r62477 r65579  
    153153
    154154
     155RTDECL(int) RTNetMaskToPrefixIPv4(PCRTNETADDRIPV4 pMask, int *piPrefix)
     156{
     157    AssertReturn(pMask != NULL, VERR_INVALID_PARAMETER);
     158
     159    if (pMask->u == 0)
     160    {
     161        if (piPrefix != NULL)
     162            *piPrefix = 0;
     163        return VINF_SUCCESS;
     164    }
     165
     166    const uint32_t uMask = RT_N2H_U32(pMask->u);
     167
     168    uint32_t uPrefixMask = UINT32_C(0xffffffff);
     169    int iPrefixLen = 32;
     170
     171    while (iPrefixLen > 0) {
     172        if (uMask == uPrefixMask)
     173        {
     174            if (piPrefix != NULL)
     175                *piPrefix = iPrefixLen;
     176            return VINF_SUCCESS;
     177        }
     178
     179        --iPrefixLen;
     180        uPrefixMask <<= 1;
     181    }
     182
     183    return VERR_INVALID_PARAMETER;
     184}
     185RT_EXPORT_SYMBOL(RTNetMaskToPrefixIPv4);
     186
     187
     188RTDECL(int) RTNetPrefixToMaskIPv4(int iPrefix, PRTNETADDRIPV4 pMask)
     189{
     190    AssertReturn(pMask != NULL, VERR_INVALID_PARAMETER);
     191
     192    if (RT_UNLIKELY(iPrefix < 0 || 32 < iPrefix))
     193        return VERR_INVALID_PARAMETER;
     194
     195    if (RT_LIKELY(iPrefix != 0))
     196        pMask->u = RT_H2N_U32(UINT32_C(0xffffffff) << (32 - iPrefix));
     197    else /* avoid UB in the shift */
     198        pMask->u = 0;
     199
     200    return VINF_SUCCESS;
     201}
     202RT_EXPORT_SYMBOL(RTNetPrefixToMaskIPv4);
     203
     204
    155205static int rtNetStrToHexGroup(const char *pcszValue, char **ppszNext,
    156206                              uint16_t *pu16)
Note: See TracChangeset for help on using the changeset viewer.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette