NAME

Net::DHCP::Packet - Object methods to create a DHCP packet.

VERSION

version 0.9

SYNOPSIS

use Net::DHCP::Packet;

my $p = Net::DHCP::Packet->new(

    'Chaddr' => '000BCDEF',
    'Xid' => 0x9F0FD,
    'Ciaddr' => '0.0.0.0',
    'Siaddr' => '0.0.0.0',
    'Hops' => 0

);

DESCRIPTION

Represents a DHCP packet as specified in RFC 1533, RFC 2132.

CONSTRUCTOR

Create a new Net::DHCP::Packet object from a raw buffer, a set of named arguments, or with no arguments for defaults.

new()
new( BUFFER )
new( ARG => VALUE, ARG => VALUE... )

Creates an Net::DHCP::Packet object, which can be used to send or receive DHCP network packets. BOOTP is not supported.

Without argument, a default empty packet is created.

$packet = Net::DHCP::Packet();

A BUFFER argument is interpreted as a binary buffer like one provided by the socket recv() function. if the packet is malformed, a fatal error is issued.

use IO::Socket::INET;
use Net::DHCP::Packet;

$sock = IO::Socket::INET->new(LocalPort => 67, Proto => "udp", Broadcast => 1)
        or die "socket: $@";

while ($sock->recv($newmsg, 1024)) {
    $packet = Net::DHCP::Packet->new($newmsg);
    print $packet->toString();
}

To create a fresh new packet new() takes arguments as a key-value pairs :

ARGUMENT   FIELD      OCTETS       DESCRIPTION
--------   -----      ------       -----------

Op         op            1  Message op code / message type.
                            1 = BOOTREQUEST, 2 = BOOTREPLY
Htype      htype         1  Hardware address type, see ARP section in "Assigned
                            Numbers" RFC; e.g., '1' = 10mb ethernet.
Hlen       hlen          1  Hardware address length (e.g.  '6' for 10mb
                            ethernet).
Hops       hops          1  Client sets to zero, optionally used by relay agents
                            when booting via a relay agent.
Xid        xid           4  Transaction ID, a random number chosen by the
                            client, used by the client and server to associate
                            messages and responses between a client and a
                            server.
Secs       secs          2  Filled in by client, seconds elapsed since client
                            began address acquisition or renewal process.
Flags      flags         2  Flags (see figure 2).
Ciaddr     ciaddr        4  Client IP address; only filled in if client is in
                            BOUND, RENEW or REBINDING state and can respond
                            to ARP requests.
Yiaddr     yiaddr        4  'your' (client) IP address.
Siaddr     siaddr        4  IP address of next server to use in bootstrap;
                            returned in DHCPOFFER, DHCPACK by server.
Giaddr     giaddr        4  Relay agent IP address, used in booting via a
                            relay agent.
Chaddr     chaddr       16  Client hardware address.
Sname      sname        64  Optional server host name, null terminated string.
File       file        128  Boot file name, null terminated string; "generic"
                            name or null in DHCPDISCOVER, fully qualified
                            directory-path name in DHCPOFFER.
IsDhcp     isDhcp        4  Controls whether the packet is BOOTP or DHCP.
                            DHCP contains the "magic cookie" of 4 bytes.
                            0x63 0x82 0x53 0x63.
DHO_*code                   Optional parameters field.  See the options
                            documents for a list of defined options.
                            See Net::DHCP::Constants.
Padding    padding       *  Optional padding at the end of the packet

See below methods for values and syntax description.

Note: DHCP options are created in the same order as key-value pairs.

METHODS

ATTRIBUTE METHODS

See Net::DHCP::Packet::Attributes

DHCP OPTIONS METHODS

This section describes how to read or set DHCP options. Methods are given in two flavours : (i) text format with automatic type conversion, (ii) raw binary format.

Standard way of accessing options is through automatic type conversion, described in the "DHCP OPTIONS TYPES" section. Only a subset of types is supported, mainly those defined in rfc 2132.

Raw binary functions are provided for pure performance optimization, and for unsupported types manipulation.

setOptionValue( CODE, VALUE )

Sets a DHCP option field (overwrites any existing value for the same code). Common code values are listed in Net::DHCP::Constants DHO_*.

Values are automatically converted according to their data types, depending on their format as defined by RFC 2132. Please see "DHCP OPTIONS TYPES" for supported options and corresponding formats.

If you need access to the raw binary values, please use setOptionRaw().

