Skip to content

IPv4 Protocol

opencode-agent[bot] edited this page Nov 1, 2026 · 2 revisions

IPv4 Protocol

IPv4 packet processing with fragment reassembly, forming the foundation of JNode's network stack.

Overview

JNode's IPv4 implementation is the network layer at the heart of the custom network stack. The IPv4NetworkLayer class acts as the NetworkLayer interface implementation, receiving packets from the link layer via NetworkLayerManager, routing them to the appropriate transport layer (TCP, UDP, ICMP, RAW), and handling outbound packet transmission with routing decisions. The layer maintains a HashMap<Integer, IPv4Protocol> mapping IP protocol numbers to handler instances, and a separate fragment table for reassembly.

IPv4Constants defines all standard IP protocol numbers (TCP=6, UDP=17, ICMP=1, etc.), fragmentation flags (IP_MF, IP_DF, IP_FRAGOFS_MASK), route flags (RTF_UP, RTF_GATEWAY, etc.), and network class limits.

Key Components

Class / File Role
net/src/net/org/jnode/net/ipv4/layer/IPv4NetworkLayer.java Central IPv4 network layer: packet receive, checksum validation, fragment reassembly, protocol routing, ARP cache update, statistics
net/src/net/org/jnode/net/ipv4/IPv4Header.java IPv4 header: 20-byte header parsing/construction, fragment flags, checksum validation, address swapping
net/src/net/org/jnode/net/ipv4/IPv4Constants.java Protocol numbers (TCP=6, UDP=17, ICMP=1, etc.), fragmentation bits, route flags, network class limits
net/src/net/org/jnode/net/ipv4/IPv4FragmentList.java Fragment reassembly tracker: ordered fragment assembly, timeout-based lifecycle, completeness check
net/src/net/org/jnode/net/ipv4/IPv4RoutingTable.java Route table: host-route lookup, longest-prefix network match, default gateway fallback. See IPv4-Routing
net/src/net/org/jnode/net/ipv4/IPv4Route.java Route identity, host/network classification, gateway flag, use count. See IPv4-Routing
net/src/net/org/jnode/net/ipv4/IPv4Address.java 32-bit IPv4 address representation and manipulation
net/src/net/org/jnode/net/ipv4/IPv4Service.java Interface for transmit(), getRoutingTable(), and protocol lookup
net/src/net/org/jnode/net/ipv4/IPv4Utils.java Internet checksum calculation (ones-complement, header validation)
net/src/net/org/jnode/net/ipv4/IPv4Protocol.java Interface for transport protocols that can receive ICMP error notifications

How It Works

Inbound Packet Processing

Network Device
  → NetDeviceAPI.receive(SocketBuffer)
    → NetworkLayerManager.receive(skbuf)
      → IPv4NetworkLayer.receive(skbuf, deviceAPI)
        1. Create IPv4Header from skbuf
        2. Validate checksum (drop if bad)
        3. Pull header bytes, trim to dataLength
        4. Update ARP cache (src MAC + src IP)
        5. Check destination address (process if for me)
        6. If fragment → deliverFragment() → IPv4FragmentList
           Else → deliver() → IPv4Protocol.receive(hdr, skbuf)
        7. Periodic cleanup of dead fragments (every 2 * IP_FRAGTIMEOUT)

IPv4Header Structure

The header is 20 bytes minimum (IHL * 4). Fields parsed on receive:

  • Version (4 bits): extracted from upper nibble of byte 0
  • IHL (4 bits): header length multiplier
  • TOS (1 byte): type of service
  • Total Length (2 bytes): full packet length minus any link layer headers
  • Identification (2 bytes): fragmentation reassembly key component
  • Flags + Fragment Offset (2 bytes): IP_DF (0x4000), IP_MF (0x2000), offset masked with IP_FRAGOFS_MASK (0x1FFF), shifted left by 3
  • TTL (1 byte): time-to-live, decremented per hop
  • Protocol (1 byte): next-layer protocol ID (1=ICMP, 6=TCP, 17=UDP)
  • Source Address (4 bytes): parsed into IPv4Address
  • Destination Address (4 bytes): parsed into IPv4Address
  • Checksum (2 bytes): validated via IPv4Utils.calcChecksum

Checksum is set to 0xFFFF if the computed value is zero (RFC 1122 compliance). Source address is inserted by the sender.

Fragment Reassembly

