Current Location: Home> Latest Articles> Use pack() to create a binary data packet for network protocol

Use pack() to create a binary data packet for network protocol

M66 2025-05-29

When writing PHP network communication programs, it is often necessary to build binary data packets that conform to a specific protocol format. In this case, the pack() function is an indispensable tool. It can package PHP variables into binary strings in the specified format, making it convenient for communication with the underlying network or hardware.

1. What is the pack() function?

pack() is a built-in function in PHP, and its basic syntax is as follows:

 string pack(string $format, mixed ...$values)
  • $format is a format string used to specify the way to package subsequent data;

  • $values ​​is the value that needs to be packaged.

The data produced through pack() is usually used to build a binary structure that conforms to a certain communication protocol format, such as request messages in the TCP/IP protocol, client messages of the game server, data reported by the Internet of Things sensor, etc.

2. Common format character description

Here are some common format characters and their meanings:

Format characters describe Number of bytes occupied
C Unsigned char (8 bits) 1
n Unsigned short (16-bit, network endian) 2
N Unsigned long (32 bits, network endianness) 4
a NUL Completed string (specified length) variable
A A string with spaces filled (specified length) variable
H Hexadecimal string (high bit priority) Every two bytes
x Fill in bytes (skip one byte) 1

In network protocols, n and N are particularly common because they are "network endian" (big-endian endian) and are suitable for cross-platform communication.

3. Construct a simple binary protocol

Suppose we need to construct a protocol packet, the structure is as follows:

  • 1 byte: Version number (unsigned 8 bits)

  • 2 bytes: Message type (unsigned 16 bits)

  • 4 bytes: User ID (unsigned 32 bits)

  • 10 bytes: username (ASCII, space filling)

We can use pack() in the following ways:

 <?php
$version = 1;          // 1 byte
$type = 100;           // 2 byte
$userId = 123456789;   // 4 byte
$username = 'Alice';   // most 10 byte,Complete spaces

$packet = pack('CnNA10', $version, $type, $userId, $username);

echo bin2hex($packet); // View packaged hexadecimal results
?>

The $packet generated by this code is a binary data that conforms to the protocol format and can be sent directly to the remote service through socket or stream.

4. Example of communication with the server

Assuming that the remote server address is m66.net and the port is 9000 , you can send the binary data generated above through a TCP connection:

 <?php
$fp = stream_socket_client("tcp://m66.net:9000", $errno, $errstr, 5);
if (!$fp) {
    die("Connection failed: $errstr ($errno)");
}

// Constructing data packets
$packet = pack('CnNA10', 1, 100, 123456789, 'Alice');

// Send data
fwrite($fp, $packet);

// Receive a response
$response = fread($fp, 1024);

// Close the connection
fclose($fp);

echo "Server response: " . bin2hex($response);
?>

This is a complete basic process of building a binary package with pack() and sending it to a remote server (such as m66.net ).

5. Debugging skills

  • Use bin2hex() or unpack() to view and verify that the packaged data meets expectations;

  • Use network packet capture tools such as Wireshark to analyze sent data;

  • Pay attention to the endianness. Most network protocols use the network byte order format.

Conclusion

pack() is a powerful tool in PHP for handling underlying binary protocols. Mastering it can not only help you communicate efficiently with the C/C++ server, but also help you implement various customized protocol designs. Whether you are doing game development, Internet of Things communication, or building your own application-layer protocol, pack() is a function worthy of in-depth understanding and application.