$pac = Net::DHCP::Packet->new();
$pac->setOptionValue(DHO_DHCP_MESSAGE_TYPE(), DHCPINFORM());
$pac->setOptionValue(DHO_NAME_SERVERS(), "192.0.2.1", "192.0.2.2");
pushOptionValue( CODE, VALUE )

Appends a value to a multi-value DHCP option. If the option already exists, the value is added to the accumulated list; if the option has not been set yet, it is stored as a single value.

Only multi-value option formats are accepted (inets, inets2, bytes, shorts, csr, userclass, suboptions, hexa). Calling pushOptionValue on a scalar-only format (byte, short, int, inet, string, clientid, sipserv) will croak with an error.

Use setOptionValue when you want to overwrite; use pushOptionValue when you want to accumulate.

$pac = Net::DHCP::Packet->new();
$pac->pushOptionValue(DHO_NAME_SERVERS(), "192.0.2.1");
$pac->pushOptionValue(DHO_NAME_SERVERS(), "192.0.2.2");
DEPRECATED addOptionValue( CODE, VALUE )

Deprecated. Please use setOptionValue() instead.

addSubOptionValue( CODE, SUBCODE, VALUE )

Adds a DHCP sub-option field. Common code values are listed in Net::DHCP::Constants SUBOPTION_*.

Values are automatically converted according to their data types, depending on their format as defined by RFC 2132. Please see "DHCP OPTIONS TYPES" for supported options and corresponding formats.

If you need access to the raw binary values, please use addSubOptionRaw().

$pac = Net::DHCP::Packet->new();
$pac->addSubOptionValue(
    DHO_DHCP_AGENT_OPTIONS(),
    RAI_CIRCUIT_ID(),
    "my-circuit-id"
);
$pac->addSubOptionValue(
    DHO_DHCP_AGENT_OPTIONS(),
    RAI_REMOTE_ID(),
    "my-remote-id"
);
getOptionValue( CODE )

Returns the value of a DHCP option.

Automatic type conversion is done according to their data types, as defined in RFC 2132. Please see "DHCP OPTIONS TYPES" for supported options and corresponding formats.

If you need access to the raw binary values, please use getOptionRaw().

Return value is either a string or an array, depending on the context.

$ip  = $pac->getOptionValue(DHO_SUBNET_MASK());
$ips = $pac->getOptionValue(DHO_NAME_SERVERS());
setOptionRaw( CODE, VALUE )

Sets a DHCP OPTION in packed binary format (overwrites any existing value for the same code). Please see corresponding RFC for manual type conversion.

DEPRECATED addOptionRaw( CODE, VALUE )

Deprecated. Please use setOptionRaw() instead.

addSubOptionRaw( CODE, SUBCODE, VALUE )

Adds a DHCP SUB-OPTION provided in packed binary format. Please see corresponding RFC for manual type conversion.

getOptionRaw( CODE )

Gets a DHCP OPTION provided in packed binary format. Please see corresponding RFC for manual type conversion.

getSubOptionRaw( CODE, SUBCODE )

Gets a DHCP SUB-OPTION provided in packed binary format. Please see corresponding RFC for manual type conversion.

getSubOptionValue()

This is an empty stub for now

removeSubOption()

This is an empty stub for now

removeOption( CODE )

Remove option from option list.

packclientid( VALUE [, FORCE_TYPE ] )

Returns the packed Client-identifier.

Auto-detects format: even-length hex strings (e.g. "0010A706DFFF") are packed as type 1 (ether), plain text as type 0 (fqdn).

To override auto-detection, pass a second argument:

packclientid('deadbeef', 'fqdn')   # force type 0, treat hex as text
packclientid('myhost',   'ether')  # force type 1, treat text as raw bytes

Warning: if a value is both valid hex and meaningful text (e.g. a hostname that happens to be even-length hex), the heuristic picks type 1. Use setOptionRaw or the $force_type parameter to be explicit.

For flexible MAC address input from many formats, use NetAddr::MAC:

use NetAddr::MAC;
my $mac = NetAddr::MAC->new('00:11:22:aa:bb:cc');
$p->setOptionRaw(DHO_DHCP_CLIENT_IDENTIFIER(),
    pack('C H*', 1, $mac->as_basic));

See https://tools.ietf.org/html/rfc2132#section-9.14

See also https://tools.ietf.org/html/rfc4361

unpackclientid

returns the unpacked clientid.

Decodes: type 0 as a string type 1 as a mac address (hex string) everything is passed through

See https://tools.ietf.org/html/rfc2132#section-9.14

See also https://tools.ietf.org/html/rfc4361

packsipserv( VALUE [, FORCE_TYPE ] )

Returns the packed SIP server field.

Auto-detects format: IP addresses are packed as type 1, domain names as type 0.

To override auto-detection, pass a second argument:

packsipserv('192.0.2.1',   'domain')  # force type 0, treat IP as text
packsipserv('sip.example', 'ip')     # force type 1, treat domain as IP

See https://tools.ietf.org/html/rfc3361

unpacksipserv

returns the unpacked sip server.

Decodes: type 0 as a domain name string type 1 as space-separated IPv4 addresses (e.g. "192.0.2.1 203.0.113.1") everything else is passed through

packcsr( ARRAYREF )

returns the packed Classless Static Route option built from a list of CIDR prefix/gateway pairs. Each pair is [prefix, gateway] where prefix is a CIDR string like "192.0.2.0/24" and gateway is an IPv4 string like "192.0.2.1".

unpackcsr

Returns the unpacked Classless Static Route as a list of alternating prefix/mask and gateway strings (e.g. "192.0.2.0/24", "192.0.2.1").

packuserclass( VALUE [, VALUE...] )

returns the packed User Class option (code 77) per RFC 3004. Each value is encoded as a [len][data] block. Accepts one or more strings; undef and empty strings are skipped.

packuserclass('ipxe')
packuserclass('ipxe', 'BIOS')
unpackuserclass( STRING )

returns the unpacked User Class option (code 77). Decodes each [len][data] block and joins them with ', '.

addOption( CODE, VALUE )

Removed as of version 0.60. Please use setOptionRaw() instead.

getOption( CODE )

Removed as of version 0.60. Please use getOptionRaw() instead.

DHCP OPTIONS TYPES

This section describes supported option types (cf. RFC 2132).

For unsupported data types, please use getOptionRaw() and setOptionRaw to manipulate binary format directly.

dhcp message type

Only supported for DHO_DHCP_MESSAGE_TYPE (053) option. Converts a integer to a single byte.

Option code for 'dhcp message' format:

(053) DHO_DHCP_MESSAGE_TYPE

Example:

$pac->setOptionValue(DHO_DHCP_MESSAGE_TYPE(), DHCPINFORM());
string

Pure string attribute, no type conversion.

Option codes for 'string' format:

(012) DHO_HOST_NAME
(014) DHO_MERIT_DUMP
(015) DHO_DOMAIN_NAME
(017) DHO_ROOT_PATH
(018) DHO_EXTENSIONS_PATH
(047) DHO_NETBIOS_SCOPE
(056) DHO_DHCP_MESSAGE
(060) DHO_VENDOR_CLASS_IDENTIFIER
(062) DHO_NWIP_DOMAIN_NAME
(064) DHO_NIS_DOMAIN
(065) DHO_NIS_SERVER
(066) DHO_TFTP_SERVER
(067) DHO_BOOTFILE
(086) DHO_NDS_TREE_NAME
(098) DHO_USER_AUTHENTICATION_PROTOCOL

Example:

$pac->setOptionValue(DHO_TFTP_SERVER(), "foobar");
single ip address

Exactly one IP address, in dotted numerical format '192.168.1.1'.

Option codes for 'single ip address' format:

(001) DHO_SUBNET_MASK
(016) DHO_SWAP_SERVER
(028) DHO_BROADCAST_ADDRESS
(032) DHO_ROUTER_SOLICITATION_ADDRESS
(050) DHO_DHCP_REQUESTED_ADDRESS
(054) DHO_DHCP_SERVER_IDENTIFIER
(118) DHO_SUBNET_SELECTION

Example:

$pac->setOptionValue(DHO_SUBNET_MASK(), "255.255.255.0");
multiple ip addresses

Any number of IP address, in dotted numerical format '192.168.1.1'. Empty value allowed.

Option codes for 'multiple ip addresses' format:

(003) DHO_ROUTERS
(004) DHO_TIME_SERVERS
(005) DHO_NAME_SERVERS
(006) DHO_DOMAIN_NAME_SERVERS
(007) DHO_LOG_SERVERS
(008) DHO_COOKIE_SERVERS
(009) DHO_LPR_SERVERS
(010) DHO_IMPRESS_SERVERS
(011) DHO_RESOURCE_LOCATION_SERVERS
(041) DHO_NIS_SERVERS
(042) DHO_NTP_SERVERS
(044) DHO_NETBIOS_NAME_SERVERS
(045) DHO_NETBIOS_DD_SERVER
(048) DHO_FONT_SERVERS
(049) DHO_X_DISPLAY_MANAGER
(068) DHO_MOBILE_IP_HOME_AGENT
(069) DHO_SMTP_SERVER
(070) DHO_POP3_SERVER
(071) DHO_NNTP_SERVER
(072) DHO_WWW_SERVER
(073) DHO_FINGER_SERVER
(074) DHO_IRC_SERVER
(075) DHO_STREETTALK_SERVER
(076) DHO_STDA_SERVER
(085) DHO_NDS_SERVERS

Example:

$pac->setOptionValue(DHO_NAME_SERVERS(), "192.0.2.11 198.51.100.10");
pairs of ip addresses

Even number of IP address, in dotted numerical format '192.168.1.1'. Empty value allowed.

Option codes for 'pairs of ip address' format:

(021) DHO_POLICY_FILTER
(033) DHO_STATIC_ROUTES

Example:

$pac->setOptionValue(DHO_STATIC_ROUTES(), "192.0.2.1 198.51.100.254");
byte, short and integer

Numerical value in byte (8 bits), short (16 bits) or integer (32 bits) format.

Option codes for 'byte (8)' format:

(019) DHO_IP_FORWARDING
(020) DHO_NON_LOCAL_SOURCE_ROUTING
(023) DHO_DEFAULT_IP_TTL
(027) DHO_ALL_SUBNETS_LOCAL
(029) DHO_PERFORM_MASK_DISCOVERY
(030) DHO_MASK_SUPPLIER
(031) DHO_ROUTER_DISCOVERY
(034) DHO_TRAILER_ENCAPSULATION
(036) DHO_IEEE802_3_ENCAPSULATION
(037) DHO_DEFAULT_TCP_TTL
(039) DHO_TCP_KEEPALIVE_GARBAGE
(046) DHO_NETBIOS_NODE_TYPE
(052) DHO_DHCP_OPTION_OVERLOAD
(116) DHO_AUTO_CONFIGURE

Option codes for 'short (16)' format:

(013) DHO_BOOT_SIZE
(022) DHO_MAX_DGRAM_REASSEMBLY
(026) DHO_INTERFACE_MTU
(057) DHO_DHCP_MAX_MESSAGE_SIZE

Option codes for 'integer (32)' format:

(002) DHO_TIME_OFFSET
(024) DHO_PATH_MTU_AGING_TIMEOUT
(035) DHO_ARP_CACHE_TIMEOUT
(038) DHO_TCP_KEEPALIVE_INTERVAL
(051) DHO_DHCP_LEASE_TIME
(058) DHO_DHCP_RENEWAL_TIME
(059) DHO_DHCP_REBINDING_TIME

Examples:

$pac->setOptionValue(DHO_DHCP_OPTION_OVERLOAD(), 3);
$pac->setOptionValue(DHO_INTERFACE_MTU(), 1500);
$pac->setOptionValue(DHO_DHCP_RENEWAL_TIME(), 24*60*60);
multiple bytes, shorts

A list a bytes or shorts.

Option codes for 'multiple bytes (8)' format:

(055) DHO_DHCP_PARAMETER_REQUEST_LIST

Option codes for 'multiple shorts (16)' format:

(025) DHO_PATH_MTU_PLATEAU_TABLE
(117) DHO_NAME_SERVICE_SEARCH

Examples:

$pac->setOptionValue(DHO_DHCP_PARAMETER_REQUEST_LIST(),  "1 3 6 12 15 28 42 72");

SERIALIZATION METHODS

serialize()

Converts a Net::DHCP::Packet to a string, ready to put on the network.

If any option's packed data exceeds 255 bytes, it is split into multiple option instances per RFC 3396 (Long Options). This applies to all option storage types: scalars, arrayrefs (e.g. CSR), and hashrefs (suboptions).

marshall( BYTES )

The inverse of serialize. Converts a string, presumably a received UDP packet, into a Net::DHCP::Packet.

Per RFC 3396, duplicate option instances are automatically concatenated during parsing. Packets with options split across multiple instances (e.g. vendor-specific options with more than 255 bytes of suboptions) are reconstructed correctly.

If the packet is malformed, a fatal error is produced.

HELPER METHODS

toString()

Returns a textual representation of the packet, for debugging.

packsuboptions( LIST )

Transforms an list of lists into packed option. For option 43 (vendor specific), 82 (relay agent) etc. Output is canonical TLV: type|len|data triplets with no outer wrapping.

unpacksuboptions( STRING )

Unpacks sub-options to a list of lists

min_len_handling( LEVEL )

