HeadlinesBriefing favicon HeadlinesBriefing.com

Netstrings: A Simple Self-Delimiting String Encoding

Hacker News •
×

Netstrings, developed by D. J. Bernstein, offer a straightforward method for encoding strings that is easy to generate and parse. A key advantage is that a netstring declares the string's size upfront, allowing applications to pre-allocate sufficient memory. This feature is particularly beneficial for network protocols, where sequences of strings can be encoded as netstrings, concatenated, and transmitted over reliable stream protocols like TCP. Netstrings can also be used recursively, encoding a sequence of netstrings into a single string.

A netstring is defined by the format `[len]:[string],`, where `[len]` is a non-empty sequence of ASCII digits representing the string's length, and `[string]` is the actual data. For example, the string "hello world!" is encoded as `12:hello world!,`. The empty string is represented as `0:,`.

Netstrings enhance security by mitigating risks like buffer overflows, which plagued older encoding methods such as CRLF. Unlike CRLF, which doesn't declare string size in advance, netstrings enable robust memory management, as demonstrated in the provided C code examples for both encoding and decoding. This inherent safety makes netstrings a valuable tool for building secure network applications.