Networking in C · intermediate · ~12 min

Pull the method out of a SIP message

Extract the request method (such as `INVITE`, `REGISTER`, `OPTIONS`, or `BYE`) from a SIP message.

Overview

The plan is simple:

  • Scan forward to the first space.
  • Check that every character before it is an uppercase letter (A-Z).
  • Copy the method into the output buffer, staying within its size limit.

Why it matters

SIP gateways sit on the public internet, exposed to untrusted input.

Rejecting a malformed method right at the entry point is cheap. Skipping that check can be expensive.

Lesson

Why this matters

SIP is the protocol behind every VoIP call and WebRTC signalling exchange. (SIP stands for Session Initiation Protocol; it sets up and tears down voice and video sessions.)

SIP looks almost exactly like HTTP. Both have:

  • A request line
  • Headers
  • A blank line
  • An optional body

The bug surface is similar too. The first place to get input validation right is the request line.

Here we extract just the method. Later modules can pull out the URI and the Via chain.

What the wire looks like

INVITE sip:alice@example.com SIP/2.0\r\n
Via: SIP/2.0/UDP 10.0.0.1:5060;branch=z9hG4bK1234\r\n
...

The method is the first token, INVITE, ending at the first space.

Your job

Implement this function:

int parse_sip_method(const char *msg, char *out, size_t cap);

It should:

  • Copy the leading method (everything up to the first space) into out.
  • NUL-terminate the result.
  • Return the number of bytes written.

Return -1 on any failure. Failure cases:

  • msg or out is NULL, or cap == 0.
  • No space found within the first 16 bytes.
  • The method would overflow cap.
  • Any non-letter character appears before the first space.

Common mistakes

  • Allowing lowercase. Real SIP methods are uppercase ASCII.
  • Forgetting the NUL terminator on the bounded output.
  • Treating arbitrary bytes as a method. Reject anything outside A-Z.

What this is NOT

  • A full SIP parser. Headers, SDP, and dialog tracking are all out of scope.
  • A signalling stack. We are only classifying the method.

Summary

  • The method is the first token, ending at the first space.
  • Accept uppercase letters only (A-Z); reject everything else.
  • Copy within the buffer's size limit and NUL-terminate.
  • Return the length written, or -1 on any failure.

Practice with these exercises