VoIP and SIP Call Flow Testing with SIPp: Complete Guide

VoIP and SIP Call Flow Testing with SIPp: Complete Guide

SIP (Session Initiation Protocol) is the signaling backbone of modern VoIP infrastructure — from enterprise PBXes to carrier-grade IMS cores. Testing SIP implementations correctly requires more than checking that calls connect; you need to verify codec negotiation, DTMF handling, failover behavior, and that your infrastructure holds up under load. SIPp is the industry-standard open-source tool for all of this.

SIP Protocol Fundamentals

Before diving into testing, a quick protocol grounding. A basic SIP INVITE flow:

UAC (caller)          Proxy / B2BUA          UAS (callee)
    |                      |                      |
    |---INVITE ----------->|                      |
    |                      |---INVITE ----------->|
    |                      |<--100 Trying---------|
    |<--100 Trying---------|                      |
    |                      |<--180 Ringing--------|
    |<--180 Ringing--------|                      |
    |                      |<--200 OK (SDP)-------|
    |<--200 OK (SDP)-------|                      |
    |---ACK --------------->|---ACK -------------->|
    |<=================== RTP media =============>|
    |---BYE--------------->|---BYE -------------->|
    |                      |<--200 OK-------------|
    |<--200 OK-------------|                      |

Key headers to validate in every test:

  • From, To, Call-ID, CSeq — dialog identification
  • Contact — where to send subsequent requests
  • Via — routing record
  • Content-Type: application/sdp — media description

SIPp Architecture

SIPp operates in two roles:

  • UAC (User Agent Client): Generates calls, plays scenarios
  • UAS (User Agent Server): Answers calls, plays server scenarios

Scenarios are defined in XML files. SIPp supports variable substitution, regexp matching, conditional branching, CSV-driven test data, and RTP media generation.

Basic UAC Scenario (INVITE → 200 OK → BYE)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE scenario SYSTEM "sipp.dtd">
<scenario name="Basic UAC">
  <!-- Send INVITE -->
  <send retrans="500">
    <![CDATA[
      INVITE sip:[service]@[remote_ip]:[remote_port] SIP/2.0
      Via: SIP/2.0/[transport] [local_ip]:[local_port];branch=[branch]
      From: "Test Caller" <sip:caller@[local_ip]>;tag=[pid]SIPpTag00[call_number]
      To: <sip:[service]@[remote_ip]:[remote_port]>
      Call-ID: [call_id]
      CSeq: 1 INVITE
      Contact: sip:caller@[local_ip]:[local_port]
      Max-Forwards: 70
      Content-Type: application/sdp
      Content-Length: [len]

      v=0
      o=user1 53655765 2353687637 IN IP[local_ip_type] [local_ip]
      s=-
      c=IN IP[local_ip_type] [local_ip]
      t=0 0
      m=audio [media_port] RTP/AVP 0 8 101
      a=rtpmap:0 PCMU/8000
      a=rtpmap:8 PCMA/8000
      a=rtpmap:101 telephone-event/8000
      a=fmtp:101 0-15
    ]]>
  </send>

  <!-- Receive 100 Trying (optional) -->
  <recv response="100" optional="true" />

  <!-- Receive 180 Ringing (optional) -->
  <recv response="180" optional="true" />

  <!-- Receive 200 OK -->
  <recv response="200" rtd="true">
    <!-- Extract Contact for ACK and BYE routing -->
    <action>
      <ereg regexp="Contact: <([^>]+)>" 
            search_in="hdr" 
            header="Contact:" 
            assign_to="contact_uri" />
    </action>
  </recv>

  <!-- Send ACK -->
  <send>
    <![CDATA[
      ACK [contact_uri] SIP/2.0
      Via: SIP/2.0/[transport] [local_ip]:[local_port];branch=[branch]
      From: "Test Caller" <sip:caller@[local_ip]>;tag=[pid]SIPpTag00[call_number]
      To: <sip:[service]@[remote_ip]:[remote_port]>[peer_tag_param]
      Call-ID: [call_id]
      CSeq: 1 ACK
      Max-Forwards: 70
      Content-Length: 0
    ]]>
  </send>

  <!-- Hold for call duration (3 seconds) -->
  <pause milliseconds="3000" />

  <!-- Send BYE -->
  <send retrans="500">
    <![CDATA[
      BYE [contact_uri] SIP/2.0
      Via: SIP/2.0/[transport] [local_ip]:[local_port];branch=[branch]
      From: "Test Caller" <sip:caller@[local_ip]>;tag=[pid]SIPpTag00[call_number]
      To: <sip:[service]@[remote_ip]:[remote_port]>[peer_tag_param]
      Call-ID: [call_id]
      CSeq: 2 BYE
      Max-Forwards: 70
      Content-Length: 0
    ]]>
  </send>

  <!-- Receive 200 OK for BYE -->
  <recv response="200" />

  <!-- Statistics counters -->
  <ResponseTimeRepartition value="100, 200, 300, 500, 1000, 2000, 5000" />
  <CallLengthRepartition value="10, 50, 100, 500, 1000, 5000, 10000" />