Fragments are tracked via IPv4FragmentList, keyed by identification-protocol-srcIP-dstIP. When a fragment arrives:

  1. Look up fragment list by key
  2. If not found, create a new IPv4FragmentList
  3. Insert at correct offset position (checking for overlaps)
  4. Track haveFirstFragment and haveLastFragment flags
  5. If isComplete() (first+last fragment, single list entry), deliver to protocol
  6. Periodically remove lists where isAlive() returns false (timeout: IP_FRAGTIMEOUT = 120000ms)

Outbound Packet Transmission

IPv4NetworkLayer delegates to IPv4Sender. The sender:

  1. Looks up route via IPv4RoutingTable.search(dst)
  2. Gets destination MAC via ARP resolution
  3. Sets source/destination IP in header
  4. Increments TTL, sets identification
  5. Computes and writes checksum
  6. Sends via the route's device

Routing Table

Three-tier lookup in IPv4RoutingTable.search():

  1. Host routes — exact destination match (r.isHost() && r.isUp()).
  2. Network routes — every matching r.isNetwork() && r.isUp() route is considered and the highest subnetmask.prefixLength() wins. Equal prefix lengths prefer a gateway route over a direct route.
  3. Default gateway — the first gateway route (r.isGateway() && r.isUp()).

ConcurrentModificationException is caught and the whole scan is retried, because the table can be modified by another thread during traversal.

Route insertion and removal are identity-based. IPv4Route.equals() compares destination, subnet mask, gateway (null-safe) and device identity; flags and use count are excluded. IPv4RoutingTable.add() replaces an entry only when all four identity fields match, so 10.0.0.0/8 and 10.0.0.0/16 can coexist for longest-prefix matching. remove() matches by value.

Ifconfig.setDefault() maintains the on-link route for a configured address: it removes the connected route of the previous address, then adds one for the new address & netmask (skipping the any-address). Re-addressing therefore no longer leaves the old subnet reachable.

IPv4NetworkArgument accepts a.b.c.d, a.b.c.d/N, a.b.c.d/dotted.mask and default. It validates octets locally (0 <= v < 256) instead of relying on IPv4Address(String)'s unchecked byte cast, and rejects a non-contiguous dotted mask before it can report a misleading prefix length. See IPv4-Routing for the full lookup algorithm, host/network classification rules and route grammar.

Gotchas

  • Checksum corner case: IPv4Utils.calcChecksum returns ~chsum. For a zero-checksum (all zeros), this produces 0xFFFF. On write, prefixTo() converts 0 to 0xFFFF to represent zero (RFC 1122). A true zero checksum is computed as 0x0000 only when the checksum field itself is zeroed and the computed value is 0, which should not happen in normal packets.
  • Fragment reassembly buffering: Fragments are held in IPv4FragmentList until complete or timed out. There is no limit on the number of concurrent fragment lists — a DoS attack could exhaust memory.
  • TTL decrement is not performed: The stack reads TTL but does not decrement it during forwarding. This means packets never expire in the stack; TTL is purely informational unless the stack implements forwarding.
  • No fragmentation on send: The outbound path does not check MTU before sending. If the packet exceeds the device MTU, it may be silently dropped or cause hardware issues.
  • Routing must be longest-prefix, not first-match. A route is identified by destination, mask, gateway and device. Replacing by destination alone drops the more-specific route and breaks LPM; see IPv4-Routing.
  • A non-contiguous dotted mask is invalid. prefixLength() only popcounts bits, so 255.255.0.255 would compete at /24 specificity. IPv4NetworkArgument round-trips the mask through fromPrefixLength() and rejects it.
  • Re-addressing an interface has two sides. Removing the old connected route is as important as adding the new one; otherwise the retired subnet stays on-link.
  • ARP cache update on every packet: Every inbound IPv4 packet updates the ARP cache with the source IP-to-MAC mapping. This is a passive ARP table update mechanism.
  • Fragment key includes source address: This prevents fragments from different sources being mixed (which is correct per RFC 791).
  • Minimum fragment size: IP_MIN_FRAG_SIZE = 8 bytes. Fragments smaller than this are still tracked — the check is informational.
  • ChecksumOk flag: When constructing a header from a buffer, the checksum is validated and stored. When creating a header programmatically, checksumOk = true unconditionally — the caller is responsible for ensuring correctness.

Related Pages

Clone this wiki locally