Skip to content

Instantly share code, notes, and snippets.

@devyte
Created November 27, 2018 03:08
Show Gist options
  • Save devyte/e6bf1b48a2dc0b753e6e05d5ddcbae45 to your computer and use it in GitHub Desktop.
Save devyte/e6bf1b48a2dc0b753e6e05d5ddcbae45 to your computer and use it in GitHub Desktop.
IfList implementation with separate objects
#ifndef __IFLIST_H__
#define __IFLIST_H__
struct NetInterface
{
NetInterface(_netif *netif) : _netif(netif), _num(-1) {}
NetInterface(const NetInterface & o) : _netif(o.netif), _num(o._num) {}
bool isLegacy() const { return _num == 0; }
IPAddress addr () const { return _ip_from_netif_num(); }
IPAddress netmask () const { return _netif->netmask; }
IPAddress gw () const { return _netif->gw; }
String iface () const { return String(_netif->name[0]) + _netif->name[1]; }
const char* hostname () const { return _netif->hostname ? : ""; }
const char* mac () const { return (const char*)_netif->hwaddr; }
int number () const { return _netif->num; }
bool operator==(const NetInterface & o) {return equal(o);}
bool operator!=(const NetInterface & o) {return !equal(o);}
bool equal (const NetInterface& o)
{
return _netif == o._netif && (!_netif || _num == o._num);
}
const ip_addr_t* ip_from_netif_num () const
{
#if LWIP_IPV6
return _num ? &_netif->ip6_addr[_num - 1] : &_netif->ip_addr;
#else
return &_netif->ip_addr;
#endif
}
netif* _netif;
int _num;
};
class NetInterfaceIterator
{
public:
const NetInterfaceIterator& operator* () const { return netIface; }
const NetInterfaceIterator* operator-> () const { return &netIface; }
bool operator==(const NetInterfaceIterator & o) {return netIface.equal(o.netIface);}
bool operator!=(const NetInterfaceIterator & o) {return !netIface.equal(o.netIface);}
NetInterfaceIterator & operator= (const NetInterfaceIterator& o) { _netif = o._netif; _num = o._num; return *this; }
NetInterfaceIterator operator++(int)
{
NetInterfaceIterator ret = *this;
++(*this);
return ret;
}
NetInterfaceIterator & operator++()
{
while (netIface._netif)
{
if (++netIface._num == IF_NUM_ADDRESSES)
{
netIface = NetInterface(netIface._netif->next);
continue;
}
if (!ip_addr_isany(netIface.ip_from_netif_num()))
break;
}
return *this;
}
private:
NetInterface netIface;
};
class IfList
{
using const_iterator = const NetInterfaceIterator;
const_iterator begin() {return const_iterator(netif_list);}
const_iterator end() {return const_iterator(nullptr);}
};
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment