Utility functions to produce an IPv4 broadcast address

These functions work only for IPv4, becasue IPv6 doesn't have the same
concept of "broadcast address" as IPv4. They merely OR the inverse of
the netmask with the given host address, thus turning on all the host
bits.
This commit is contained in:
Laine Stump 2010-12-30 21:33:24 -05:00
parent 6b6cb7ea15
commit 86387878b0
3 changed files with 63 additions and 0 deletions

View File

@ -558,6 +558,8 @@ virShrinkN;
# network.h
virSocketAddrBroadcast;
virSocketAddrBroadcastByPrefix;
virSocketAddrIsNetmask;
virSocketAddrMask;
virSocketAddrMaskByPrefix;

View File

@ -340,6 +340,61 @@ virSocketAddrMaskByPrefix(virSocketAddrPtr addr, unsigned int prefix)
return virSocketAddrMask(addr, &netmask);
}
/**
* virSocketAddrBroadcast:
* @addr: address that needs to be turned into broadcast address (IPv4 only)
* @netmask: the netmask address
* @broadcast: virSocketAddr to recieve the broadcast address
*
* Mask ON the host bits of @addr according to @netmask, turning it
* into a broadcast address.
*
* Returns 0 in case of success, or -1 on error.
*/
int
virSocketAddrBroadcast(const virSocketAddrPtr addr,
const virSocketAddrPtr netmask,
virSocketAddrPtr broadcast)
{
if ((addr->data.stor.ss_family != AF_INET) ||
(netmask->data.stor.ss_family != AF_INET)) {
broadcast->data.stor.ss_family = AF_UNSPEC;
return -1;
}
broadcast->data.stor.ss_family = AF_INET;
broadcast->len = addr->len;
broadcast->data.inet4.sin_addr.s_addr
= (addr->data.inet4.sin_addr.s_addr
| ~netmask->data.inet4.sin_addr.s_addr);
return 0;
}
/**
* virSocketAddrBroadcastByPrefix:
* @addr: address that needs to be turned into broadcast address (IPv4 only)
* @prefix: prefix (# of 1 bits) of netmask to apply
* @broadcast: virSocketAddr to recieve the broadcast address
*
* Mask off the host bits of @addr according to @prefix, turning it
* into a network address.
*
* Returns 0 in case of success, or -1 on error.
*/
int
virSocketAddrBroadcastByPrefix(const virSocketAddrPtr addr,
unsigned int prefix,
virSocketAddrPtr broadcast)
{
virSocketAddr netmask;
if (virSocketAddrPrefixToNetmask(prefix, &netmask,
addr->data.stor.ss_family) < 0)
return -1;
return virSocketAddrBroadcast(addr, &netmask, broadcast);
}
/**
* virSocketCheckNetmask:
* @addr1: a first network address

View File

@ -77,6 +77,12 @@ int virSocketAddrMask (virSocketAddrPtr addr,
const virSocketAddrPtr netmask);
int virSocketAddrMaskByPrefix(virSocketAddrPtr addr,
unsigned int prefix);
int virSocketAddrBroadcast(const virSocketAddrPtr addr,
const virSocketAddrPtr netmask,
virSocketAddrPtr broadcast);
int virSocketAddrBroadcastByPrefix(const virSocketAddrPtr addr,
unsigned int prefix,
virSocketAddrPtr broadcast);
int virSocketGetNumNetmaskBits(const virSocketAddrPtr netmask);
int virSocketAddrPrefixToNetmask(unsigned int prefix,