P4sim

ns-3 module · BMv2 inside

Run real P4 programs inside ns-3 simulations

P4sim embeds the BMv2 behavioral model in the ns-3 network simulator. The P4 programs and flow tables you run on simple_switch forward packets in repeatable, end-to-end network simulations, while ns-3 handles the topology, links, traffic and time.

How a packet crosses a P4sim switch Inside an ns-3 simulation, a packet from Host A enters port 0 of a P4SwitchNetDevice. It runs through the parser, ingress, queues, egress and deparser, then leaves port 1 to Host B. The control plane programs the tables through the BMv2 runtime API. ns-3 simulation: topology · links · traffic · time Control plane flowtable_*.txt · P4Controller runtime API P4SwitchNetDevice BMv2 Parser Ingress Queues Egress Deparser match-action pipeline + traffic manager (V1model shown; PSA and PNA too) Host A Host B
More detailAnimated walkthroughs: the switch, the pipeline, queues and scheduling, custom headers

Features

Programmable data planes, simulated end to end

P4sim couples a P4 packet processing engine with ns-3's network models, so you can study P4 programs in realistic topologies and traffic, at a scale a testbed rarely allows.

BMv2 runs every packet

Packets pass through the BMv2 pipeline, the reference behavioral model used across the P4 community, so forwarding follows the same semantics as simple_switch.

Bring your BMv2 programs

Compiled P4 JSON from p4c and runtime CLI flow tables (table_add …) load without changes. Several examples are adapted from the p4lang tutorials.

Three P4 architectures

Select V1model, PSA or PNA per switch with one attribute. Each maps to its BMv2 target: simple_switch, psa_switch or pna_nic.

ns-3 does the rest

Topology, CSMA or point-to-point links, applications, timing, pcap traces and logging all come from ns-3. Combine P4 switches with any other ns-3 module.

Runtime control

P4Controller adds, modifies and deletes table entries, default actions and action profiles while the simulation runs, through the BMv2 runtime API.

Switch-level knobs

Set the processing rate, queue buffers and BMv2 log level per switch. Thrift ports are picked automatically, so several simulations can run in parallel.

How it works

A P4 switch as an ns-3 NetDevice

P4sim adds P4SwitchNetDevice, which takes the place of the standard ns-3 bridge. At start-up each switch loads a compiled P4 JSON program and a flow-table file.

A packet that arrives on a switch port is handed to the BMv2 core, linked in as a shared library. BMv2 parses it and runs the ingress match-action tables. The packet then waits in the switch's egress queues, which ns-3 events serve at the configured processing rate. BMv2 runs the egress pipeline and the deparser, and ns-3 sends the packet out of the chosen port.

The control plane uses BMv2's own interfaces. Flow-table files in runtime CLI syntax are applied at start-up, and P4Controller calls the BMv2 runtime API while the simulation runs.

Watch it step by step: inside the switch →

main · stable

Arch 1: bridge-based

Each switch port is an ordinary ns-3 NetDevice (CSMA or point-to-point). Flexible: the switch can connect to any device.

switch_channel · in development

Arch 2: switch-centric

Ports are internal parts of P4SwitchNetDevice, joined by a switched Ethernet channel. Finer control over port behaviour, closer to real programmable switches. May contain breaking changes.

Two P4sim architectures. Left, Arch 1 on the main branch: a P4SwitchNetDevice with control plane interface and P4SwitchCore, whose four ports are separate CSMA or P2P NetDevices attached through a bridge channel. Right, Arch 2 on the switch_channel branch: the four ports are part of the P4SwitchNetDevice and hosts attach through a switch Ethernet channel.
Arch 1 (main) and Arch 2 (switch_channel). Click to enlarge.

Supported P4 architectures

P4SwitchArchArchitectureBMv2 targetExample
0V1modelsimple_switchp4-v1model-ipv4-forwarding
1PSApsa_switchp4-psa-ipv4-forwarding
2PNApna_nicp4-pna-ipv4-forwarding

Get started

Install and run your first example

Tested on Ubuntu 24.04 LTS with ns-3.39. Installing BMv2 and the P4 tools takes 1–2 hours and up to 15 GB of disk space. The full guide also covers virtual machines and older ns-3 versions.

  1. 1

    Install BMv2 and the P4 tools

    Use the install script of the official p4lang/tutorials repository.

    sudo apt update && sudo apt install git vim cmake
    cd ~ && git clone https://github.com/p4lang/tutorials
    mkdir ~/src && cd ~/src
    ../tutorials/vm-ubuntu-24.04/install.sh |& tee log.txt
    simple_switch --version   # check the installation
  2. 2

    Get ns-3.39 and add P4sim

    P4sim is an ns-3 contrib module. The script registers BMv2 with pkg-config.

    mkdir -p ~/workdir && cd ~/workdir
    git clone https://github.com/nsnam/ns-3-dev-git.git ns3.39
    cd ns3.39 && git checkout ns-3.39
    cd contrib && git clone https://github.com/HapCommSys/p4sim.git
    cd p4sim && sudo ./set_pkg_config_env.sh
  3. 3

    Build and set P4SIM_DIR

    Examples find their P4 programs, flow tables and topologies through P4SIM_DIR.

    cd ~/workdir/ns3.39
    ./ns3 configure --enable-tests --enable-examples
    ./ns3 build
    echo 'export P4SIM_DIR="$HOME/workdir/ns3.39/contrib/p4sim"' >> ~/.bashrc
    source ~/.bashrc
  4. 4

    Run an example

    Two hosts, one V1model switch. Turning the BMv2 log off makes larger runs much faster.

    ./ns3 run p4-v1model-ipv4-forwarding
    ./ns3 run "p4-basic-example --ns3::P4SwitchNetDevice::BmLogLevel=off"
    ./test.py -s p4sim   # run a test suite

Workflow

From a P4 program to a simulation

  1. Write the P4 program. Headers, parser, match-action tables and control flow.
  2. Compile it with p4c. p4c-bm2-ss, p4c-bm2-psa or p4c-bm2-pna produce the JSON pipeline.
  3. Write the ns-3 script. Build the topology and install P4 switches on the switch nodes.
  4. Configure the control plane. Flow-table files at start-up, P4Controller during the run.
  5. Run and observe. Throughput, latency, pcap traces and logs from ns-3.
#include "ns3/p4-helper.h"
#include "ns3/format-utils.h"  // GetP4ExamplePath()

std::string dir = GetP4ExamplePath() + "/simple_v1model";

P4Helper p4;
p4.SetDeviceAttribute("JsonPath",
    StringValue(dir + "/simple_v1model.json"));
p4.SetDeviceAttribute("FlowTablePath",
    StringValue(dir + "/flowtable_0.txt"));
// 0 = V1model, 1 = PSA, 2 = PNA
p4.SetDeviceAttribute("P4SwitchArch", UintegerValue(0));
// processing rate in packets per second
p4.SetDeviceAttribute("SwitchRate", UintegerValue(10000));

// ports: the switch node's CSMA or P2P NetDevices
p4.Install(switchNode, ports);

From p4-v1model-ipv4-forwarding, shortened.

Switch attributes

Forwarding is defined by the P4 program and its flow tables. These attributes of ns3::P4SwitchNetDevice control the simulation side.

AttributeDescription
JsonPathPath to the compiled P4 JSON file
FlowTablePathPath to the flow-table file
P4SwitchArchArchitecture: 0 = V1model, 1 = PSA, 2 = PNA
ChannelTypeChannel type: 0 = CSMA, 1 = point-to-point
SwitchRateProcessing rate in packets per second
QueueBufferSizeTotal queue buffer size, in packets
InputBufferSizeLowInput buffer for low-priority (external) packets
InputBufferSizeHighInput buffer for high-priority (internal) packets
EnableTracingBasic throughput tracing
EnableSwapSwap the P4 configuration at run time
BmLogLevelBMv2 pipeline log level, from trace (default) to off; off speeds up the simulation
ThriftPortThrift port for the runtime CLI; 0 (default) picks a free port from 9090 up

Examples

Sixteen ready-to-run scenarios

Each example is an ns-3 script plus a p4src/ folder with the P4 source, compiled JSON, flow tables and topology. Run any of them with ./ns3 run <name>.

Results of the paper's experiments: p4sim-artifact-icns3. New examples are welcome as pull requests.

Testing

Seven test suites

Run them with ./test.py -s <suite>. The example smoke tests in examples-to-run.py keep the examples from breaking unnoticed.

SuiteChecks
p4-packetFrames in and out of a switch on V1model, PSA and PNA
p4simProgram loading, Thrift ports, BmLogLevel
p4-controllerFlow entries and action profiles, read back
p4-queueCapacity, rate, FIFO order, priorities
p4-p2p-channelThe P4 point-to-point channel
p4-topology-readerReading topology files
format-utilsConversion and path helpers

Packet tests

Write a test as frames in, frames out

p4-packet reads a subset of p4c's STF format: send a frame into a port, expect frames on the others. * matches any nibble.

# send this frame into port 0
packet 0 0000000000fe 000000000010 0800 ...
# expect this frame to leave port 1
expect 1 000000000011 0000000000fe 0800 ...

Scope

  • P4sim simulates functional behaviour: it reproduces P4 forwarding logic, not ASIC-level timing.
  • SwitchRate is set by hand per switch; an unsuitable value wastes CPU time on idle polling.
  • With a CSMA channel, the P4 program has to handle ARP itself.
  • Tracing is basic (throughput); per-table counters are not exported yet.

Publications

Cite P4sim

ICNS3 2025 · Proceedings of the 2025 International Conference on ns-3 · ACM

P4sim: Simulating Programmable Switches in ns-3

Mingyu Ma, Giang T. Nguyen

The arXiv preprint appeared as “P4sim: Programming Protocol-independent Packet Processors in ns-3”.

BibTeX
@inproceedings{ma2025p4sim,
  title     = {P4sim: Simulating Programmable Switches in ns-3},
  author    = {Ma, Mingyu and Nguyen, Giang T.},
  booktitle = {Proceedings of the 2025 International Conference on ns-3},
  series    = {ICNS3 2025},
  pages     = {107--115},
  year      = {2025},
  publisher = {ACM},
  doi       = {10.1145/3747204.3747210}
}

Builds on

  • Jiasong Bai, Jun Bi, Peng Kuang, Chengze Fan, Yu Zhou, Cheng Zhang. NS4: Enabling programmable data plane simulation. ACM SOSR 2018. ACM DL
  • Chengze Fan, Jun Bi, Yu Zhou, Cheng Zhang, Haisu Yu. NS4: A P4-driven network simulator. SIGCOMM Posters and Demos 2017. ACM DL

People

Maintainers and contributors

Maintainer: Mingyu Ma, TU Dresden.

Contributors: developed further in Google Summer of Code 2025 with P4.org, with support from Davide and contributions from Vineet, and from everyone on GitHub.

Contribute

Bug reports, new examples and pull requests are welcome.