Skip to content

Commit b057aee

Browse files
committed
Add generic IP calculations
Add: calculateNetworkID(IPAddress ip, IPAddress subnet) => Calculate the network id using the ip and subnet (e.g. 192.168.0.0) calculateBroadcast(IPAddress ip, IPAddress subnet) => Calculate the broadcast ip using the ip and subnet (e.g. 192.168.0.255) calculateSubnetCIDR(IPAddress subnetMask) => Calculate the subnet CIDR using the subnet (e.g. 24)
1 parent 548f712 commit b057aee

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

libraries/WiFi/src/WiFiGeneric.cpp

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -656,3 +656,45 @@ int WiFiGenericClass::hostByName(const char* aHostname, IPAddress& aResult)
656656
return (uint32_t)aResult != 0;
657657
}
658658

659+
IPAddress WiFiGenericClass::calculateNetworkID(IPAddress ip, IPAddress subnet) {
660+
IPAddress networkID;
661+
662+
for (size_t i = 0; i < 4; i++)
663+
networkID[i] = subnet[i] & ip[i];
664+
665+
return networkID;
666+
}
667+
668+
IPAddress WiFiGenericClass::calculateBroadcast(IPAddress ip, IPAddress subnet) {
669+
IPAddress broadcastIp;
670+
671+
for (int i = 0; i < 4; i++)
672+
broadcastIp[i] = ~subnet[i] | ip[i];
673+
674+
return broadcastIp;
675+
}
676+
677+
uint8_t WiFiGenericClass::calculateSubnetCIDR(IPAddress subnetMask) {
678+
uint8_t CIDR = 0;
679+
680+
for (uint8_t i = 0; i < 4; i++) {
681+
if (subnetMask[i] == 0x80) // 128
682+
CIDR += 1;
683+
else if (subnetMask[i] == 0xC0) // 192
684+
CIDR += 2;
685+
else if (subnetMask[i] == 0xE0) // 224
686+
CIDR += 3;
687+
else if (subnetMask[i] == 0xF0) // 242
688+
CIDR += 4;
689+
else if (subnetMask[i] == 0xF8) // 248
690+
CIDR += 5;
691+
else if (subnetMask[i] == 0xFC) // 252
692+
CIDR += 6;
693+
else if (subnetMask[i] == 0xFE) // 254
694+
CIDR += 7;
695+
else if (subnetMask[i] == 0xFF) // 255
696+
CIDR += 8;
697+
}
698+
699+
return CIDR;
700+
}

libraries/WiFi/src/WiFiGeneric.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,10 @@ class WiFiGenericClass
108108
public:
109109
static int hostByName(const char *aHostname, IPAddress &aResult);
110110

111+
static IPAddress calculateNetworkID(IPAddress ip, IPAddress subnet);
112+
static IPAddress calculateBroadcast(IPAddress ip, IPAddress subnet);
113+
static uint8_t calculateSubnetCIDR(IPAddress subnetMask);
114+
111115
protected:
112116
friend class WiFiSTAClass;
113117
friend class WiFiScanClass;

0 commit comments

Comments
 (0)