By default, the level is set to 0. If the packet is shorter than the minimum BOOTP_MIN_LEN, a warning is issued; if it is shorter than the absolute minimum BOOTP_ABSOLUTE_MIN_LEN, an exception is thrown.

If the level is set to 1, even the absolute minimum just warns.

Setting the level to 2 means the packet length checks are skipped altogether.

Without a parameter, the method returns the current level.

multi_value_array_ref (BOOL)

Controls whether getOptionValue returns multi-value options as arrayrefs instead of comma-joined strings. Affects all plural DHCP option formats (inets, bytes, shorts, userclass, csr, etc.).

When enabled, getOptionValue(6) returns ["192.0.2.1", "192.0.2.2"] instead of "192.0.2.1, 192.0.2.2".

May also be set globally via $Net::DHCP::multi_value_array_ref or passed as a constructor argument. The instance value is captured at construction time and is independent of the global thereafter.

Default is disabled (legacy comma-joined string behavior).

is_list_format( FORMAT )

Returns true if the format type supports multiple values (list/accumulation semantics). List-capable formats are those ending in s (inets, strings, bytes, shorts) plus csr, userclass, hexa, and inets2. Used internally by pushOptionValue and setOptionValue.

See also Net::DHCP::Packet::IPv4Utils

EXAMPLES

Sending a simple DHCP packet:

#!/usr/bin/perl
# Simple DHCP client - sending a broadcasted DHCP Discover request

use IO::Socket::INET;
use Net::DHCP::Packet;
use Net::DHCP::Constants;

# create DHCP Packet
$discover = Net::DHCP::Packet->new(
    Xid                      => int(rand(0xFFFFFFFF)),
    Flags                    => 0x8000,
    DHO_DHCP_MESSAGE_TYPE()  => DHCPDISCOVER(),
);

# send packet
$handle = IO::Socket::INET->new(
    Proto     => 'udp',
    Broadcast => 1,
    PeerPort  => '67',
    LocalPort => '68',
    PeerAddr  => '255.255.255.255',
) or die "socket: $@";

$handle->send($discover->serialize())
    or die "Error sending broadcast inform: $!\n";

Sniffing DHCP packets.

#!/usr/bin/perl
# Simple DHCP server - listen to DHCP packets and print them

use IO::Socket::INET;
use Net::DHCP::Packet;

$sock = IO::Socket::INET->new(
    LocalPort => 67,
    Proto     => 'udp',
    Broadcast => 1,
) or die "socket: $@";

while ($sock->recv($newmsg, 1024)) {
    $packet = Net::DHCP::Packet->new($newmsg);
    print STDERR $packet->toString();
}

Sending a LEASEQUERY (provided by John A. Murphy).

#!/usr/bin/perl
# Simple DHCP client - send a LeaseQuery (by IP) and receive the response

use IO::Socket::INET;
use Net::DHCP::Packet;
use Net::DHCP::Constants;

$usage = "usage: $0 DHCP_SERVER_IP DHCP_CLIENT_IP\n";
$ARGV[1] or die $usage;

# create a socket
$handle = IO::Socket::INET->new(
    Proto     => 'udp',
    Broadcast => 1,
    PeerPort  => '67',
    LocalPort => '67',
    PeerAddr  => $ARGV[0],
) or die "socket: $@";

# create DHCP Packet
$inform = Net::DHCP::Packet->new(
    Op                       => BOOTREQUEST(),
    Htype                    => 0,
    Hlen                     => 0,
    Ciaddr                   => $ARGV[1],
    Giaddr                   => $handle->sockhost(),
    Xid                      => int(rand(0xFFFFFFFF)),
    DHO_DHCP_MESSAGE_TYPE()  => DHCPLEASEQUERY,
);

# send request
$handle->send($inform->serialize())
    or die "Error sending LeaseQuery: $!\n";

# receive response
$handle->recv($newmsg, 1024) or die;
$packet = Net::DHCP::Packet->new($newmsg);
print $packet->toString();

A simple DHCP Server is provided in the "examples" directory. It is composed of "dhcpd.pl" a *very* simple server example, and "dhcpd_test.pl" a simple tester for this server.

SEE ALSO

Net::DHCP::Constants, Net::DHCP::Packet::IPv4Utils, Net::DHCP::Packet::Attributes, Net::DHCP::Packet::OrderOptions.

AUTHOR

Dean Hamstead <dean@fragfest.com.au>

COPYRIGHT AND LICENSE

This software is Copyright (c) 2026 by Dean Hamstead.

This is free software, licensed under:

The MIT (X11) License