Jaroslav Ištvan
ČeštinaEnglish
← Back to projects

IPK — L2/L3 Network Scanner

C++20Raw socketsARP / NDP / ICMP

What it does

A network scanner working on layers L2 and L3 - it finds active devices in a given subnet and returns their MAC and IP addresses, whether IPv4 or IPv6. It is a pure CLI tool and the results are printed straight to the terminal. Because it works with raw sockets, it has to run with sudo.

Networks and subnets

Every device connected to a network has an IP address, but addresses are not handed out at random - the address space is cut into subnets. The notation 192.168.1.0/24 says that the first 24 bits of the address identify the network and the remaining 8 a particular device in it. That gives 256 addresses, of which the first belongs to the network and the last to broadcast, leaving 254 for devices.

There is nothing exotic about it: everyone has their own subnet at home. The laptop, the phone and the TV all got an address from the router with the same first 24 bits and differ only in the last number - which is why they can talk to each other directly.

This division is exactly why the scanner combines two kinds of protocols. Devices within the same subnet talk to each other directly via MAC addresses on the link layer (L2). Anything outside it has to go through a router and is handled on the network layer (L3).

For the scanner, a subnet defines the work to be done: “go through 10.0.1.0/24” means trying 254 addresses. The same holds for IPv6, only on a different scale - an ordinary home /64 subnet contains over 18 quintillion addresses. Going through them is impossible even in theory, so with IPv6 only small ranges or specific addresses are scanned.

Protocols used and why these

  • ARP (IPv4, L2) — the question “who has this IP address?” sent to everyone in the segment. Whoever has it answers with its MAC address. It only works in the local subnet, but it almost always gets an answer: devices need ARP for normal operation, so they cannot ignore it.
  • ICMP Echo (IPv4, L3) — a plain ping. It reaches beyond a router, but firewalls commonly drop it, so silence does not mean there is no device.
  • NDP (IPv6) — IPv6 has no ARP; its role is taken over by Neighbor Discovery on top of ICMPv6. Instead of a broadcast, it asks a multicast group derived from the address being looked up.
  • ICMPv6 Echo (IPv6) — the IPv6 counterpart of ping.

The point of the combination: each protocol sees something different. ARP and NDP give the MAC address and are reliable, but cannot reach beyond the segment. ICMP reaches further, but is easily filtered out. Trying both at once gives a more complete picture - and the output then shows which of them succeeded. That is also why ScanResult holds four independent flags instead of a single “found / not found”.

Input and output

One command, one subnet, a list of hosts found. This output is a real record from testing on a home network:

Input
sudo ./ipk-L2L3-scan -i enp0s3 -s 10.0.1.48/24
Output
Scanning ranges:
10.0.1.0/24 254

10.0.1.1 arp FAIL, icmpv4 FAIL
10.0.1.11 arp OK (be-87-5a-ad-ea-55), icmpv4 OK
10.0.1.18 arp OK (60-cf-84-62-68-59), icmpv4 FAIL
10.0.1.19 arp OK (c8-8a-d8-0a-cb-2c), icmpv4 OK
10.0.1.39 arp OK (70-54-b4-8d-73-7b), icmpv4 OK
10.0.1.48 arp FAIL, icmpv4 OK
10.0.1.138 arp OK (24-e4-ce-60-de-d1), icmpv4 OK

10.0.1.18 is the physical machine that ran the test VM (hence ICMP fails), 10.0.1.48 is the VM itself (hence ARP fails) - both are expected, not errors.

Architecture

Two abstractions make the main logic practically protocol-independent - and the readability of the whole project rests on them.

Factory Method — Subnet::parse()

Parsing a subnet returns either IPv4Subnet or IPv6Subnet, but the calling code works only with the abstract Subnet - it never has to branch on the IP version.

utils/subnet.hpp
class Subnet {
public:
    virtual ~Subnet() = default;
    virtual std::string toString() const = 0;
    virtual uint64_t hostCount() const = 0;
    virtual std::unique_ptr<IPGenerator> getGenerator() const = 0;
    static std::unique_ptr<Subnet> parse(const std::string& input);
    // ...returns IPv4Subnet or IPv6Subnet, the caller does not need to care
};

Polymorphism — NetworkScanner

ARP, ICMPv4, NDP and ICMPv6 have completely different packets, but they all sit behind the same interface: send a request, receive a response, say whether you support the given IP version.

scanner/network_scanner.hpp
class NetworkScanner {
public:
    virtual ~NetworkScanner() = default;
    virtual void sendRequest(const std::string& ip) = 0;
    virtual void receiveResponse(std::unordered_map<std::string, ScanResult>& results) = 0;
    virtual int getSocket() const = 0;
    virtual bool supports(const std::string& ip) const = 0;
};
// implemented by: ARPScanner, ICMPv4Scanner, NDPScanner, ICMPv6Scanner

The result: main() knows nothing about ARP/ICMP/NDP packets, it just puts subnets, scanners and results together.

main.cpp
int main(int argc, char** argv) {
    std::signal(SIGINT, handle_signal);
    std::signal(SIGTERM, handle_signal);

    Arguments args = processArguments(argc, argv);
    optionalDisplayHelp(args);
    optionalDisplayInterfaces(args);

    std::vector<std::unique_ptr<Subnet>> subnets = getSubnets(args);
    displayScanningRanges(subnets);

    std::unordered_map<std::string, ScanResult> results;
    std::vector<std::unique_ptr<NetworkScanner>> scanners = initializeScanners(args);

    sendAllRequestsLazy(subnets, scanners, results);
    collectResponses(scanners, results, args.timeout);

    displayResultsLazy(subnets, results);

    return static_cast<int>(ExitCode::SUCCESS);
}

Lazy address generation

A /16 subnet has 65,534 addresses, a /8 over sixteen million. If the program first built a list of all of them, it would pay for it in memory and in waiting before it sent the first packet.

utils/ip_generator.hpp
class IPGenerator {
public:
    virtual ~IPGenerator() = default;
    virtual bool hasNext() const = 0;
    virtual std::string next() = 0;
};

The interface has just two methods and hands out addresses one at a time, so the program never holds more than one. There are two implementations: IPv4Generator increments a 32-bit number, IPv6Generator has to carry over across a whole 16-byte array.

It is used twice - when sending the requests and when printing the results. Hence the names sendAllRequestsLazy() and displayResultsLazy().

Asynchronous scanning

The naive approach - send a query, wait for the answer, move on to the next address - is useless for scanning. With a 500 ms timeout for each of 254 addresses, going through a single /24 would take over two minutes, even if most devices answered immediately.

The program turns it around: it first sends requests to all addresses and only then collects the responses. The sockets are non-blocking and waited on with select(), so a single thread handles all protocols at once. Each protocol has its own socket - which is why the NetworkScanner interface has a getSocket() method.

Responses therefore arrive in any order and are written into a map of results keyed by IP address. For ICMP this is done with the request sequence number, which is paired back to the address through the seq_to_ip_ map.

Rate limiting

Sending tens of thousands of packets as fast as possible is not a good idea. The send buffer overflows, network devices may treat the traffic as an attack, and some packets get lost on the way. The result is false negatives - the device is there, but the scan does not find it.

The program therefore throttles sending with a simple limiter. It is a deliberate trade-off: a slightly slower scan in exchange for a result you can trust.

Exit codes

For a command-line tool, the exit code is often the only thing the calling script learns about how it went. Instead of magic numbers, the project therefore uses an enumeration:

utils/exit_code.hpp
enum class ExitCode {
    SUCCESS                = 0,
    ARGUMENT_PARSING_ERROR = 3,
    INTERFACE_LISTING_ERROR = 4,
    SUBNET_PARSING_ERROR   = 5,
    SOCKET_ERROR           = 6,
    INTERFACE_ERROR        = 7,
};

Fatal errors are reported via std::exit(static_cast<int>(code)), so even in the code it is obvious at first glance what exactly failed.

Modules

FolderResponsibility
/argsParsing and validating command-line options
/coreOrchestration — initialising scanners and subnets, sending requests, collecting responses, printing results
/scannerImplementations of the individual protocols: building a packet, sending it, recognising a valid response
/utilsSubnets, address generators, the result structure, exit codes, signal handling and system call checks
/testsUnit tests (doctest)
/externdoctest as the only external dependency

The split follows the flow of the program: /args finds out what, /utils turns it into concrete addresses, /scanner asks the network and /core runs the whole thing. The only folder that knows about raw sockets and packet headers is /scanner.

Classes

ClassResponsibility
ArgumentParserGoes through argv, fills the Arguments structure and checks that it makes sense
SubnetAbstract subnet — the common interface and the parse() factory method
IPv4Subnet / IPv6SubnetPrefix validation, normalising the notation, computing the range and the host count
IPGeneratorAbstract source of addresses handed out one at a time
IPv4Generator / IPv6GeneratorIncrementing a 32-bit number, or a 16-byte array with carry
NetworkScannerThe scanner contract: supports, sendRequest, receiveResponse, getSocket
ARPScanner / NDPScannerFinding the MAC address on layer two (IPv4 / IPv6)
ICMPv4Scanner / ICMPv6ScannerChecking reachability on layer three, pairing responses by sequence number
ScanResultThe result for one IP: four independent flags and a MAC address

Three abstract interfaces and nine concrete classes - that is the whole object design. Adding a fifth protocol means writing one class derived from NetworkScanner and registering it in initializeScanners(); nothing else is touched.

Class diagram

Class diagram of the IPK project with attributes and methods: three abstract interfaces Subnet, IPGenerator and NetworkScanner with their concrete implementations and the ScanResult data classClass diagram of the IPK project with attributes and methods: three abstract interfaces Subnet, IPGenerator and NetworkScanner with their concrete implementations and the ScanResult data class
Subnet creates its own IPGenerator through getGenerator(), NetworkScanner fills ScanResult. Attributes and methods follow the headers in cpp-projects/ipk.

Testing

Automated tests (doctest, run with make test) cover parsing of arguments and subnets, the IP address generators, the factory method and the scanner orchestration using mock objects.

Manual testing took place on a real home network - the scanner’s results were compared with nmap, ping6 and the system ip neigh table and they matched, including edge cases such as a local VM or the host machine.

GitHub