</scenario>

Run the scenario:

# Single call test
sipp -sf uac_basic.xml \
     -s 1000 \
     192.168.1.100:5060 \
     -m 1 \
     -l 1 \
     -trace_msg \
     -message_file sipp-messages.log

# Load test: 100 simultaneous calls, 10 calls/second, run for 60 seconds
sipp -sf uac_basic.xml \
     -s 1000 \
     192.168.1.100:5060 \
     -r 10 \       # Call rate: 10 per second
     -l 100 \      # Max simultaneous calls
     -d 6000 \     # Call duration: 6 seconds
     -m 600 \      # Total calls: 600
     -trace_stat \
     -stf stats.csv

Load Testing VoIP Infrastructure

Interpreting SIPp Statistics

import csv
import statistics

def analyze_sipp_stats(stats_file):
    """Parse SIPp stats CSV and report key metrics."""
    with open(stats_file) as f:
        reader = csv.DictReader(f, delimiter=';')
        rows = list(reader)
    
    # Extract per-second call setup times
    call_setup_times = []
    for row in rows:
        try:
            # RTD1 = Response Time Distribution 1 (INVITE → 200 OK)
            rtd = float(row.get("ResponseTime1(Avg)", 0))
            if rtd > 0:
                call_setup_times.append(rtd)
        except ValueError:
            continue
    
    if call_setup_times:
        print(f"Call Setup Time:")
        print(f"  Min:    {min(call_setup_times):.0f}ms")
        print(f"  Max:    {max(call_setup_times):.0f}ms")
        print(f"  Avg:    {statistics.mean(call_setup_times):.0f}ms")
        print(f"  P95:    {sorted(call_setup_times)[int(len(call_setup_times)*0.95)]:.0f}ms")
    
    # Check for failures
    last_row = rows[-1] if rows else {}
    failed = int(last_row.get("FailedCall", 0))
    total = int(last_row.get("TotalCallCreated", 1))
    success_rate = (total - failed) / total * 100
    
    print(f"\nCall Success Rate: {success_rate:.2f}% ({total - failed}/{total})")
    if success_rate < 99.0:
        print(f"WARNING: Success rate below 99% threshold")

analyze_sipp_stats("stats.csv")

DTMF Testing

DTMF (Dual Tone Multi-Frequency) testing is critical for IVR systems, call routing, and legacy PSTN integration. SIPp supports RTP RFC 2833 telephone-event injection.

