NetBurner 3.5.6
PDF Version |
UDP Packet Class - Complete UDP packet management. More...
#include <udp.h>
Public Member Functions | |
UDPPacket (OS_FIFO *pFifo, TickTimeout timeout) | |
Create UDP packet from FIFO with timeout. | |
UDPPacket (int sock) | |
Create UDP packet from socket (blocks until data available) | |
UDPPacket (PoolPtr p) | |
Create from raw pool buffer (ADVANCED - rarely needed) | |
UDPPacket (UDPPacket &pkt) | |
Move constructor - transfers ownership. | |
UDPPacket (bool bIsIpv6=false) | |
Construct a new UDP packet object. | |
~UDPPacket () | |
Destructor - automatically frees pool buffer. | |
bool | Receive (OS_FIFO *pFifo, uint32_t wait_ticks) |
Reuse packet object for multiple receives (efficiency optimization) | |
void | SetSourcePort (uint16_t port) |
Set source port (0=auto-assign ephemeral port, 1024-65535=specific port) | |
uint16_t | GetSourcePort (void) const |
Get source port from received packet or previously set value. | |
MACADR | GetMacSource () |
Get sender's MAC address (link-layer identification) | |
IPADDR | GetSourceAddress (void) |
Get source IP address of the packet. | |
IPADDR | GetDestinationAddress (void) |
Get destination IP address of the packet. | |
bool | bIsIPV6 () const |
Check if packet uses IPv6 addressing. | |
void | SetDestinationPort (uint16_t port) |
Set destination port (standard services: 53=DNS, 80=HTTP, 123=NTP, 161=SNMP) | |
uint16_t | GetDestinationPort (void) const |
Get destination port (for received packets: local port that received it) | |
uint16_t | GetPacketId (void) |
Get IP packet ID (used for fragment reassembly and packet tracking) | |
void | SetDSCP (uint8_t dscp) |
Set DSCP for QoS (0=best effort, 46=VoIP/EF, 34=video/AF41, 8=bulk/CS1) | |
uint8_t | GetDSCP (void) const |
Get DSCP value (0-63) | |
puint8_t | GetDataBuffer (bool bReAllocateIfNeeded=false) |
Get data buffer pointer for reading or writing. | |
void | SetDataSize (uint16_t numBytes) |
Set data size (REQUIRED after GetDataBuffer() writes) | |
uint16_t | GetDataSize (void) const |
Get current data size in bytes. | |
void | AddData (puint8_t pData, uint16_t len) |
Add binary data (auto-updates size - no SetDataSize() needed) | |
void | AddData (PCSTR pData) |
Add null-terminated string (includes NULL in packet) | |
void | AddDataWord (uint16_t w) |
Add 16-bit value. | |
void | AddDataByte (uint8_t b) |
Add 8-bit value. | |
BOOL | Validate (void) |
Validate received packet (checks checksum and data presence) | |
void | ResetData (void) |
Reset data size to 0 (clears packet) | |
void | SendAndKeep (const IPADDR &to, uint8_t ttl=0) |
Send copy, keep original (for sending to multiple destinations) | |
void | Send (const IPADDR &to, uint8_t ttl=0) |
Send and free buffer (recommended - most efficient) | |
void | SendAndKeepViaInterfaceNum (const IPADDR &to, int interface, uint8_t ttl=0) |
Send copy via specific interface, keep original. | |
void | SendViaInterfaceNum (const IPADDR &to, int interface, uint8_t ttl=0) |
Send via specific interface and free buffer. | |
void | SendAndKeepViaIfAddr (const IPADDR &to, const IPADDR &from_ip, uint8_t ttl=0) |
Send a packet and retain a copy via a specific interface address. | |
void | SendViaIfAddr (const IPADDR &to, const IPADDR &from_ip, uint8_t ttl=0) |
Send a packet via a specific interface address. | |
UDP Packet Class - Complete UDP packet management.
Provides comprehensive UDP packet handling with automatic memory management, flexible data insertion methods, and advanced sending options.
Method 1: sprintf with GetDataBuffer() - Best for formatted text
Method 2: AddData() - Best for binary/incremental data
UDPPacket::UDPPacket | ( | OS_FIFO * | pFifo, |
TickTimeout | timeout ) |
Create UDP packet from FIFO with timeout.
Constructs a UDPPacket by receiving data from a registered FIFO queue with a specified timeout. This constructor blocks until either a packet arrives or the timeout expires. The packet may be invalid even if the constructor returns, so ALWAYS call Validate() immediately after construction.
pFifo | Pointer to OS_FIFO queue registered with RegisterUDPFifo() |
timeout | Timeout duration in system ticks:
|
Expand for Example Usage
Scenario | Use This Constructor? | Better Alternative |
---|---|---|
One-time receive | Yes | N/A |
Loop with many receives | No | Use Receive() method |
Quick test/debug | Yes | Convenient for testing |
Performance critical | No | Reuse packet object |
Multiple ports | Maybe | Consider Receive() |
UDPPacket::UDPPacket | ( | int | sock | ) |
Create UDP packet from socket (blocks until data available)
Constructs a UDPPacket by receiving data from a UDP socket. This constructor blocks until data is available on the socket. Best practice: Use after select() or poll() to ensure data is ready before calling this constructor to avoid unexpected blocking.
sock | UDP socket descriptor from CreateRxUdpSocket() or CreateRxTxUdpSocket() |
Expand for Example Usage
Approach | Pros | Cons |
---|---|---|
Socket (this) | Works with select(), standard BSD sockets | Requires select() setup |
FIFO (other constructors) | Simple, RTOS-native, efficient | NetBurner-specific API |
UDPPacket::UDPPacket | ( | PoolPtr | p | ) |
Create from raw pool buffer (ADVANCED - rarely needed)
Constructs a UDPPacket by wrapping an existing pool buffer pointer. This is an advanced constructor for custom protocol implementations that work directly with the NetBurner pool buffer system. The UDPPacket takes ownership of the buffer and will automatically free it when destroyed.
p | Pool buffer pointer (PoolPtr) containing packet data |
Expand for Example Usage
UDPPacket()
- Standard packet creationUDPPacket(bool)
- IPv4/IPv6 packet creationUDPPacket::UDPPacket | ( | UDPPacket & | pkt | ) |
Move constructor - transfers ownership.
Constructs a new UDPPacket by moving resources from an existing packet. The source packet transfers ownership of its internal buffers and state to the new packet. After the move, the source packet becomes invalid and should not be used.
pkt | Source packet to move from (will be invalidated) |
Expand for Example Usage
UDPPacket::UDPPacket | ( | bool | bIsIpv6 = false | ) |
Construct a new UDP packet object.
Creates a UDP packet object that can be used for sending or receiving UDP data. The packet is allocated with appropriate buffer space and initialized for either IPv4 or IPv6 operation.
bIsIpv6 | IP version selector:
|
Feature | IPv4 (false) | IPv6 (true) |
---|---|---|
Address Size | 32-bit (4 bytes) | 128-bit (16 bytes) |
Address Format | 192.168.1.100 | fe80::1234:5678:abcd:ef01 |
Header Size | 20 bytes minimum | 40 bytes minimum |
Typical Use | Most networks today | Modern/future networks |
Expand for Example Usage
UDPPacket::~UDPPacket | ( | ) |
Destructor - automatically frees pool buffer.
Destructor that automatically releases the UDP packet's pool buffer back to the system memory pool. This implements RAII (Resource Acquisition Is Initialization) principles, ensuring proper cleanup without manual memory management.
Case 1: Buffer never sent
Case 2: Buffer sent with Send()
Case 3: Buffer sent with SendAndKeep()
Case 4: Exception safety
Expand for Example Usage
Operation | Buffer State After | Destructor Action |
---|---|---|
Send() | Freed immediately | None (already freed) |
SendAndKeep() | Retained | Frees on destruction |
No send | Allocated | Frees on destruction |
Receive() only | Allocated | Frees on destruction |
void UDPPacket::AddData | ( | PCSTR | pData | ) |
Add null-terminated string (includes NULL in packet)
Appends a null-terminated string to the packet, including the terminating NULL character. This is convenient for string-based protocols where the receiver expects NULL-terminated strings.
pData | Pointer to null-terminated string to add |
void UDPPacket::AddData | ( | puint8_t | pData, |
uint16_t | len ) |
Add binary data (auto-updates size - no SetDataSize() needed)
Appends binary data to the packet buffer and automatically updates the internal data size counter. This is the primary method for building packets with structured data.
pData | Pointer to the binary data to add |
len | Number of bytes to copy from pData |
void UDPPacket::AddDataByte | ( | uint8_t | b | ) |
Add 8-bit value.
Appends a single byte to the packet. Useful for adding flags, command codes, or single-byte values to packet data.
b | 8-bit value to add (0-255) |
void UDPPacket::AddDataWord | ( | uint16_t | w | ) |
Add 16-bit value.
Appends a 16-bit word to the packet in network byte order (big-endian). Useful for adding integer values, ports, or length fields to packets.
w | 16-bit value to add (0-65535) |
|
inline |
Check if packet uses IPv6 addressing.
Determines whether this packet is using IPv6 or IPv4 addressing by checking if the internal IPv6 header pointer is set. Returns true for IPv6 packets, false for IPv4 packets.
Expand for Example Usage
puint8_t UDPPacket::GetDataBuffer | ( | bool | bReAllocateIfNeeded = false | ) |
Get data buffer pointer for reading or writing.
CRITICAL: After writing, MUST call SetDataSize() before sending!
uint16_t UDPPacket::GetDataSize | ( | void | ) | const |
Get current data size in bytes.
Returns the number of bytes currently stored in the packet's data buffer. This reflects the actual data length, not the buffer capacity.
|
inline |
Get destination IP address of the packet.
Returns the destination IP address from the packet header. For received packets, this is YOUR local interface address that received the packet (useful for multi-homed devices). For outgoing packets, this is the target remote address.
For Sent Packets:
uint16_t UDPPacket::GetDestinationPort | ( | void | ) | const |
Get destination port (for received packets: local port that received it)
For outgoing packets, returns the destination port set by SetDestinationPort(). For received packets, returns the LOCAL port that received the packet (i.e., which port on YOUR device the packet was addressed to).
uint8_t UDPPacket::GetDSCP | ( | void | ) | const |
Get DSCP value (0-63)
Returns the Differentiated Services Code Point (DSCP) value from the packet's IP header. DSCP is used for Quality of Service (QoS) classification and traffic prioritization in IP networks.
Value | Name | Description |
---|---|---|
0 | CS0 | Best Effort (default) |
8 | CS1 | Low Priority |
46 | EF | Expedited Forwarding (VoIP) |
34 | AF41 | High Priority Data |
26 | AF31 | Medium Priority Data |
MACADR UDPPacket::GetMacSource | ( | ) |
Get sender's MAC address (link-layer identification)
Returns the source MAC address from the Ethernet frame header. This is the hardware address of the last-hop device that transmitted the packet on the local network segment.
Attribute | MAC Address | IP Address |
---|---|---|
Scope | Local network only | End-to-end (across networks) |
Identity | Last-hop device | Original source device |
Routing | Changes at each router | Remains constant |
Use Case | Link-layer filtering | Application identification |
Expand for Example Usage
uint16_t UDPPacket::GetPacketId | ( | void | ) |
Get IP packet ID (used for fragment reassembly and packet tracking)
Returns the IP packet identification field from the IP header. This value is used by the network stack for IP fragmentation/reassembly and can be used by applications for packet tracking and debugging.
|
inline |
Get source IP address of the packet.
Returns the source IP address from the packet header. For received packets, this is the address of the remote sender. For outgoing packets, this is the local interface address used to send the packet.
uint16_t UDPPacket::GetSourcePort | ( | void | ) | const |
Get source port from received packet or previously set value.
Returns the source port from the packet's UDP header. The meaning depends on whether this is a received packet or one you're preparing to send.
Expand for Example Usage
|
inline |
Reuse packet object for multiple receives (efficiency optimization)
Receives a UDP packet from the specified FIFO queue with a timeout. This function blocks until a packet arrives or the timeout expires. The same packet object can be reused across multiple receives for efficiency (avoids repeated allocation).
pFifo | Pointer to OS_FIFO queue to receive from (created by RegisterUDPFifo()) |
wait_ticks | Maximum time to wait for packet, in system ticks
|
Expand for Example Usage
wait_ticks Value | Behavior | Use Case |
---|---|---|
0 | Non-blocking | Polling, multi-tasking |
TICKS_PER_SECOND / 10 | 100ms | Responsive UI updates |
TICKS_PER_SECOND | 1 second | Typical network timeout |
TICKS_PER_SECOND * 5 | 5 seconds | Slow networks, retries |
0xFFFFFFFF | Forever | Dedicated receive threads |
void UDPPacket::ResetData | ( | void | ) |
Reset data size to 0 (clears packet)
This function resets the packet's data length to zero, effectively clearing the packet contents without deallocating memory. The packet buffer remains allocated and can be reused for new data.
|
inline |
Send and free buffer (recommended - most efficient)
Sends the packet to the specified destination and immediately frees the buffer. This is the standard, most efficient way to send UDP packets. After calling this function, the packet buffer is freed and the UDPPacket object should not be used for sending again (though it can receive new data).
to | Destination IP address (IPv4 or IPv6) |
ttl | Time-to-live value for packet (0 = use default TTL, typically 64)
|
Expand for Example Usage
Method | Memory | Speed | Use When |
---|---|---|---|
Send() | Low | Fast | Single destination |
SendAndKeep() | High | Slower | Multiple destinations |
|
inline |
Send copy, keep original (for sending to multiple destinations)
Sends a copy of the packet to the specified destination while retaining the original buffer for additional sends. This is essential when sending the same packet to multiple destinations. The buffer remains allocated until either Send() is called or the packet is destroyed.
to | Destination IP address (IPv4 or IPv6) |
ttl | Time-to-live value for packet (0 = use default TTL, typically 64)
|
Aspect | Cost | Notes |
---|---|---|
Buffer copy | Medium | Each SendAndKeep() allocates new buffer |
Network I/O | High | N separate transmissions |
Memory | Higher | Temporary buffers until final Send() |
Use when | N is small | Typically < 10 destinations |
TTL | Scope | Use Case |
---|---|---|
0 | System default (usually 64) | Normal operation |
1 | Local subnet only | Link-local communication |
16 | Limited regional | Campus networks |
64 | Internet standard | General Internet traffic |
128 | Extended reach | Cross-continent |
255 | Maximum | Unrestricted (rarely needed) |
|
inline |
Send a packet and retain a copy via a specific interface address.
This inline function wraps SendAndKeepViaIfAddr6() to send a packet to a destination IP address while routing through a specific source interface address. The function retains a copy of the packet after sending (useful for retransmission or logging).
to | Destination IP address for the packet |
from_ip | Source interface IP address to use for routing the packet |
ttl | Time-to-live value for the packet (0 = use default TTL) |
|
inline |
Send copy via specific interface, keep original.
Sends a copy of the packet via a specific network interface while retaining the original buffer. This is essential for multi-homed systems where you need to send the same packet through multiple network interfaces or send to multiple destinations via specific interfaces.
to | Destination IP address (IPv4 or IPv6) |
interface | Network interface number (0=first interface, 1=second, etc.)
|
ttl | Time-to-live value for packet (0 = use default TTL)
|
Expand for Example Usage
Scenario | Interface Selection | Reason |
---|---|---|
Primary data | Interface 0 | Main network connection |
Management | Interface 1 | Isolated management network |
Testing | Iterate all | Verify all paths working |
Redundancy | Multiple | Ensure delivery via any path |
Load balancing | Round-robin | Distribute traffic |
Aspect | Impact | Notes |
---|---|---|
Buffer copy | Medium | Each call allocates new buffer |
Network I/O | High | N separate transmissions |
Interface overhead | Low | Just routing decision |
Memory | Higher | Temporary buffers until final send |
Send a packet via a specific interface address.
This inline function sends a packet to a destination IP address while routing through a specific source interface address. Unlike SendAndKeepViaIfAddr(), this function does not retain a copy of the packet after transmission.
to | Destination IP address for the packet |
from_ip | Source interface IP address to use for routing the packet |
ttl | Time-to-live value for the packet (0 = use default TTL) |
|
inline |
Send via specific interface and free buffer.
Sends the packet via a specific network interface and immediately frees the buffer. This is the standard way to send a packet through a specific interface in multi-homed systems. The buffer is freed after sending, making this the most memory-efficient option for single-interface sends.
to | Destination IP address (IPv4 or IPv6) |
interface | Network interface number (0=first interface, 1=second, etc.)
|
ttl | Time-to-live value for packet (0 = use default TTL)
|
Expand for Example Usage
System Type | Interface 0 | Interface 1 | Use Case |
---|---|---|---|
Dual Ethernet | Production | Management | Network segregation |
Ethernet + WiFi | Wired | Wireless | Redundant connectivity |
Multi-port router | LAN | WAN | Traffic direction |
Industrial system | Control | Data | Real-time vs bulk |
Method | Memory | Speed | Complexity | Use When |
---|---|---|---|---|
SendViaInterfaceNum() | Low | Fast | Low | Single interface |
SendAndKeepViaIfNum() | High | Slower | Medium | Multiple interfaces |
Send() (any interface) | Low | Fastest | Lowest | Don't care which interface |
void UDPPacket::SetDataSize | ( | uint16_t | numBytes | ) |
Set data size (REQUIRED after GetDataBuffer() writes)
Maximum ~1472 bytes for standard Ethernet. Larger needs fragmentation.
void UDPPacket::SetDestinationPort | ( | uint16_t | port | ) |
Set destination port (standard services: 53=DNS, 80=HTTP, 123=NTP, 161=SNMP)
Sets the destination UDP port for outgoing packets. The port identifies which service or application on the remote host should receive the packet.
port | Destination port number (1-65535)
|
Port | Service | Description |
---|---|---|
53 | DNS | Domain Name System |
67/68 | DHCP | Dynamic Host Configuration |
80 | HTTP | Web Server |
123 | NTP | Network Time Protocol |
161 | SNMP | Simple Network Management |
443 | HTTPS | Secure Web Server |
1883 | MQTT | Message Queue Telemetry |
5353 | mDNS | Multicast DNS |
void UDPPacket::SetDSCP | ( | uint8_t | dscp | ) |
Set DSCP for QoS (0=best effort, 46=VoIP/EF, 34=video/AF41, 8=bulk/CS1)
Standard DSCP values (RFC 4594):
void UDPPacket::SetSourcePort | ( | uint16_t | port | ) |
Set source port (0=auto-assign ephemeral port, 1024-65535=specific port)
Sets the source UDP port for outgoing packets. The source port identifies which local port the packet originates from and where replies should be sent.
port | Source port number:
|
Application Type | Recommended Port | Reason |
---|---|---|
UDP Server | Fixed port (e.g., 5000) | Clients need to know where to send |
UDP Client | 0 (auto-assign) | Don't care which local port is used |
Peer-to-Peer | Fixed port | Both sides need predictable ports |
Reply Packet | Use 0 or leave default | Stack handles reply routing |
Clients use AUTO-ASSIGNED ports:
Expand for Example Usage
BOOL UDPPacket::Validate | ( | void | ) |
Validate received packet (checks checksum and data presence)
ALWAYS call after receiving packet!
This function performs integrity checks on a received packet to ensure: