Skip to content

Commit

Permalink
Add getter to fetch all IP addresses of a live device as IPAddress ob…
Browse files Browse the repository at this point in the history
…jects. (#1500)
  • Loading branch information
Dimi1010 authored Jul 29, 2024
1 parent e46bf12 commit d21c05c
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
7 changes: 7 additions & 0 deletions Pcap++/header/PcapLiveDevice.h
Original file line number Diff line number Diff line change
Expand Up @@ -291,9 +291,16 @@ namespace pcpp

/**
* @return A vector containing all addresses defined for this interface, each in pcap_addr_t struct
* @deprecated This method is deprecated and will be removed in future versions. Please use getIPAddresses() instead.
*/
PCPP_DEPRECATED("This method is deprecated and will be removed in future versions. Please use getIPAddresses() instead.")
const std::vector<pcap_addr_t>& getAddresses() const { return m_Addresses; }

/**
* @return A vector containing all IP addresses defined for this interface.
*/
std::vector<IPAddress> getIPAddresses() const;

/**
* @return The MAC address for this interface
*/
Expand Down
23 changes: 23 additions & 0 deletions Pcap++/src/PcapLiveDevice.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1168,6 +1168,29 @@ void PcapLiveDevice::setDefaultGateway()
#endif
}

std::vector<IPAddress> PcapLiveDevice::getIPAddresses() const
{
std::vector<IPAddress> results;
for (const auto& address : m_Addresses)
{
in_addr* ipv4Addr = internal::try_sockaddr2in_addr(address.addr);
if (ipv4Addr != nullptr)
{
results.push_back(IPv4Address(ipv4Addr->s_addr));
continue;
}

in6_addr* ipv6Addr = internal::try_sockaddr2in6_addr(address.addr);
if (ipv6Addr != nullptr)
{
results.push_back(IPv6Address(ipv6Addr->s6_addr));
continue;
}
}

return results;
}

IPv4Address PcapLiveDevice::getIPv4Address() const
{
for(const auto& addrIter : m_Addresses)
Expand Down
9 changes: 9 additions & 0 deletions Tests/Pcap++Test/Tests/LiveDeviceTests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
#include "../Common/TestUtils.h"
#include "../Common/PcapFileNamesDef.h"
#include <array>
#include <algorithm>
#include <cstdio>
#if defined(_WIN32)
# include "PcapRemoteDevice.h"
Expand Down Expand Up @@ -296,6 +297,14 @@ PTF_TEST_CASE(TestPcapLiveDevice)
PTF_ASSERT_NOT_NULL(liveDev);
PTF_ASSERT_GREATER_THAN(liveDev->getMtu(), 0);
PTF_ASSERT_TRUE(liveDev->open());

PTF_ASSERT_EQUAL(liveDev->getIPv4Address(), ipToSearch);
{
// Should probably be refactored as PTF_ASSERT_CONTAINS or similar.
auto const ipAddresses = liveDev->getIPAddresses();
PTF_ASSERT_TRUE(std::any_of(ipAddresses.begin(), ipAddresses.end(), [ipToSearch](pcpp::IPAddress const& addr) { return addr == ipToSearch; }));
}

DeviceTeardown devTeardown(liveDev);
int packetCount = 0;
int numOfTimeStatsWereInvoked = 0;
Expand Down

0 comments on commit d21c05c

Please sign in to comment.