<!-- DTMF testing scenario: call, then send digits "1234#" -->
<scenario name="DTMF Test">
  <!-- ... INVITE, receive 200 OK, send ACK as above ... -->
  
  <!-- Wait for IVR prompt (2 seconds) -->
  <pause milliseconds="2000" />
  
  <!-- Send DTMF digit '1' via RTP telephone-event (payload type 101) -->
  <send>
    <![CDATA[
      INFO sip:[service]@[remote_ip]:[remote_port] SIP/2.0
      Via: SIP/2.0/[transport] [local_ip]:[local_port];branch=[branch]
      From: <sip:caller@[local_ip]>;tag=[pid]SIPpTag00[call_number]
      To: <sip:[service]@[remote_ip]:[remote_port]>[peer_tag_param]
      Call-ID: [call_id]
      CSeq: 2 INFO
      Content-Type: application/dtmf-relay
      Content-Length: 14

      Signal=1
      Duration=160
    ]]>
  </send>
  <recv response="200" />
  
  <!-- Repeat for each digit -->
  <pause milliseconds="500" />
  <!-- ... more digits ... -->
</scenario>

For RFC 2833 in-band DTMF, SIPp sends actual RTP packets with PT=101. Validate receipt at the far end:

# Capture and verify DTMF events with tshark
tshark -i eth0 \
       -Y "rtp.payload_type == 101" \
       -T fields \
       -e rtp.timestamp \
       -e rtp.seq \
       -e rtp.p.rfc2833.event \
       -e rtp.p.rfc2833.end_of_event \
       -e rtp.p.rfc2833.duration

Codec Negotiation Testing (SDP)

A critical test: verify that the SIP proxy/B2BUA correctly negotiates codec preferences and that the far end uses the negotiated codec.

import re
import subprocess

def extract_sdp_from_sip(pcap_file):
    """Extract SDP bodies from SIP messages."""
    result = subprocess.run([
        "tshark", "-r", pcap_file,
        "-Y", "sdp",
        "-T", "fields",
        "-e", "sdp.media",
        "-e", "sdp.media.attribute",
        "-e", "ip.src",
        "-e", "ip.dst"
    ], capture_output=True, text=True)
    return result.stdout

def verify_codec_negotiation(pcap_file, expected_codec="PCMU/8000"):
    """
    Verify that offer contains G.711 PCMU and that the answer
    agrees on PCMU (not falling back to PCMA or G.729).
    """
    sdp_data = extract_sdp_from_sip(pcap_file)
    
    # Find INVITE offer
    offer_codecs = re.findall(r"a=rtpmap:(\d+) ([^/]+/\d+)", sdp_data)
    answer_codecs = re.findall(r"a=rtpmap:(\d+) ([^/]+/\d+)", sdp_data)
    
    print(f"Offered codecs: {[c[1] for c in offer_codecs]}")
    
    # Find RTP stream to verify actual codec used
    rtp_result = subprocess.run([
        "tshark", "-r", pcap_file,
        "-Y", "rtp",
        "-T", "fields",
        "-e", "rtp.payload_type",
        "-e", "frame.number"
    ], capture_output=True, text=True)
    
    pt_values = set(rtp_result.stdout.strip().split("\n"))
    # PT=0 = PCMU, PT=8 = PCMA, PT=18 = G.729
    pt_map = {"0": "PCMU/8000", "8": "PCMA/8000", "18": "G.729"}
    used_codecs = {pt_map.get(pt.split("\t")[0], f"PT={pt}") for pt in pt_values if pt}
    
    print(f"Codecs in RTP stream: {used_codecs}")
    assert expected_codec in used_codecs, \
        f"Expected {expected_codec} in RTP stream, found {used_codecs}"
    print(f"PASS: Codec negotiation correct — {expected_codec} used")

Call Quality Metrics: MOS, Jitter, Packet Loss

After confirming call setup, measure quality:

# Install PESQ/POLQA tools for MOS scoring, or use VoIPMonitor

# Capture RTP audio stream
tshark -r capture.pcap \
       -Y "rtp" \
       -T fields \
       -e rtp.timestamp \
       -e rtp.seq \
       -e rtp.ssrc \
       -e frame.time_epoch \
       > rtp-stream.tsv

python3 << 'EOF'
import csv

def analyze_rtp_quality(tsv_file):
    rows = []
    with open(tsv_file) as f:
        for line in f:
            parts = line.strip().split("\t")
            if len(parts) >= 4:
                rows.append({
                    "rtp_ts": int(parts[0]),
                    "seq": int(parts[1]),
                    "ssrc": parts[2],
                    "epoch": float(parts[3])
                })
    
    if len(rows) < 2:
        return
    
    # Calculate jitter (RFC 3550 method)
    jitter = 0.0
    jitter_values = []
    prev_transit = None
    
    for i in range(1, len(rows)):
        arrival_diff = (rows[i]["epoch"] - rows[i-1]["epoch"]) * 8000  # Convert to RTP timestamp units
        send_diff = rows[i]["rtp_ts"] - rows[i-1]["rtp_ts"]
        d = abs(arrival_diff - send_diff)
        jitter += (d - jitter) / 16.0
        jitter_values.append(jitter)
    
    # Packet loss
    seqs = [r["seq"] for r in rows]
    expected = max(seqs) - min(seqs) + 1
    received = len(set(seqs))
    loss_pct = (expected - received) / expected * 100
    
    avg_jitter_ms = (sum(jitter_values) / len(jitter_values)) / 8.0  # Convert back to ms
    
    print(f"RTP Stream Quality:")
    print(f"  Packets received: {received}/{expected}")
    print(f"  Packet loss:      {loss_pct:.2f}%")
    print(f"  Average jitter:   {avg_jitter_ms:.2f}ms")
    
    # Quality thresholds (ITU-T G.114)
    if loss_pct > 1.0:
        print("  WARNING: Packet loss > 1% will degrade MOS below 3.5")
    if avg_jitter_ms > 30:
        print("  WARNING: Jitter > 30ms may cause audio artifacts")

analyze_rtp_quality("rtp-stream.tsv")
EOF

B2BUA Failover Testing

B2BUA (Back-to-Back User Agent) systems must maintain call state through failures. Testing failover:

#!/bin/bash
# B2BUA failover test: establish calls, kill primary B2BUA, verify call continuity

SIP_SERVER="192.168.1.100"
FAILOVER_SERVER="192.168.1.101"

echo "Step 1: Establish 50 simultaneous calls through primary B2BUA"
sipp -sf uac_basic.xml \
     -s 1000 $SIP_SERVER:5060 \
     -r 10 -l 50 -d 30000 -m 50 \
     -bg &  # Run in background

sleep 5  # Wait for calls to establish

echo "Step 2: Kill primary B2BUA"
ssh admin@$SIP_SERVER "sudo systemctl stop kamailio"

sleep 2

echo "Step 3: Verify failover server is handling traffic"
# Check active calls on failover server
ssh admin@$FAILOVER_SERVER "kamctl dialog list | wc -l"

echo "Step 4: Verify no new call failures after failover"
# New calls should route to failover
sipp -sf uac_basic.xml \
     -s 1000 $FAILOVER_SERVER:5060 \
     -r 5 -l 10 -d 5000 -m 10 \
     -trace_err

echo "Step 5: Restore primary and verify re-registration"
ssh admin@$SIP_SERVER "sudo systemctl start kamailio"
sleep 10
ssh admin@$SIP_SERVER "kamctl ul show | wc -l"

Key Takeaways

  • SIPp scenario XML is the lingua franca of SIP testing — invest in building a library of scenarios for common call flows
  • Load test with realistic call rates and durations; VoIP infrastructure often fails under burst traffic, not steady state
  • DTMF testing requires both in-band (RFC 2833) and out-of-band (SIP INFO) methods depending on your infrastructure
  • Capture RTP streams and compute jitter/loss directly from packet timestamps — MOS below 3.5 indicates perceptible quality degradation
  • B2BUA failover tests must verify both that existing calls survive and that new calls route correctly after failover

Read more

Start now free