Core API Reference

This section documents the core MafiaNet classes.

RakPeerInterface

The main entry point for all networking operations.

class RakPeerInterface

The main interface for network communications.

The primary interface for RakNet, RakPeer contains all major functions for the library. See the individual functions for what the class can do.

Subclassed by MafiaNet::RakPeer

Public Functions

inline virtual ~RakPeerInterface()

Destructor.

virtual StartupResult Startup(unsigned int maxConnections, SocketDescriptor *socketDescriptors, unsigned socketDescriptorCount, int threadPriority = -99999) = 0

Starts the network threads, opens the listen port.

You must call this before calling Connect().

Note

Call SetMaximumIncomingConnections if you want to accept incoming connections

Parameters:
  • maxConnections[in] The maximum number of connections between this instance of RakPeer and another instance of RakPeer. Required so the network can preallocate and for thread safety. A pure client would set this to 1. A pure server would set it to the number of allowed clients.- A hybrid would set it to the sum of both types of connections

  • localPort[in] The port to listen for connections on. On linux the system may be set up so thast ports under 1024 are restricted for everything but the root user. Use a higher port for maximum compatibility.

  • socketDescriptors[in] An array of SocketDescriptor structures to force RakNet to listen on a particular IP address or port (or both). Each SocketDescriptor will represent one unique socket. Do not pass redundant structures. To listen on a specific port, you can pass SocketDescriptor(myPort,0); such as for a server. For a client, it is usually OK to just pass SocketDescriptor(); However, on the XBOX be sure to use IPPROTO_VDP

  • socketDescriptorCount[in] The size of the socketDescriptors array. Pass 1 if you are not sure what to pass.

  • threadPriority[in] Passed to the thread creation routine. Use THREAD_PRIORITY_NORMAL for Windows. For Linux based systems, you MUST pass something reasonable based on the thread priorities for your application.

Pre:

On the PS3, call Startup() after Client_Login()

Pre:

On Android, add the necessary permission to your application’s androidmanifest.xml: <uses-permission android:name=”android.permission.INTERNET” /> Multiple calls while already active are ignored. To call this function again with different settings, you must first call Shutdown().

Returns:

RAKNET_STARTED on success, otherwise appropriate failure enumeration.

virtual bool InitializeSecurity(const char *publicKey, const char *privateKey, bool bRequireClientKey = false) = 0

If you accept connections, you must call this or else security will not be enabled for incoming connections. This feature requires more round trips, bandwidth, and CPU time for the connection handshake x64 builds require under 25% of the CPU time of other builds See the Encryption sample for example usage

Parameters:
  • publicKey[in] A pointer to the public key for accepting new connections

  • privateKey[in] A pointer to the private key for accepting new connections

  • bRequireClientKey[in] Should be set to false for most servers. Allows the server to accept a public key from connecting clients as a proof of identity but eats twice as much CPU time as a normal connection

Pre:

Must be called while offline

Pre:

LIBCAT_SECURITY must be defined to 1 in NativeFeatureIncludes.h for this function to have any effect

virtual void DisableSecurity(void) = 0

Disables security for incoming connections.

Note

Must be called while offline

virtual void AddToSecurityExceptionList(const char *ip) = 0

If secure connections are on, do not use secure connections for a specific IP address. This is useful if you have a fixed-address internal server behind a LAN.

Note

Secure connections are determined by the recipient of an incoming connection. This has no effect if called on the system attempting to connect.

Parameters:

ip[in] IP address to add. * wildcards are supported.

virtual void RemoveFromSecurityExceptionList(const char *ip) = 0

Remove a specific connection previously added via AddToSecurityExceptionList

Parameters:

ip[in] IP address to remove. Pass 0 to remove all IP addresses. * wildcards are supported.

virtual bool IsInSecurityExceptionList(const char *ip) = 0

Checks to see if a given IP is in the security exception list

Parameters:

IP[in] address to check.

virtual void SetMaximumIncomingConnections(unsigned short numberAllowed) = 0

Sets how many incoming connections are allowed. If this is less than the number of players currently connected, no more players will be allowed to connect. If this is greater than the maximum number of peers allowed, it will be reduced to the maximum number of peers allowed. Defaults to 0, meaning by default, nobody can connect to you

Parameters:

numberAllowed[in] Maximum number of incoming connections allowed.

virtual unsigned int GetMaximumIncomingConnections(void) const = 0

Returns the value passed to SetMaximumIncomingConnections()

Returns:

the maximum number of incoming connections, which is always <= maxConnections

virtual unsigned short NumberOfConnections(void) const = 0

Returns how many open connections there are at this time

Returns:

the number of open connections

virtual void SetIncomingPassword(const char *passwordData, int passwordDataLength) = 0

Sets the password incoming connections must match in the call to Connect (defaults to none). Pass 0 to passwordData to specify no password This is a way to set a low level password for all incoming connections. To selectively reject connections, implement your own scheme using CloseConnection() to remove unwanted connections

Parameters:
  • passwordData[in] A data block that incoming connections must match. This can be just a password, or can be a stream of data. Specify 0 for no password data

  • passwordDataLength[in] The length in bytes of passwordData

virtual void GetIncomingPassword(char *passwordData, int *passwordDataLength) = 0

Gets the password passed to SetIncomingPassword

Parameters:
  • passwordData[out] Should point to a block large enough to hold the password data you passed to SetIncomingPassword()

  • passwordDataLength[inout] Maximum size of the array passwordData. Modified to hold the number of bytes actually written

virtual ConnectionAttemptResult Connect(const char *host, unsigned short remotePort, const char *passwordData, int passwordDataLength, PublicKey *publicKey = 0, unsigned connectionSocketIndex = 0, unsigned sendConnectionAttemptCount = 12, unsigned timeBetweenSendConnectionAttemptsMS = 500, MafiaNet::TimeMS timeoutTime = 0) = 0

Connect to the specified host (ip or domain name) and server port. Calling Connect and not calling SetMaximumIncomingConnections acts as a dedicated client. Calling both acts as a true peer. This is a non-blocking connection. You know the connection is successful when GetConnectionState() returns IS_CONNECTED or Receive() gets a message with the type identifier ID_CONNECTION_REQUEST_ACCEPTED. If the connection is not successful, such as a rejected connection or no response then neither of these things will happen.

Note

CONNECTION_ATTEMPT_STARTED does not mean you are already connected!

Note

It is possible to immediately get back ID_CONNECTION_ATTEMPT_FAILED if you exceed the maxConnections parameter passed to Startup(). This could happen if you call CloseConnection() with sendDisconnectionNotificaiton true, then immediately call Connect() before the connection has closed.

Parameters:
  • host[in] Either a dotted IP address or a domain name

  • remotePort[in] Which port to connect to on the remote machine.

  • passwordData[in] A data block that must match the data block on the server passed to SetIncomingPassword. This can be a string or can be a stream of data. Use 0 for no password.

  • passwordDataLength[in] The length in bytes of passwordData

  • publicKey[in] The public key the server is using. If 0, the server is not using security. If non-zero, the publicKeyMode member determines how to connect

  • connectionSocketIndex[in] Index into the array of socket descriptors passed to socketDescriptors in RakPeer::Startup() to send on.

  • sendConnectionAttemptCount[in] How many datagrams to send to the other system to try to connect.

  • timeBetweenSendConnectionAttemptsMS[in] Time to elapse before a datagram is sent to the other system to try to connect. After sendConnectionAttemptCount number of attempts, ID_CONNECTION_ATTEMPT_FAILED is returned. Under low bandwidth conditions with multiple simultaneous outgoing connections, this value should be raised to 1000 or higher, or else the MTU detection can overrun the available bandwidth.

  • timeoutTime[in] How long to keep the connection alive before dropping it on unable to send a reliable message. 0 to use the default from SetTimeoutTime(UNASSIGNED_SYSTEM_ADDRESS);

Pre:

Requires that you first call Startup()

Returns:

CONNECTION_ATTEMPT_STARTED on successful initiation. Otherwise, an appropriate enumeration indicating failure.

virtual ConnectionAttemptResult ConnectWithSocket(const char *host, unsigned short remotePort, const char *passwordData, int passwordDataLength, RakNetSocket2 *socket, PublicKey *publicKey = 0, unsigned sendConnectionAttemptCount = 12, unsigned timeBetweenSendConnectionAttemptsMS = 500, MafiaNet::TimeMS timeoutTime = 0) = 0

Connect to the specified host (ip or domain name) and server port, using a shared socket from another instance of RakNet.

Note

CONNECTION_ATTEMPT_STARTED does not mean you are already connected!

Parameters:
  • host[in] Either a dotted IP address or a domain name

  • remotePort[in] Which port to connect to on the remote machine.

  • passwordData[in] A data block that must match the data block on the server passed to SetIncomingPassword. This can be a string or can be a stream of data. Use 0 for no password.

  • passwordDataLength[in] The length in bytes of passwordData

  • socket[in] A bound socket returned by another instance of RakPeerInterface

  • sendConnectionAttemptCount[in] How many datagrams to send to the other system to try to connect.

  • timeBetweenSendConnectionAttemptsMS[in] Time to elapse before a datagram is sent to the other system to try to connect. After sendConnectionAttemptCount number of attempts, ID_CONNECTION_ATTEMPT_FAILED is returned. Under low bandwidth conditions with multiple simultaneous outgoing connections, this value should be raised to 1000 or higher, or else the MTU detection can overrun the available bandwidth.

  • timeoutTime[in] How long to keep the connection alive before dropping it on unable to send a reliable message. 0 to use the default from SetTimeoutTime(UNASSIGNED_SYSTEM_ADDRESS);

Returns:

CONNECTION_ATTEMPT_STARTED on successful initiation. Otherwise, an appropriate enumeration indicating failure.

virtual void Shutdown(unsigned int blockDuration, unsigned char orderingChannel = 0, MafiaNet::Priority disconnectionNotificationPriority = MafiaNet::Priority::Low) = 0

Connect to the specified network ID (Platform specific console function)

Does built-in NAt traversal

Stops the network threads and closes all connections.

Parameters:
  • passwordData[in] A data block that must match the data block on the server passed to SetIncomingPassword. This can be a string or can be a stream of data. Use 0 for no password.

  • passwordDataLength[in] The length in bytes of passwordData

  • blockDuration[in] How long, in milliseconds, you should wait for all remaining messages to go out, including ID_DISCONNECTION_NOTIFICATION. If 0, it doesn’t wait at all.

  • orderingChannel[in] If blockDuration > 0, ID_DISCONNECTION_NOTIFICATION will be sent on this channel

  • disconnectionNotificationPriority[in] Priority at which ID_DISCONNECTION_NOTIFICATION is sent. Note that a blockDuration of 0 means the threads stop without waiting for it to flush.

virtual bool IsActive(void) const = 0

Returns if the network thread is running

Returns:

true if the network thread is running, false otherwise

virtual bool GetConnectionList(SystemAddress *remoteSystems, unsigned short *numberOfSystems) const = 0

Fills the array remoteSystems with the SystemAddress of all the systems we are connected to

Parameters:
  • remoteSystems[out] An array of SystemAddress structures to be filled with the SystemAddresss of the systems we are connected to. Pass 0 to remoteSystems to only get the number of systems we are connected to

  • numberOfSystems[inout] As input, the size of remoteSystems array. As output, the number of elements put into the array

virtual uint32_t GetNextSendReceipt(void) = 0

Returns the next uint32_t that Send() will return

Note

If using RakPeer from multiple threads, this may not be accurate for your thread. Use IncrementNextSendReceipt() in that case.

Returns:

The next uint32_t that Send() or SendList will return

virtual uint32_t IncrementNextSendReceipt(void) = 0

Returns the next uint32_t that Send() will return, and increments the value by one

Note

If using RakPeer from multiple threads, pass this to forceReceipt in the send function

Returns:

The next uint32_t that Send() or SendList will return

virtual uint32_t Send(const char *data, const int length, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, uint32_t forceReceiptNumber = 0) = 0

Sends a block of data to the specified system that you are connected to. This function only works while connected The first byte should be a message identifier starting at ID_USER_PACKET_ENUM

Parameters:
  • data[in] The block of data to send

  • length[in] The size in bytes of the data to send

  • priority[in] What priority level to send on. See PacketPriority.h

  • reliability[in] How reliability to send this data. See PacketPriority.h

  • orderingChannel[in] When using ordered or sequenced messages, what channel to order these on. Messages are only ordered relative to other messages on the same stream

  • systemIdentifier[in] Who to send this packet to, or in the case of broadcasting who not to send it to. Pass either a SystemAddress structure or a RakNetGUID structure. Use UNASSIGNED_SYSTEM_ADDRESS or to specify none

  • broadcast[in] True to send this packet to all connected systems. If true, then systemAddress specifies who not to send the packet to.

  • forceReceipt[in] If 0, will automatically determine the receipt number to return. If non-zero, will return what you give it.

Returns:

0 on bad input. Otherwise a number that identifies this message. If reliability is a type that returns a receipt, on a later call to Receive() you will get ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS with bytes 1-4 inclusive containing this number

virtual void SendLoopback(const char *data, const int length) = 0

“Send” to yourself rather than a remote system. The message will be processed through the plugins and returned to the game as usual This function works anytime The first byte should be a message identifier starting at ID_USER_PACKET_ENUM

Parameters:
  • data[in] The block of data to send

  • length[in] The size in bytes of the data to send

virtual uint32_t Send(const MafiaNet::BitStream *bitStream, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, uint32_t forceReceiptNumber = 0) = 0

Sends a block of data to the specified system that you are connected to. Same as the above version, but takes a BitStream as input.

Note

COMMON MISTAKE: When writing the first byte, bitStream->Write((unsigned char) ID_MY_TYPE) be sure it is casted to a byte, and you are not writing a 4 byte enumeration.

Parameters:
  • bitStream[in] The bitstream to send

  • priority[in] What priority level to send on. See PacketPriority.h

  • reliability[in] How reliability to send this data. See PacketPriority.h

  • orderingChannel[in] When using ordered or sequenced messages, what channel to order these on. Messages are only ordered relative to other messages on the same stream

  • systemIdentifier[in] Who to send this packet to, or in the case of broadcasting who not to send it to. Pass either a SystemAddress structure or a RakNetGUID structure. Use UNASSIGNED_SYSTEM_ADDRESS or to specify none

  • broadcast[in] True to send this packet to all connected systems. If true, then systemAddress specifies who not to send the packet to.

  • forceReceipt[in] If 0, will automatically determine the receipt number to return. If non-zero, will return what you give it.

Returns:

0 on bad input. Otherwise a number that identifies this message. If reliability is a type that returns a receipt, on a later call to Receive() you will get ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS with bytes 1-4 inclusive containing this number

virtual uint32_t SendList(const char **data, const int *lengths, const int numParameters, MafiaNet::Priority priority, MafiaNet::Reliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, uint32_t forceReceiptNumber = 0) = 0

Sends multiple blocks of data, concatenating them automatically.

This is equivalent to: MafiaNet::BitStream bs; bs.WriteAlignedBytes(block1, blockLength1); bs.WriteAlignedBytes(block2, blockLength2); bs.WriteAlignedBytes(block3, blockLength3); Send(&bs, …)

This function only works while connected

Parameters:
  • data[in] An array of pointers to blocks of data

  • lengths[in] An array of integers indicating the length of each block of data

  • numParameters[in] Length of the arrays data and lengths

  • priority[in] What priority level to send on. See PacketPriority.h

  • reliability[in] How reliability to send this data. See PacketPriority.h

  • orderingChannel[in] When using ordered or sequenced messages, what channel to order these on. Messages are only ordered relative to other messages on the same stream

  • systemIdentifier[in] Who to send this packet to, or in the case of broadcasting who not to send it to. Pass either a SystemAddress structure or a RakNetGUID structure. Use UNASSIGNED_SYSTEM_ADDRESS or to specify none

  • broadcast[in] True to send this packet to all connected systems. If true, then systemAddress specifies who not to send the packet to.

  • forceReceipt[in] If 0, will automatically determine the receipt number to return. If non-zero, will return what you give it.

Returns:

0 on bad input. Otherwise a number that identifies this message. If reliability is a type that returns a receipt, on a later call to Receive() you will get ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS with bytes 1-4 inclusive containing this number

virtual Packet *Receive(void) = 0

Gets a message from the incoming message queue. Use DeallocatePacket() to deallocate the message after you are done with it. User-thread functions, such as RPC calls and the plugin function PluginInterface::Update occur here.

Note

COMMON MISTAKE: Be sure to call this in a loop, once per game tick, until it returns 0. If you only process one packet per game tick they will buffer up. sa types.h contains struct Packet

Returns:

0 if no packets are waiting to be handled, otherwise a pointer to a packet.

virtual void DeallocatePacket(Packet *packet) = 0

Call this to deallocate a message returned by Receive() when you are done handling it.

Parameters:

packet[in] The message to deallocate.

virtual unsigned int GetMaximumNumberOfPeers(void) const = 0

Return the total number of connections we are allowed.

virtual void CloseConnection(const AddressOrGUID target, bool sendDisconnectionNotification, unsigned char orderingChannel = 0, MafiaNet::Priority disconnectionNotificationPriority = MafiaNet::Priority::Low, const MafiaNet::BitStream *reasonData = nullptr) = 0

Close the connection to another host (if we initiated the connection it will disconnect, if they did it will kick them out).

Parameters:
  • target[in] Which system to close the connection to.

  • sendDisconnectionNotification[in] True to send ID_DISCONNECTION_NOTIFICATION to the recipient. False to close it silently.

  • channel[in] Which ordering channel to send the disconnection notification on, if any

  • disconnectionNotificationPriority[in] Priority to send ID_DISCONNECTION_NOTIFICATION on.

  • reasonData[in] Optional payload appended after the ID_DISCONNECTION_NOTIFICATION message ID so the remote peer can learn why it was dropped (e.g. an enum + custom string). The receiver reads it from packet->data+1 (length packet->length-1), exactly like any other message body. Only graceful disconnects (sendDisconnectionNotification==true) carry a reason; locally-synthesized notifications (ID_CONNECTION_LOST and timeout/dead-connection paths) stay payload-less, so consumers must tolerate a zero-length body. Pass nullptr (the default) for no reason. Appending bytes after the 1-byte ID is wire-backward-compatible: peers that only read data[0] are unaffected.

virtual ConnectionState GetConnectionState(const AddressOrGUID systemIdentifier) = 0

Returns if a system is connected, disconnected, connecting in progress, or various other states

Note

This locks a mutex, do not call too frequently during connection attempts or the attempt will take longer and possibly even timeout

Parameters:

systemIdentifier[in] The system we are referring to

Returns:

What state the remote system is in

virtual void CancelConnectionAttempt(const SystemAddress target) = 0

Cancel a pending connection attempt If we are already connected, the connection stays open

Parameters:

target[in] Which system to cancel

virtual int GetIndexFromSystemAddress(const SystemAddress systemAddress) const = 0

Given a systemAddress, returns an index from 0 to the maximum number of players allowed - 1.

Parameters:

systemAddress[in] The SystemAddress we are referring to

Returns:

The index of this SystemAddress or -1 on system not found.

virtual SystemAddress GetSystemAddressFromIndex(unsigned int index) = 0

This function is only useful for looping through all systems Given an index, will return a SystemAddress.

Parameters:

index[in] Index should range between 0 and the maximum number of players allowed - 1.

Returns:

The SystemAddress

virtual RakNetGUID GetGUIDFromIndex(unsigned int index) = 0

Same as GetSystemAddressFromIndex but returns RakNetGUID

Parameters:

index[in] Index should range between 0 and the maximum number of players allowed - 1.

Returns:

The RakNetGUID

virtual void GetSystemList(DataStructures::List<SystemAddress> &addresses, DataStructures::List<RakNetGUID> &guids) const = 0

Same as calling GetSystemAddressFromIndex and GetGUIDFromIndex for all systems, but more efficient Indices match each other, so addresses[0] and guids[0] refer to the same system

Parameters:
  • addresses[out] All system addresses. Size of the list is the number of connections. Size of the list will match the size of the guids list.

  • guids[out] All guids. Size of the list is the number of connections. Size of the list will match the size of the addresses list.

virtual void AddToBanList(const char *IP, MafiaNet::TimeMS milliseconds = 0) = 0

Bans an IP from connecting. Banned IPs persist between connections but are not saved on shutdown nor loaded on startup. param[in] IP Dotted IP address. Can use * as a wildcard, such as 128.0.0.* will ban all IP addresses starting with 128.0.0

Parameters:

milliseconds[in] how many ms for a temporary ban. Use 0 for a permanent ban

virtual void RemoveFromBanList(const char *IP) = 0

Allows a previously banned IP to connect. param[in] Dotted IP address. Can use * as a wildcard, such as 128.0.0.* will banAll IP addresses starting with 128.0.0

virtual void ClearBanList(void) = 0

Allows all previously banned IPs to connect.

virtual bool IsBanned(const char *IP) = 0

Returns true or false indicating if a particular IP is banned.

Parameters:

IP[in] - Dotted IP address.

Returns:

true if IP matches any IPs in the ban list, accounting for any wildcards. False otherwise.

virtual void SetLimitIPConnectionFrequency(bool b) = 0

Enable or disable allowing frequent connections from the same IP adderss This is a security measure which is disabled by default, but can be set to true to prevent attackers from using up all connection slots

Parameters:

b[in] True to limit connections from the same ip to at most 1 per 100 milliseconds.

virtual void Ping(const SystemAddress target) = 0

Send a ping to the specified connected system.

Parameters:

target[in] Which system to ping

Pre:

The sender and recipient must already be started via a successful call to Startup()

virtual bool Ping(const char *host, unsigned short remotePort, bool onlyReplyOnAcceptingConnections, unsigned connectionSocketIndex = 0) = 0

Send a ping to the specified unconnected system. The remote system, if it is Initialized, will respond with ID_PONG followed by sizeof(MafiaNet::TimeMS) containing the system time the ping was sent.(Default is 4 bytes - See __GET_TIME_64BIT in types.h System should reply with ID_PONG if it is active

Parameters:
  • host[in] Either a dotted IP address or a domain name. Can be 255.255.255.255 for LAN broadcast.

  • remotePort[in] Which port to connect to on the remote machine.

  • onlyReplyOnAcceptingConnections[in] Only request a reply if the remote system is accepting connections

  • connectionSocketIndex[in] Index into the array of socket descriptors passed to socketDescriptors in RakPeer::Startup() to send on.

Returns:

true on success, false on failure (unknown hostname)

virtual int GetAveragePing(const AddressOrGUID systemIdentifier) = 0

Returns the average of all ping times read for the specific system or -1 if none read yet

Parameters:

systemAddress[in] Which system we are referring to

Returns:

The ping time for this system, or -1

virtual int GetLastPing(const AddressOrGUID systemIdentifier) const = 0

Returns the last ping time read for the specific system or -1 if none read yet

Parameters:

systemAddress[in] Which system we are referring to

Returns:

The last ping time for this system, or -1

virtual int GetLowestPing(const AddressOrGUID systemIdentifier) const = 0

Returns the lowest ping time read or -1 if none read yet

Parameters:

systemAddress[in] Which system we are referring to

Returns:

The lowest ping time for this system, or -1

virtual void SetOccasionalPing(bool doPing) = 0

Ping the remote systems every so often, or not. Can be called anytime. By default this is true. Recommended to leave on, because congestion control uses it to determine how often to resend lost packets. It would be true by default to prevent timestamp drift, since in the event of a clock spike, the timestamp deltas would no longer be accurate

Parameters:

doPing[in] True to start occasional pings. False to stop them.

virtual MafiaNet::Time GetClockDifferential(const AddressOrGUID systemIdentifier) = 0

Return the clock difference between your system and the specified system Subtract GetClockDifferential() from a time returned by the remote system to get that time relative to your own system Returns 0 if the system is unknown

Parameters:

systemIdentifier[in] Which system we are referring to

virtual void SetOfflinePingResponse(const char *data, const unsigned int length) = 0

Sets the data to send along with a LAN server discovery or offline ping reply. length should be under 400 bytes, as a security measure against flood attacks

See also

Ping.cpp

Parameters:
  • data[in] a block of data to store, or 0 for none

  • length[in] The length of data in bytes, or 0 for none

virtual void GetOfflinePingResponse(char **data, unsigned int *length) = 0

Returns pointers to a copy of the data passed to SetOfflinePingResponse

Parameters:
virtual SystemAddress GetInternalID(const SystemAddress systemAddress = UNASSIGNED_SYSTEM_ADDRESS, const int index = 0) const = 0

Return the unique address identifier that represents you or another system on the the network and is based on your local IP / port.

Note

Not supported by the XBOX

Parameters:
  • systemAddress[in] Use UNASSIGNED_SYSTEM_ADDRESS to get your behind-LAN address. Use a connected system to get their behind-LAN address

  • index[in] When you have multiple internal IDs, which index to return? Currently limited to MAXIMUM_NUMBER_OF_INTERNAL_IDS (so the maximum value of this variable is MAXIMUM_NUMBER_OF_INTERNAL_IDS-1)

Returns:

the identifier of your system internally, which may not be how other systems see if you if you are behind a NAT or proxy

virtual void SetInternalID(SystemAddress systemAddress, int index = 0) = 0

Sets your internal IP address, for platforms that do not support reading it, or to override a value.

Parameters:
  • systemAddress.[in] The address to set. Use SystemAddress::FromString() if you want to use a dotted string

  • index[in] When you have multiple internal IDs, which index to set?

virtual SystemAddress GetExternalID(const SystemAddress target) const = 0

Return the unique address identifier that represents you on the the network and is based on your externalIP / port (the IP / port the specified player uses to communicate with you)

Parameters:

target[in] Which remote system you are referring to for your external ID. Usually the same for all systems, unless you have two or more network cards.

virtual const RakNetGUID GetMyGUID(void) const = 0

Return my own GUID.

virtual SystemAddress GetMyBoundAddress(const int socketIndex = 0) = 0

Return the address bound to a socket at the specified index.

virtual const RakNetGUID &GetGuidFromSystemAddress(const SystemAddress input) const = 0

Given a connected system, give us the unique GUID representing that instance of RakPeer. This will be the same on all systems connected to that instance of RakPeer, even if the external system addresses are different Currently O(log(n)), but this may be improved in the future. If you use this frequently, you may want to cache the value as it won’t change. Returns UNASSIGNED_RAKNET_GUID if system address can’t be found. If input is UNASSIGNED_SYSTEM_ADDRESS, will return your own GUID

Parameters:

input[in] The system address of the system we are connected to

Pre:

Call Startup() first, or the function will return UNASSIGNED_RAKNET_GUID

virtual SystemAddress GetSystemAddressFromGuid(const RakNetGUID input) const = 0

Given the GUID of a connected system, give us the system address of that system. The GUID will be the same on all systems connected to that instance of RakPeer, even if the external system addresses are different Currently O(log(n)), but this may be improved in the future. If you use this frequently, you may want to cache the value as it won’t change. If input is UNASSIGNED_RAKNET_GUID, will return UNASSIGNED_SYSTEM_ADDRESS

Parameters:

input[in] The RakNetGUID of the system we are checking to see if we are connected to

virtual bool GetClientPublicKeyFromSystemAddress(const SystemAddress input, char *client_public_key) const = 0

Given the SystemAddress of a connected system, get the public key they provided as an identity Returns false if system address was not found or client public key is not known

Parameters:
  • input[in] The RakNetGUID of the system

  • client_public_key[in] The connected client’s public key is copied to this address. Buffer must be cat::EasyHandshake::PUBLIC_KEY_BYTES bytes in length.

virtual void SetTimeoutTime(MafiaNet::TimeMS timeMS, const SystemAddress target) = 0

Set the time, in MS, to use before considering ourselves disconnected after not being able to deliver a reliable message. Default time is 10,000 or 10 seconds in release and 30,000 or 30 seconds in debug. Do not set different values for different computers that are connected to each other, or you won’t be able to reconnect after ID_CONNECTION_LOST

Parameters:
  • timeMS[in] Time, in MS

  • target[in] Which system to do this for. Pass UNASSIGNED_SYSTEM_ADDRESS for all systems.

virtual MafiaNet::TimeMS GetTimeoutTime(const SystemAddress target) = 0
Parameters:

target[in] Which system to do this for. Pass UNASSIGNED_SYSTEM_ADDRESS to get the default value

Returns:

timeoutTime for a given system.

virtual int GetMTUSize(const SystemAddress target) const = 0

Returns the current MTU size

Parameters:

target[in] Which system to get this for. UNASSIGNED_SYSTEM_ADDRESS to get the default

Returns:

The current MTU size

virtual unsigned GetNumberOfAddresses(void) = 0

Returns the number of IP addresses this system has internally. Get the actual addresses from GetLocalIP()

virtual const char *GetLocalIP(unsigned int index) = 0

Returns an IP address at index 0 to GetNumberOfAddresses-1

Parameters:

index[in] index into the list of IP addresses

Returns:

The local IP address at this index

virtual bool IsLocalIP(const char *ip) = 0

Is this a local IP?

Parameters:

An[in] IP address to check, excluding the port

Returns:

True if this is one of the IP addresses returned by GetLocalIP

virtual void AllowConnectionResponseIPMigration(bool allow) = 0

Allow or disallow connection responses from any IP. Normally this should be false, but may be necessary when connecting to servers with multiple IP addresses.

Parameters:

allow[in] - True to allow this behavior, false to not allow. Defaults to false. Value persists between connections

virtual bool AdvertiseSystem(const char *host, unsigned short remotePort, const char *data, int dataLength, unsigned connectionSocketIndex = 0) = 0

Sends a one byte message ID_ADVERTISE_SYSTEM to the remote unconnected system. This will tell the remote system our external IP outside the LAN along with some user data.

Parameters:
  • host[in] Either a dotted IP address or a domain name

  • remotePort[in] Which port to connect to on the remote machine.

  • data[in] Optional data to append to the packet.

  • dataLength[in] length of data in bytes. Use 0 if no data.

  • connectionSocketIndex[in] Index into the array of socket descriptors passed to socketDescriptors in RakPeer::Startup() to send on.

Pre:

The sender and recipient must already be started via a successful call to Initialize

Returns:

false if IsActive()==false or the host is unresolvable. True otherwise

virtual void SetSplitMessageProgressInterval(int interval) = 0

Controls how often to return ID_DOWNLOAD_PROGRESS for large message downloads. ID_DOWNLOAD_PROGRESS is returned to indicate a new partial message chunk, roughly the MTU size, has arrived As it can be slow or cumbersome to get this notification for every chunk, you can set the interval at which it is returned. Defaults to 0 (never return this notification)

Parameters:

interval[in] How many messages to use as an interval

virtual int GetSplitMessageProgressInterval(void) const = 0

Returns what was passed to SetSplitMessageProgressInterval()

Returns:

What was passed to SetSplitMessageProgressInterval(). Default to 0.

virtual void SetUnreliableTimeout(MafiaNet::TimeMS timeoutMS) = 0

Set how long to wait before giving up on sending an unreliable message Useful if the network is clogged up. Set to 0 or less to never timeout. Defaults to 0.

Parameters:

timeoutMS[in] How many ms to wait before simply not sending an unreliable message.

virtual void SendTTL(const char *host, unsigned short remotePort, int ttl, unsigned connectionSocketIndex = 0) = 0

Send a message to host, with the IP socket option TTL set to 3 This message will not reach the host, but will open the router. Used for NAT-Punchthrough

virtual void AttachPlugin(PluginInterface2 *plugin) = 0

Attaches a Plugin interface to an instance of the base class (RakPeer or PacketizedTCP) to run code automatically on message receipt in the Receive call. If the plugin returns false from PluginInterface::UsesReliabilityLayer(), which is the case for all plugins except PacketLogger, you can call AttachPlugin() and DetachPlugin() for this plugin while RakPeer is active.

Parameters:

messageHandler[in] Pointer to the plugin to attach.

virtual void DetachPlugin(PluginInterface2 *messageHandler) = 0

Detaches a Plugin interface from the instance of the base class (RakPeer or PacketizedTCP) it is attached to.

This method disables the plugin code from running automatically on base class’s updates or message receipt. If the plugin returns false from PluginInterface::UsesReliabilityLayer(), which is the case for all plugins except PacketLogger, you can call AttachPlugin() and DetachPlugin() for this plugin while RakPeer is active.

Parameters:

messageHandler[in] Pointer to a plugin to detach.

virtual void PushBackPacket(Packet *packet, bool pushAtHead) = 0

Put a message back at the end of the receive queue in case you don’t want to deal with it immediately

Parameters:
  • packet[in] The packet you want to push back.

  • pushAtHead[in] True to push the packet so that the next receive call returns it. False to push it at the end of the queue (obviously pushing it at the end makes the packets out of order)

virtual void ChangeSystemAddress(RakNetGUID guid, const SystemAddress &systemAddress) = 0
virtual Packet *AllocatePacket(unsigned dataSize) = 0
Parameters:

dataSize[in] How many bytes to allocate for the buffer

Returns:

a packet for you to write to if you want to create a Packet for some reason. You can add it to the receive buffer with PushBackPacket

Returns:

A packet you can write to

virtual RakNetSocket2 *GetSocket(const SystemAddress target) = 0

Get the socket used with a particular active connection The smart pointer reference counts the RakNetSocket2 object, so the socket will remain active as long as the smart pointer does, even if RakNet were to shutdown or close the connection.

Note

This sends a query to the thread and blocks on the return value for up to one second. In practice it should only take a millisecond or so.

Parameters:

target[in] Which system

Returns:

A smart pointer object containing the socket information about the socket. Be sure to check IsNull() which is returned if the update thread is unresponsive, shutting down, or if this system is not connected

virtual void GetSockets(DataStructures::List<RakNetSocket2*> &sockets) = 0

Get all sockets in use

Note

This sends a query to the thread and blocks on the return value for up to one second. In practice it should only take a millisecond or so.

Parameters:

sockets[out] List of RakNetSocket2 structures in use. Sockets will not be closed until sockets goes out of scope

virtual void ReleaseSockets(DataStructures::List<RakNetSocket2*> &sockets) = 0
virtual void WriteOutOfBandHeader(MafiaNet::BitStream *bitStream) = 0
virtual void SetUserUpdateThread(void (*_userUpdateThreadPtr)(RakPeerInterface*, void*), void *_userUpdateThreadData) = 0

If you need code to run in the same thread as RakNet’s update thread, this function can be used for that

Parameters:
  • _userUpdateThreadPtr[in] C callback function

  • _userUpdateThreadData[in] Passed to C callback function

virtual void SetIncomingDatagramEventHandler(bool (*_incomingDatagramEventHandler)(RNS2RecvStruct*)) = 0

Set a C callback to be called whenever a datagram arrives Return true from the callback to have RakPeer handle the datagram. Return false and RakPeer will ignore the datagram. This can be used to filter incoming datagrams by system, or to share a recvfrom socket with RakPeer RNS2RecvStruct will only remain valid for the duration of the call If the incoming datagram is not from your game at all, it is a RakNet packet. If the incoming datagram has an IP address that matches a known address from your game, then check the first byte of data. For RakNet connected systems, the first bit is always 1. So for your own game packets, make sure the first bit is always 0.

virtual void ApplyNetworkSimulator(float packetloss, unsigned short minExtraPing, unsigned short extraPingVariance) = 0

Adds simulated ping and packet loss to the outgoing data flow. To simulate bi-directional ping and packet loss, you should call this on both the sender and the recipient, with half the total ping and packetloss value on each. You can exclude network simulator code with the _RELEASE #define to decrease code size

Deprecated:

Use http://www.jenkinssoftware.com/forum/index.php?topic=1671.0 instead.

Note

Doesn’t work past version 3.6201

Parameters:
  • packetloss[in] Chance to lose a packet. Ranges from 0 to 1.

  • minExtraPing[in] The minimum time to delay sends.

  • extraPingVariance[in] The additional random time to delay sends.

virtual void SetPerConnectionOutgoingBandwidthLimit(unsigned maxBitsPerSecond) = 0

Limits how much outgoing bandwidth can be sent per-connection. This limit does not apply to the sum of all connections! Exceeding the limit queues up outgoing traffic

Parameters:

maxBitsPerSecond[in] Maximum bits per second to send. Use 0 for unlimited (default). Once set, it takes effect immedately and persists until called again.

virtual bool IsNetworkSimulatorActive(void) = 0

Returns if you previously called ApplyNetworkSimulator

Returns:

If you previously called ApplyNetworkSimulator

virtual RakNetStatistics *GetStatistics(const SystemAddress systemAddress, RakNetStatistics *rns = 0) = 0

Returns a structure containing a large set of network statistics for the specified system. You can map this data to a string using the C style StatisticsToString() function

See also

statistics.h

Parameters:
  • systemAddress[in] Which connected system to get statistics for

  • rns[in] If you supply this structure, it will be written to it. Otherwise it will use a static struct, which is not threadsafe

Returns:

0 on can’t find the specified system. A pointer to a set of data otherwise.

virtual bool GetStatistics(const unsigned int index, RakNetStatistics *rns) = 0

Returns the network statistics of the system at the given index in the remoteSystemList.

Returns:

True if the index is less than the maximum number of peers allowed and the system is active. False otherwise.

virtual void GetStatisticsList(DataStructures::List<SystemAddress> &addresses, DataStructures::List<RakNetGUID> &guids, DataStructures::List<RakNetStatistics> &statistics) = 0

Returns the list of systems, and statistics for each of those systems Each system has one entry in each of the lists, in the same order.

Parameters:
  • addresses[out] SystemAddress for each connected system

  • guids[out] RakNetGUID for each connected system

  • statistics[out] Calculated RakNetStatistics for each connected system

virtual unsigned int GetReceiveBufferSize(void) = 0

\Returns how many messages are waiting when you call Receive()

virtual bool RunUpdateCycle(BitStream &updateBitStream) = 0
virtual bool SendOutOfBand(const char *host, unsigned short remotePort, const char *data, BitSize_t dataLength, unsigned connectionSocketIndex = 0) = 0

Public Static Functions

static RakPeerInterface *GetInstance(void)
static void DestroyInstance(RakPeerInterface *i)
static uint64_t Get64BitUniqueRandomNumber(void)

Get a random number (to generate a GUID)

BitStream

Binary serialization for network messages.

class BitStream

This class allows you to write and read native types as a string of bits. BitStream is used extensively throughout RakNet and is designed to be used by users as well.

See also

BitStreamSample.txt

Public Functions

BitStream()

Default Constructor.

BitStream(const unsigned int initialBytesToAllocate)

Create the bitstream, with some number of bytes to immediately allocate.

There is no benefit to calling this, unless you know exactly how many bytes you need and it is greater than BITSTREAM_STACK_ALLOCATION_SIZE. In that case all it does is save you one or more realloc calls.

Parameters:

initialBytesToAllocate[in] the number of bytes to pre-allocate.

BitStream(unsigned char *_data, const unsigned int lengthInBytes, bool _copyData)

Initialize the BitStream, immediately setting the data it contains to a predefined pointer.

Set _copyData to true if you want to make an internal copy of the data you are passing. Set it to false to just save a pointer to the data. You shouldn’t call Write functions with _copyData as false, as this will write to unallocated memory 99% of the time you will use this function to cast Packet::data to a bitstream for reading, in which case you should write something as follows:

MafiaNet::BitStream bs(packet->data, packet->length, false);

Parameters:
  • _data[in] An array of bytes.

  • lengthInBytes[in] Size of the _data.

  • _copyData[in] true or false to make a copy of _data or not.

~BitStream()
void Reset(void)

Resets the bitstream for reuse.

template<class templateType>
inline bool Serialize(bool writeToBitstream, templateType &inOutTemplateVar)

Bidirectional serialize/deserialize any integral type to/from a bitstream.

Undefine __BITSTREAM_NATIVE_END if you need endian swapping.

Parameters:
  • writeToBitstream[in] true to write from your data to this bitstream. False to read from this bitstream and write to your data

  • inOutTemplateVar[in] The value to write

Returns:

true if writeToBitstream is true. true if writeToBitstream is false and the read was successful. false if writeToBitstream is false and the read was not successful.

template<class templateType>
inline bool SerializeDelta(bool writeToBitstream, templateType &inOutCurrentValue, const templateType &lastValue)

Bidirectional serialize/deserialize any integral type to/from a bitstream.

If the current value is different from the last value the current value will be written. Otherwise, a single bit will be written

Parameters:
  • writeToBitstream[in] true to write from your data to this bitstream. False to read from this bitstream and write to your data

  • inOutCurrentValue[in] The current value to write

  • lastValue[in] The last value to compare against. Only used if writeToBitstream is true.

Returns:

true if writeToBitstream is true. true if writeToBitstream is false and the read was successful. false if writeToBitstream is false and the read was not successful.

template<class templateType>
inline bool SerializeDelta(bool writeToBitstream, templateType &inOutCurrentValue)

Bidirectional version of SerializeDelta when you don’t know what the last value is, or there is no last value.

Parameters:
  • writeToBitstream[in] true to write from your data to this bitstream. False to read from this bitstream and write to your data

  • inOutCurrentValue[in] The current value to write

Returns:

true if writeToBitstream is true. true if writeToBitstream is false and the read was successful. false if writeToBitstream is false and the read was not successful.

template<class templateType>
inline bool SerializeCompressed(bool writeToBitstream, templateType &inOutTemplateVar)

Bidirectional serialize/deserialize any integral type to/from a bitstream.

Undefine __BITSTREAM_NATIVE_END if you need endian swapping. If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type

Parameters:
  • writeToBitstream[in] true to write from your data to this bitstream. False to read from this bitstream and write to your data

  • inOutTemplateVar[in] The value to write

Returns:

true if writeToBitstream is true. true if writeToBitstream is false and the read was successful. false if writeToBitstream is false and the read was not successful.

template<class templateType>
inline bool SerializeCompressedDelta(bool writeToBitstream, templateType &inOutCurrentValue, const templateType &lastValue)

Bidirectional serialize/deserialize any integral type to/from a bitstream.

If the current value is different from the last value the current value will be written. Otherwise, a single bit will be written For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte

Parameters:
  • writeToBitstream[in] true to write from your data to this bitstream. False to read from this bitstream and write to your data

  • inOutCurrentValue[in] The current value to write

  • lastValue[in] The last value to compare against. Only used if writeToBitstream is true.

Returns:

true if writeToBitstream is true. true if writeToBitstream is false and the read was successful. false if writeToBitstream is false and the read was not successful.

template<class templateType>
inline bool SerializeCompressedDelta(bool writeToBitstream, templateType &inOutTemplateVar)

Save as SerializeCompressedDelta(templateType &currentValue, const templateType &lastValue) when we have an unknown second parameter.

Returns:

true on data read. False on insufficient data in bitstream

inline bool Serialize(bool writeToBitstream, char *inOutByteArray, const unsigned int numberOfBytes)

Bidirectional serialize/deserialize an array or casted stream or raw data. This does NOT do endian swapping.

Parameters:
  • writeToBitstream[in] true to write from your data to this bitstream. False to read from this bitstream and write to your data

  • inOutByteArray[in] a byte buffer

  • numberOfBytes[in] the size of input in bytes

Returns:

true if writeToBitstream is true. true if writeToBitstream is false and the read was successful. false if writeToBitstream is false and the read was not successful.

bool SerializeFloat16(bool writeToBitstream, float &inOutFloat, float floatMin, float floatMax)

Serialize a float into 2 bytes, spanning the range between floatMin and floatMax.

Parameters:
  • writeToBitstream[in] true to write from your data to this bitstream. False to read from this bitstream and write to your data

  • inOutFloat[in] The float to write

  • floatMin[in] Predetermined minimum value of f

  • floatMax[in] Predetermined maximum value of f

template<class serializationType, class sourceType>
bool SerializeCasted(bool writeToBitstream, sourceType &value)

Serialize one type casted to another (smaller) type, to save bandwidth serializationType should be uint8_t, uint16_t, uint24_t, or uint32_t Example: int num=53; SerializeCasted<uint8_t>(true, num); would use 1 byte to write what would otherwise be an integer (4 or 8 bytes)

Parameters:
  • writeToBitstream[in] true to write from your data to this bitstream. False to read from this bitstream and write to your data

  • value[in] The value to serialize

template<class templateType>
bool SerializeBitsFromIntegerRange(bool writeToBitstream, templateType &value, const templateType minimum, const templateType maximum, bool allowOutsideRange = false)

Given the minimum and maximum values for an integer type, figure out the minimum number of bits to represent the range Then serialize only those bits

Note

A static is used so that the required number of bits for (maximum-minimum) is only calculated once. This does require that minimum and \maximum are fixed values for a given line of code for the life of the program

Parameters:
  • writeToBitstream[in] true to write from your data to this bitstream. False to read from this bitstream and write to your data

  • value[in] Integer value to write, which should be between minimum and maximum

  • minimum[in] Minimum value of value

  • maximum[in] Maximum value of value

  • allowOutsideRange[in] If true, all sends will take an extra bit, however value can deviate from outside minimum and maximum. If false, will assert if the value deviates

template<class templateType>
bool SerializeBitsFromIntegerRange(bool writeToBitstream, templateType &value, const templateType minimum, const templateType maximum, const int requiredBits, bool allowOutsideRange = false)
Parameters:

requiredBits[in] Primarily for internal use, called from above function() after calculating number of bits needed to represent maximum-minimum

template<class templateType>
inline bool SerializeNormVector(bool writeToBitstream, templateType &x, templateType &y, templateType &z)

Bidirectional serialize/deserialize a normalized 3D vector, using (at most) 4 bytes + 3 bits instead of 12-24 bytes.

Will further compress y or z axis aligned vectors. Accurate to 1/32767.5.

Parameters:
  • writeToBitstream[in] true to write from your data to this bitstream. False to read from this bitstream and write to your data

  • x[in] x

  • y[in] y

  • z[in] z

Returns:

true if writeToBitstream is true. true if writeToBitstream is false and the read was successful. false if writeToBitstream is false and the read was not successful.

template<class templateType>
inline bool SerializeVector(bool writeToBitstream, templateType &x, templateType &y, templateType &z)

Bidirectional serialize/deserialize a vector, using 10 bytes instead of 12.

Loses accuracy to about 3/10ths and only saves 2 bytes, so only use if accuracy is not important.

Parameters:
  • writeToBitstream[in] true to write from your data to this bitstream. False to read from this bitstream and write to your data

  • x[in] x

  • y[in] y

  • z[in] z

Returns:

true if writeToBitstream is true. true if writeToBitstream is false and the read was successful. false if writeToBitstream is false and the read was not successful.

template<class templateType>
inline bool SerializeNormQuat(bool writeToBitstream, templateType &w, templateType &x, templateType &y, templateType &z)

Bidirectional serialize/deserialize a normalized quaternion in 6 bytes + 4 bits instead of 16 bytes. Slightly lossy.

Parameters:
  • writeToBitstream[in] true to write from your data to this bitstream. False to read from this bitstream and write to your data

  • w[in] w

  • x[in] x

  • y[in] y

  • z[in] z

Returns:

true if writeToBitstream is true. true if writeToBitstream is false and the read was successful. false if writeToBitstream is false and the read was not successful.

template<class templateType>
inline bool SerializeOrthMatrix(bool writeToBitstream, templateType &m00, templateType &m01, templateType &m02, templateType &m10, templateType &m11, templateType &m12, templateType &m20, templateType &m21, templateType &m22)

Bidirectional serialize/deserialize an orthogonal matrix by creating a quaternion, and writing 3 components of the quaternion in 2 bytes each.

Use 6 bytes instead of 36 Lossy, although the result is renormalized

Returns:

true on success, false on failure.

inline bool SerializeBits(bool writeToBitstream, unsigned char *inOutByteArray, const BitSize_t numberOfBitsToSerialize, const bool rightAlignedBits = true)

Bidirectional serialize/deserialize numberToSerialize bits to/from the input.

Right aligned data means in the case of a partial byte, the bits are aligned from the right (bit 0) rather than the left (as in the normal internal representation) You would set this to true when writing user data, and false when copying bitstream data, such as writing one bitstream to another

Parameters:
  • writeToBitstream[in] true to write from your data to this bitstream. False to read from this bitstream and write to your data

  • inOutByteArray[in] The data

  • numberOfBitsToSerialize[in] The number of bits to write

  • rightAlignedBits[in] if true data will be right aligned

Returns:

true if writeToBitstream is true. true if writeToBitstream is false and the read was successful. false if writeToBitstream is false and the read was not successful.

template<class templateType>
inline void Write(const templateType &inTemplateVar)

Write any integral type to a bitstream.

Undefine __BITSTREAM_NATIVE_END if you need endian swapping.

Parameters:

inTemplateVar[in] The value to write

template<class templateType>
inline void WritePtr(templateType *inTemplateVar)

Write the dereferenced pointer to any integral type to a bitstream.

Undefine __BITSTREAM_NATIVE_END if you need endian swapping.

Parameters:

inTemplateVar[in] The value to write

template<class templateType>
inline void WriteDelta(const templateType &currentValue, const templateType &lastValue)

Write any integral type to a bitstream.

If the current value is different from the last value the current value will be written. Otherwise, a single bit will be written

Parameters:
  • currentValue[in] The current value to write

  • lastValue[in] The last value to compare against

template<class templateType>
inline void WriteDelta(const templateType &currentValue)

WriteDelta when you don’t know what the last value is, or there is no last value.

Parameters:

currentValue[in] The current value to write

template<class templateType>
inline void WriteCompressed(const templateType &inTemplateVar)

Write any integral type to a bitstream.

Undefine __BITSTREAM_NATIVE_END if you need endian swapping. If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type

Undefine __BITSTREAM_NATIVE_END if you need endian swapping. For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte

Parameters:
  • inTemplateVar[in] The value to write

  • inTemplateVar[in] The value to write

template<class templateType>
inline void WriteCompressedDelta(const templateType &currentValue, const templateType &lastValue)

Write any integral type to a bitstream.

If the current value is different from the last value the current value will be written. Otherwise, a single bit will be written For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte

Parameters:
  • currentValue[in] The current value to write

  • lastValue[in] The last value to compare against

template<class templateType>
inline void WriteCompressedDelta(const templateType &currentValue)

Save as WriteCompressedDelta(const templateType &currentValue, const templateType &lastValue) when we have an unknown second parameter.

template<class templateType>
inline bool Read(templateType &outTemplateVar)

Read any integral type from a bitstream.

Read any integral type from a bitstream. Define __BITSTREAM_NATIVE_END if you need endian swapping.

Define __BITSTREAM_NATIVE_END if you need endian swapping.

Parameters:
  • outTemplateVar[in] The value to read

  • outTemplateVar[in] The value to read

Returns:

true on success, false on failure.

inline bool Read(wchar_t *&varString)

Read a wchar from a bitstream.

Define __BITSTREAM_NATIVE_END if you need endian swapping.

Parameters:
  • varString[in] The value to read

  • varStringLength[in] The length of the given varString array (in wchar_t)

Returns:

true on success, false on failure.

inline bool Read(wchar_t *&varString, size_t varStringLength)
template<class templateType>
inline bool ReadDelta(templateType &outTemplateVar)

Read any integral type from a bitstream.

If the written value differed from the value compared against in the write function, var will be updated. Otherwise it will retain the current value. ReadDelta is only valid from a previous call to WriteDelta

If the written value differed from the value compared against in the write function, var will be updated. Otherwise it will retain the current value. ReadDelta is only valid from a previous call to WriteDelta

Parameters:
  • outTemplateVar[in] The value to read

  • outTemplateVar[in] The value to read

Returns:

true on success, false on failure.

template<class templateType>
inline bool ReadCompressed(templateType &outTemplateVar)

Read any integral type from a bitstream.

Undefine __BITSTREAM_NATIVE_END if you need endian swapping. For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte

Undefine __BITSTREAM_NATIVE_END if you need endian swapping. For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte

Parameters:
  • outTemplateVar[in] The value to read

  • outTemplateVar[in] The value to read

Returns:

true on success, false on failure.

inline bool ReadCompressed(wchar_t *&varString)

Read a wchar from a bitstream.

Define __BITSTREAM_NATIVE_END if you need endian swapping. This is lossless, but only has benefit if you use less than half the bits of the type If you are not using __BITSTREAM_NATIVE_END the opposite is true

Parameters:
  • varString[in] The value to read

  • varStringLength[in] The length of the given varString array (in wchar_t)

Returns:

true on success, false on failure.

inline bool ReadCompressed(wchar_t *&varString, size_t varStringLength)
template<class templateType>
inline bool ReadCompressedDelta(templateType &outTemplateVar)

Read any integral type from a bitstream.

If the written value differed from the value compared against in the write function, var will be updated. Otherwise it will retain the current value. the current value will be updated. For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte ReadCompressedDelta is only valid from a previous call to WriteDelta

If the written value differed from the value compared against in the write function, var will be updated. Otherwise it will retain the current value. the current value will be updated. For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte ReadCompressedDelta is only valid from a previous call to WriteDelta

Parameters:
  • outTemplateVar[in] The value to read

  • outTemplateVar[in] The value to read

Returns:

true on success, false on failure.

bool Read(BitStream *bitStream, BitSize_t numberOfBits)

Read one bitstream to another.

Parameters:
  • numberOfBits[in] bits to read

  • bitStream – the bitstream to read into from

Returns:

true on success, false on failure.

bool Read(BitStream *bitStream)
bool Read(BitStream &bitStream, BitSize_t numberOfBits)
bool Read(BitStream &bitStream)
void Write(const char *inputByteArray, const unsigned int numberOfBytes)

Write an array or casted stream or raw data. This does NOT do endian swapping.

Parameters:
  • inputByteArray[in] a byte buffer

  • numberOfBytes[in] the size of input in bytes

void Write(BitStream *bitStream, BitSize_t numberOfBits)

Write one bitstream to another.

Parameters:
  • numberOfBits[in] bits to write

  • bitStream – the bitstream to copy from

void Write(BitStream *bitStream)
void Write(BitStream &bitStream, BitSize_t numberOfBits)
void Write(BitStream &bitStream)
void WriteFloat16(float x, float floatMin, float floatMax)

Write a float into 2 bytes, spanning the range between floatMin and floatMax.

Parameters:
  • x[in] The float to write

  • floatMin[in] Predetermined minimum value of f

  • floatMax[in] Predetermined maximum value of f

template<class serializationType, class sourceType>
void WriteCasted(const sourceType &value)

Write one type serialized as another (smaller) type, to save bandwidth serializationType should be uint8_t, uint16_t, uint24_t, or uint32_t Example: int num=53; WriteCasted<uint8_t>(num); would use 1 byte to write what would otherwise be an integer (4 or 8 bytes)

Parameters:

value[in] The value to write

template<class templateType>
void WriteBitsFromIntegerRange(const templateType value, const templateType minimum, const templateType maximum, bool allowOutsideRange = false)

Given the minimum and maximum values for an integer type, figure out the minimum number of bits to represent the range Then write only those bits

Note

A static is used so that the required number of bits for (maximum-minimum) is only calculated once. This does require that minimum and \maximum are fixed values for a given line of code for the life of the program

Parameters:
  • value[in] Integer value to write, which should be between minimum and maximum

  • minimum[in] Minimum value of value

  • maximum[in] Maximum value of value

  • allowOutsideRange[in] If true, all sends will take an extra bit, however value can deviate from outside minimum and maximum. If false, will assert if the value deviates. This should match the corresponding value passed to Read().

template<class templateType>
void WriteBitsFromIntegerRange(const templateType value, const templateType minimum, const templateType maximum, const int requiredBits, bool allowOutsideRange = false)
Parameters:

requiredBits[in] Primarily for internal use, called from above function() after calculating number of bits needed to represent maximum-minimum

template<class templateType>
void WriteNormVector(templateType x, templateType y, templateType z)

Write a normalized 3D vector, using (at most) 4 bytes + 3 bits instead of 12-24 bytes.

Will further compress y or z axis aligned vectors. Accurate to 1/32767.5.

Parameters:
  • x[in] x

  • y[in] y

  • z[in] z

template<class templateType>
void WriteVector(templateType x, templateType y, templateType z)

Write a vector, using 10 bytes instead of 12.

Loses accuracy to about 3/10ths and only saves 2 bytes, so only use if accuracy is not important.

Parameters:
  • x[in] x

  • y[in] y

  • z[in] z

template<class templateType>
void WriteNormQuat(templateType w, templateType x, templateType y, templateType z)

Write a normalized quaternion in 6 bytes + 4 bits instead of 16 bytes. Slightly lossy.

Parameters:
  • w[in] w

  • x[in] x

  • y[in] y

  • z[in] z

template<class templateType>
void WriteOrthMatrix(templateType m00, templateType m01, templateType m02, templateType m10, templateType m11, templateType m12, templateType m20, templateType m21, templateType m22)

Write an orthogonal matrix by creating a quaternion, and writing 3 components of the quaternion in 2 bytes each.

Use 6 bytes instead of 36 Lossy, although the result is renormalized

bool Read(char *output, const unsigned int numberOfBytes)

Read an array or casted stream of byte.

The array is raw data. There is no automatic endian conversion with this function

Parameters:
  • output[in] The result byte array. It should be larger than numberOfBytes.

  • numberOfBytes[in] The number of byte to read

Returns:

true on success false if there is some missing bytes.

bool ReadFloat16(float &outFloat, float floatMin, float floatMax)

Read a float into 2 bytes, spanning the range between floatMin and floatMax.

Parameters:
  • outFloat[in] The float to read

  • floatMin[in] Predetermined minimum value of f

  • floatMax[in] Predetermined maximum value of f

template<class serializationType, class sourceType>
bool ReadCasted(sourceType &value)

Read one type serialized to another (smaller) type, to save bandwidth serializationType should be uint8_t, uint16_t, uint24_t, or uint32_t Example: int num; ReadCasted<uint8_t>(num); would read 1 bytefrom the stream, and put the value in an integer

Parameters:

value[in] The value to write

template<class templateType>
bool ReadBitsFromIntegerRange(templateType &value, const templateType minimum, const templateType maximum, bool allowOutsideRange = false)

Given the minimum and maximum values for an integer type, figure out the minimum number of bits to represent the range Then read only those bits

Note

A static is used so that the required number of bits for (maximum-minimum) is only calculated once. This does require that minimum and \maximum are fixed values for a given line of code for the life of the program

Parameters:
  • value[in] Integer value to read, which should be between minimum and maximum

  • minimum[in] Minimum value of value

  • maximum[in] Maximum value of value

  • allowOutsideRange[in] If true, all sends will take an extra bit, however value can deviate from outside minimum and maximum. If false, will assert if the value deviates. This should match the corresponding value passed to Write().

template<class templateType>
bool ReadBitsFromIntegerRange(templateType &value, const templateType minimum, const templateType maximum, const int requiredBits, bool allowOutsideRange = false)
Parameters:

requiredBits[in] Primarily for internal use, called from above function() after calculating number of bits needed to represent maximum-minimum

template<class templateType>
bool ReadNormVector(templateType &x, templateType &y, templateType &z)

Read a normalized 3D vector, using (at most) 4 bytes + 3 bits instead of 12-24 bytes.

Will further compress y or z axis aligned vectors. Accurate to 1/32767.5.

Parameters:
  • x[in] x

  • y[in] y

  • z[in] z

Returns:

true on success, false on failure.

template<class templateType>
bool ReadVector(templateType &x, templateType &y, templateType &z)

Read 3 floats or doubles, using 10 bytes, where those float or doubles comprise a vector.

Loses accuracy to about 3/10ths and only saves 2 bytes, so only use if accuracy is not important.

Parameters:
  • x[in] x

  • y[in] y

  • z[in] z

Returns:

true on success, false on failure.

template<class templateType>
bool ReadNormQuat(templateType &w, templateType &x, templateType &y, templateType &z)

Read a normalized quaternion in 6 bytes + 4 bits instead of 16 bytes.

Parameters:
  • w[in] w

  • x[in] x

  • y[in] y

  • z[in] z

Returns:

true on success, false on failure.

template<class templateType>
bool ReadOrthMatrix(templateType &m00, templateType &m01, templateType &m02, templateType &m10, templateType &m11, templateType &m12, templateType &m20, templateType &m21, templateType &m22)

Read an orthogonal matrix from a quaternion, reading 3 components of the quaternion in 2 bytes each and extrapolatig the 4th.

Use 6 bytes instead of 36 Lossy, although the result is renormalized

Returns:

true on success, false on failure.

void ResetReadPointer(void)

Sets the read pointer back to the beginning of your data.

void ResetWritePointer(void)

Sets the write pointer back to the beginning of your data.

void AssertStreamEmpty(void)

This is good to call when you are done with the stream to make sure you didn’t leave any data left over void.

void PrintBits(char *out) const

RAKNET_DEBUG_PRINTF the bits in the stream. Great for debugging.

void PrintBits(char *out, size_t outLength) const
void PrintBits(void) const
void PrintHex(char *out) const
void PrintHex(char *out, size_t outLength) const
void PrintHex(void) const
void IgnoreBits(const BitSize_t numberOfBits)

Ignore data we don’t intend to read.

Parameters:

numberOfBits[in] The number of bits to ignore

void IgnoreBytes(const unsigned int numberOfBytes)

Ignore data we don’t intend to read.

Parameters:

numberOfBits[in] The number of bytes to ignore

void SetWriteOffset(const BitSize_t offset)

Move the write pointer to a position on the array.

Dangerous if you don’t know what you are doing! For efficiency reasons you can only write mid-stream if your data is byte aligned.

Attention

Parameters:

offset[in] the offset from the start of the array.

inline BitSize_t GetNumberOfBitsUsed(void) const

Returns the length in bits of the stream.

inline BitSize_t GetWriteOffset(void) const
inline BitSize_t GetNumberOfBytesUsed(void) const

Returns the length in bytes of the stream.

inline BitSize_t GetReadOffset(void) const

Returns the number of bits into the stream that we have read.

void SetReadOffset(const BitSize_t newReadOffset)

Sets the read bit index.

inline BitSize_t GetNumberOfUnreadBits(void) const

Returns the number of bits left in the stream that haven’t been read.

BitSize_t CopyData(unsigned char **_data) const

Makes a copy of the internal data for you _data will point to the stream. Partial bytes are left aligned.

Parameters:

_data[out] The allocated copy of GetData()

Returns:

The length in bits of the stream.

void SetData(unsigned char *inByteArray)
inline unsigned char *GetData(void) const

Gets the data that BitStream is writing to / reading from. Partial bytes are left aligned.

Returns:

A pointer to the internal state

void WriteBits(const unsigned char *inByteArray, BitSize_t numberOfBitsToWrite, const bool rightAlignedBits = true)

Write numberToWrite bits from the input source.

Right aligned data means in the case of a partial byte, the bits are aligned from the right (bit 0) rather than the left (as in the normal internal representation) You would set this to true when writing user data, and false when copying bitstream data, such as writing one bitstream to another.

Parameters:
  • inByteArray[in] The data

  • numberOfBitsToWrite[in] The number of bits to write

  • rightAlignedBits[in] if true data will be right aligned

void WriteAlignedBytes(const unsigned char *inByteArray, const unsigned int numberOfBytesToWrite)

Align the bitstream to the byte boundary and then write the specified number of bits.

This is faster than WriteBits but wastes the bits to do the alignment and requires you to call ReadAlignedBits at the corresponding read position.

Parameters:
  • inByteArray[in] The data

  • numberOfBytesToWrite[in] The size of input.

void EndianSwapBytes(int byteOffset, int length)
void WriteAlignedBytesSafe(const char *inByteArray, const unsigned int inputLength, const unsigned int maxBytesToWrite)

Aligns the bitstream, writes inputLength, and writes input. Won’t write beyond maxBytesToWrite.

Parameters:
  • inByteArray[in] The data

  • inputLength[in] The size of input.

  • maxBytesToWrite[in] Max bytes to write

bool ReadAlignedBytes(unsigned char *inOutByteArray, const unsigned int numberOfBytesToRead)

Read bits, starting at the next aligned bits.

Note that the modulus 8 starting offset of the sequence must be the same as was used with WriteBits. This will be a problem with packet coalescence unless you byte align the coalesced packets.

Parameters:
  • inOutByteArray[in] The byte array larger than numberOfBytesToRead

  • numberOfBytesToRead[in] The number of byte to read from the internal state

Returns:

true if there is enough byte.

bool ReadAlignedBytesSafe(char *inOutByteArray, int &inputLength, const int maxBytesToRead)

Reads what was written by WriteAlignedBytesSafe.

Parameters:
  • inOutByteArray[in] The data

  • maxBytesToRead[in] Maximum number of bytes to read

Returns:

true on success, false on failure.

bool ReadAlignedBytesSafe(char *inOutByteArray, unsigned int &inputLength, const unsigned int maxBytesToRead)
bool ReadAlignedBytesSafeAlloc(char **outByteArray, int &inputLength, const unsigned int maxBytesToRead)

Same as ReadAlignedBytesSafe() but allocates the memory for you using new, rather than assuming it is safe to write to.

Parameters:

outByteArray[in] outByteArray will be deleted if it is not a pointer to 0

Returns:

true on success, false on failure.

bool ReadAlignedBytesSafeAlloc(char **outByteArray, unsigned int &inputLength, const unsigned int maxBytesToRead)
inline void AlignWriteToByteBoundary(void)

Align the next write and/or read to a byte boundary.

This can be used to ‘waste’ bits to byte align for efficiency reasons It can also be used to force coalesced bitstreams to start on byte boundaries so so WriteAlignedBits and ReadAlignedBits both calculate the same offset when aligning.

void AlignReadToByteBoundary(void)

Align the next write and/or read to a byte boundary.

This can be used to ‘waste’ bits to byte align for efficiency reasons It can also be used to force coalesced bitstreams to start on byte boundaries so so WriteAlignedBits and ReadAlignedBits both calculate the same offset when aligning.

bool ReadBits(unsigned char *inOutByteArray, BitSize_t numberOfBitsToRead, const bool alignBitsToRight = true)

Read numberOfBitsToRead bits to the output source.

alignBitsToRight should be set to true to convert internal bitstream data to userdata. It should be false if you used WriteBits with rightAlignedBits false

Parameters:
  • inOutByteArray[in] The resulting bits array

  • numberOfBitsToRead[in] The number of bits to read

  • alignBitsToRight[in] if true bits will be right aligned.

Returns:

true if there is enough bits to read

void Write0(void)

Write a 0.

void Write1(void)

Write a 1.

bool ReadBit(void)

Reads 1 bit and returns true if that bit is 1 and false if it is 0.

void AssertCopyData(void)

If we used the constructor version with copy data off, this *makes sure it is set to on and the data pointed to is copied.

void SetNumberOfBitsAllocated(const BitSize_t lengthInBits)

Use this if you pass a pointer copy to the constructor *(_copyData==false) and want to overallocate to prevent reallocation.

void AddBitsAndReallocate(const BitSize_t numberOfBitsToWrite)

Reallocates (if necessary) in preparation of writing numberOfBitsToWrite.

BitSize_t GetNumberOfBitsAllocated(void) const
bool Read(char *varString)

Read strings, non reference.

bool Read(unsigned char *varString)
void PadWithZeroToByteLength(unsigned int bytes)

Write zeros until the bitstream is filled up to bytes.

void WriteAlignedVar8(const char *inByteArray)
bool ReadAlignedVar8(char *inOutByteArray)
void WriteAlignedVar16(const char *inByteArray)
bool ReadAlignedVar16(char *inOutByteArray)
void WriteAlignedVar32(const char *inByteArray)
bool ReadAlignedVar32(char *inOutByteArray)
inline void Write(const char *const inStringVar)
inline void Write(const wchar_t *const inStringVar)
inline void Write(const unsigned char *const inTemplateVar)
inline void Write(char *const inTemplateVar)
inline void Write(unsigned char *const inTemplateVar)
inline void WriteCompressed(const char *const inStringVar)
inline void WriteCompressed(const wchar_t *const inStringVar)
inline void WriteCompressed(const unsigned char *const inTemplateVar)
inline void WriteCompressed(char *const inTemplateVar)
inline void WriteCompressed(unsigned char *const inTemplateVar)
template<>
inline void Write(const bool &inTemplateVar)

Write a bool to a bitstream.

Parameters:

inTemplateVar[in] The value to write

template<>
inline void Write(const SystemAddress &inTemplateVar)

Write a systemAddress to a bitstream.

Parameters:

inTemplateVar[in] The value to write

template<>
inline void Write(const uint24_t &inTemplateVar)
template<>
inline void Write(const RakNetGUID &inTemplateVar)
template<>
inline void Write(const RakString &inTemplateVar)

Write a string to a bitstream.

Parameters:

var[in] The value to write

template<>
inline void Write(const RakWString &inTemplateVar)
template<>
inline void Write(const char *const &inStringVar)
template<>
inline void Write(const wchar_t *const &inStringVar)
template<>
inline void Write(const unsigned char *const &inTemplateVar)
template<>
inline void Write(char *const &inTemplateVar)
template<>
inline void Write(unsigned char *const &inTemplateVar)
template<>
inline void Write(const std::string &inStringVar)

Write a std::string to a bitstream by value.

Uses the same length-prefixed wire format as RakString (an unsigned short length followed by the raw bytes), so std::string and RakString are interchangeable on the wire. This specialization exists so std::string does NOT fall through to the catch-all template, which would raw-copy the object representation (pointer/size/capacity) and corrupt memory on deserialize.

Parameters:

inStringVar[in] The value to write

template<>
inline void WriteDelta(const bool &currentValue, const bool &lastValue)

Write a bool delta. Same thing as just calling Write.

Parameters:
  • currentValue[in] The current value to write

  • lastValue[in] The last value to compare against

template<>
inline void WriteCompressed(const SystemAddress &inTemplateVar)
template<>
inline void WriteCompressed(const RakNetGUID &inTemplateVar)
template<>
inline void WriteCompressed(const uint24_t &var)
template<>
inline void WriteCompressed(const bool &inTemplateVar)
template<>
inline void WriteCompressed(const float &inTemplateVar)

For values between -1 and 1.

template<>
inline void WriteCompressed(const double &inTemplateVar)

For values between -1 and 1.

template<>
inline void WriteCompressed(const RakString &inTemplateVar)

Compress the string.

template<>
inline void WriteCompressed(const RakWString &inTemplateVar)
template<>
inline void WriteCompressed(const char *const &inStringVar)
template<>
inline void WriteCompressed(const wchar_t *const &inStringVar)
template<>
inline void WriteCompressed(const unsigned char *const &inTemplateVar)
template<>
inline void WriteCompressed(char *const &inTemplateVar)
template<>
inline void WriteCompressed(unsigned char *const &inTemplateVar)
template<>
inline void WriteCompressedDelta(const bool &currentValue, const bool &lastValue)

Write a bool delta. Same thing as just calling Write.

Parameters:
  • currentValue[in] The current value to write

  • lastValue[in] The last value to compare against

template<>
inline void WriteCompressedDelta(const bool &currentValue)

Save as WriteCompressedDelta(bool currentValue, const templateType &lastValue) when we have an unknown second bool.

template<>
inline bool Read(bool &outTemplateVar)

Read a bool from a bitstream.

Parameters:

outTemplateVar[in] The value to read

template<>
inline bool Read(SystemAddress &outTemplateVar)

Read a systemAddress from a bitstream.

Parameters:

outTemplateVar[in] The value to read

template<>
inline bool Read(uint24_t &outTemplateVar)
template<>
inline bool Read(RakNetGUID &outTemplateVar)
template<>
inline bool Read(RakString &outTemplateVar)
template<>
inline bool Read(RakWString &outTemplateVar)
template<>
inline bool Read(char *&varString)
template<>
inline bool Read(unsigned char *&varString)
template<>
inline bool Read(std::string &outStringVar)
template<>
inline bool ReadDelta(bool &outTemplateVar)

Read a bool from a bitstream.

Parameters:

outTemplateVar[in] The value to read

template<>
inline bool ReadCompressed(SystemAddress &outTemplateVar)
template<>
inline bool ReadCompressed(uint24_t &outTemplateVar)
template<>
inline bool ReadCompressed(RakNetGUID &outTemplateVar)
template<>
inline bool ReadCompressed(bool &outTemplateVar)
template<>
inline bool ReadCompressed(float &outTemplateVar)

For values between -1 and 1.

template<>
inline bool ReadCompressed(double &outTemplateVar)

For values between -1 and 1.

template<>
inline bool ReadCompressed(RakString &outTemplateVar)

For strings.

template<>
inline bool ReadCompressed(RakWString &outTemplateVar)
template<>
inline bool ReadCompressed(char *&outTemplateVar)
template<>
inline bool ReadCompressed(unsigned char *&outTemplateVar)
template<>
inline bool ReadCompressedDelta(bool &outTemplateVar)

Read a bool from a bitstream.

Parameters:

outTemplateVar[in] The value to read

Public Static Functions

static BitStream *GetInstance(void)
static void DestroyInstance(BitStream *i)
static int NumberOfLeadingZeroes(uint8_t x)

Get the number of leading zeros for a number

Parameters:

x[in] Number to test

static int NumberOfLeadingZeroes(uint16_t x)
static int NumberOfLeadingZeroes(uint32_t x)
static int NumberOfLeadingZeroes(uint64_t x)
static int NumberOfLeadingZeroes(int8_t x)
static int NumberOfLeadingZeroes(int16_t x)
static int NumberOfLeadingZeroes(int32_t x)
static int NumberOfLeadingZeroes(int64_t x)
static inline bool DoEndianSwap(void)

-&#8212; Member function template specialization declarations -&#8212;

static inline bool IsBigEndian(void)
static inline bool IsNetworkOrder(void)
static bool IsNetworkOrderInternal(void)
static void ReverseBytes(unsigned char *inByteArray, unsigned char *inOutByteArray, const unsigned int length)
static void ReverseBytesInPlace(unsigned char *inOutData, const unsigned int length)

Packet

Represents received network data.

struct Packet

This represents a user message from another system.

Public Members

SystemAddress systemAddress

The system that send this packet.

RakNetGUID guid

A unique identifier for the system that sent this packet, regardless of IP address (internal / external / remote system) Only valid once a connection has been established (ID_CONNECTION_REQUEST_ACCEPTED, or ID_NEW_INCOMING_CONNECTION) Until that time, will be UNASSIGNED_RAKNET_GUID

unsigned int length

The length of the data in bytes.

BitSize_t bitSize

The length of the data in bits.

unsigned char *data

The data from the sender.

bool deleteData
bool wasGeneratedLocally

SystemAddress

Network endpoint identifier (IP + port).

The SystemAddress struct contains:

  • address - Union containing IPv4 (addr4) or IPv6 (addr6) address

  • debugPort - Port number for debugging

  • systemIndex - Internal system index

Key methods:

  • ToString() - Convert to string representation

  • FromString() / FromStringExplicitPort() - Parse from string

  • GetPort() / SetPortHostOrder() - Port manipulation

  • IsLoopback() / IsLANAddress() - Address type checks

RakNetGUID

Unique identifier for each peer.

struct RakNetGUID

Uniquely identifies an instance of RakPeer. Use RakPeer::GetGuidFromSystemAddress() and RakPeer::GetSystemAddressFromGuid() to go between SystemAddress and RakNetGUID Use RakPeer::GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS) to get your own GUID

Public Functions

RakNetGUID()
inline explicit RakNetGUID(uint64_t _g)
void ToString(char *dest) const
void ToString(char *dest, size_t destSize) const
bool FromString(const char *source)
inline RakNetGUID &operator=(const RakNetGUID &input)
bool operator==(const RakNetGUID &right) const
bool operator!=(const RakNetGUID &right) const
bool operator>(const RakNetGUID &right) const
bool operator<(const RakNetGUID &right) const

Public Members

uint64_t g
SystemIndex systemIndex

Public Static Functions

static unsigned long ToUint32(const RakNetGUID &g)
static inline int size()

Note

The non-thread-safe RakNetGUID::ToString(void) member (which returned a shared static buffer) was removed in 0.10.0. Use the thread-safe value-type helper MafiaNet::to_string(const RakNetGUID&) instead — see Value-Type GUID Helpers below.

SocketDescriptor

Configuration for network sockets.

struct SocketDescriptor

Describes the local socket to use for RakPeer::Startup.

Public Functions

SocketDescriptor()
SocketDescriptor(unsigned short _port, const char *_hostAddress)

Public Members

unsigned short port

The local port to bind to. Pass 0 to have the OS autoassign a port.

char hostAddress[32]

The local network card address to bind to, such as “127.0.0.1”. Pass an empty string to use INADDR_ANY.

short socketFamily

IP version: For IPV4, use AF_INET (default). For IPV6, use AF_INET6. To autoselect, use AF_UNSPEC. IPV6 is the newer internet protocol. Instead of addresses such as natpunch.slikesoft.com, you may have an address such as fe80::7c:31f7:fec4:27de%14. Encoding takes 16 bytes instead of 4, so IPV6 is less efficient for bandwidth. On the positive side, NAT Punchthrough is not needed and should not be used with IPV6 because there are enough addresses that routers do not need to create address mappings. RakPeer::Startup() will fail if this IP version is not supported.

Pre:

RAKNET_SUPPORT_IPV6 must be set to 1 in RakNetDefines.h for AF_INET6

unsigned short remotePortRakNetWasStartedOn_PS3_PSP2
int chromeInstance
bool blockingSocket
unsigned int extraSocketOptions

XBOX only: set IPPROTO_VDP if you want to use VDP. If enabled, this socket does not support broadcast to 255.255.255.255.

Message Identifiers

Built-in message types are defined in MessageIdentifiers.h.

Enums

enum OutOfBandIdentifiers

Values:

enumerator ID_NAT_ESTABLISH_UNIDIRECTIONAL
enumerator ID_NAT_ESTABLISH_BIDIRECTIONAL
enumerator ID_NAT_TYPE_DETECT
enumerator ID_ROUTER_2_REPLY_TO_SENDER_PORT
enumerator ID_ROUTER_2_REPLY_TO_SPECIFIED_PORT
enumerator ID_ROUTER_2_MINI_PUNCH_REPLY
enumerator ID_ROUTER_2_MINI_PUNCH_REPLY_BOUNCE
enumerator ID_XBOX_360_VOICE
enumerator ID_XBOX_360_GET_NETWORK_ROOM
enumerator ID_XBOX_360_RETURN_NETWORK_ROOM
enumerator ID_NAT_PING
enumerator ID_NAT_PONG
enum DefaultMessageIDTypes

You should not edit the file MessageIdentifiers.h as it is a part of RakNet static library To define your own message id, define an enum following the code example that follows.

enum {
  ID_MYPROJECT_MSG_1 = ID_USER_PACKET_ENUM,
  ID_MYPROJECT_MSG_2, 
   ... 
};

Note

All these enumerations should be casted to (unsigned char) before writing them to MafiaNet::BitStream

Values:

enumerator ID_CONNECTED_PING

These types are never returned to the user. Ping from a connected system. Update timestamps (internal use only)

enumerator ID_UNCONNECTED_PING

Ping from an unconnected system. Reply but do not update timestamps. (internal use only)

enumerator ID_UNCONNECTED_PING_OPEN_CONNECTIONS

Ping from an unconnected system. Only reply if we have open connections. Do not update timestamps. (internal use only)

enumerator ID_CONNECTED_PONG

Pong from a connected system. Update timestamps (internal use only)

enumerator ID_DETECT_LOST_CONNECTIONS

A reliable packet to detect lost connections (internal use only)

enumerator ID_OPEN_CONNECTION_REQUEST_1

C2S: Initial query: Header(1), OfflineMesageID(16), Protocol number(1), Pad(toMTU), sent with no fragment set. If protocol fails on server, returns ID_INCOMPATIBLE_PROTOCOL_VERSION to client

enumerator ID_OPEN_CONNECTION_REPLY_1

S2C: Header(1), OfflineMesageID(16), server GUID(8), HasSecurity(1), Cookie(4, if HasSecurity) , public key (if do security is true), MTU(2). If public key fails on client, returns ID_PUBLIC_KEY_MISMATCH

enumerator ID_OPEN_CONNECTION_REQUEST_2

C2S: Header(1), OfflineMesageID(16), Cookie(4, if HasSecurity is true on the server), clientSupportsSecurity(1 bit), handshakeChallenge (if has security on both server and client), remoteBindingAddress(6), MTU(2), client GUID(8) Connection slot allocated if cookie is valid, server is not full, GUID and IP not already in use.

enumerator ID_OPEN_CONNECTION_REPLY_2

S2C: Header(1), OfflineMesageID(16), server GUID(8), mtu(2), doSecurity(1 bit), handshakeAnswer (if do security is true)

enumerator ID_CONNECTION_REQUEST

C2S: Header(1), GUID(8), Timestamp, HasSecurity(1), Proof(32)

enumerator ID_REMOTE_SYSTEM_REQUIRES_PUBLIC_KEY

RakPeer - Remote system requires secure connections, pass a public key to RakPeerInterface::Connect()

enumerator ID_OUR_SYSTEM_REQUIRES_SECURITY

RakPeer - We passed a public key to RakPeerInterface::Connect(), but the other system did not have security turned on.

enumerator ID_PUBLIC_KEY_MISMATCH

RakPeer - Wrong public key passed to RakPeerInterface::Connect()

enumerator ID_OUT_OF_BAND_INTERNAL

RakPeer - Same as ID_ADVERTISE_SYSTEM, but intended for internal use rather than being passed to the user. Second byte indicates type. Used currently for NAT punchthrough for receiver port advertisement. See ID_NAT_ADVERTISE_RECIPIENT_PORT

enumerator ID_SND_RECEIPT_ACKED

If RakPeerInterface::Send() is called with one of the MafiaNet::Reliability …WithAckReceipt values, then on a later call to RakPeerInterface::Receive() you will get ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS. The message will be 5 bytes long, and bytes 1-4 inclusive will contain a number in native order containing a number that identifies this message. This number will be returned by RakPeerInterface::Send() or RakPeerInterface::SendList(). ID_SND_RECEIPT_ACKED means that the message arrived

enumerator ID_SND_RECEIPT_LOSS

If RakPeerInterface::Send() is called where MafiaNet::Reliability contains MafiaNet::Reliability::UnreliableWithAckReceipt, then on a later call to RakPeerInterface::Receive() you will get ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS. The message will be 5 bytes long, and bytes 1-4 inclusive will contain a number in native order containing a number that identifies this message. This number will be returned by RakPeerInterface::Send() or RakPeerInterface::SendList(). ID_SND_RECEIPT_LOSS means that an ack for the message did not arrive (it may or may not have been delivered, probably not). On disconnect or shutdown, you will not get ID_SND_RECEIPT_LOSS for unsent messages, you should consider those messages as all lost.

enumerator ID_CONNECTION_REQUEST_ACCEPTED

RakPeer - In a client/server environment, our connection request to the server has been accepted.

enumerator ID_CONNECTION_ATTEMPT_FAILED

RakPeer - Sent to the player when a connection request cannot be completed due to inability to connect.

enumerator ID_ALREADY_CONNECTED

RakPeer - Sent a connect request to a system we are currently connected to.

enumerator ID_NEW_INCOMING_CONNECTION

RakPeer - A remote system has successfully connected.

enumerator ID_NO_FREE_INCOMING_CONNECTIONS

RakPeer - The system we attempted to connect to is not accepting new connections.

enumerator ID_DISCONNECTION_NOTIFICATION

RakPeer - The system specified in Packet::systemAddress has disconnected from us. For the client, this would mean the server has shutdown.

enumerator ID_CONNECTION_LOST

RakPeer - Reliable packets cannot be delivered to the system specified in Packet::systemAddress. The connection to that system has been closed.

enumerator ID_CONNECTION_BANNED

RakPeer - We are banned from the system we attempted to connect to.

enumerator ID_INVALID_PASSWORD

RakPeer - The remote system is using a password and has refused our connection because we did not set the correct password.

enumerator ID_INCOMPATIBLE_PROTOCOL_VERSION
enumerator ID_IP_RECENTLY_CONNECTED

RakPeer::SetLimitIPConnectionFrequency()

enumerator ID_TIMESTAMP

RakPeer - The sizeof(RakNetTime) bytes following this byte represent a value which is automatically modified by the difference in system times between the sender and the recipient. Requires that you call SetOccasionalPing.

enumerator ID_UNCONNECTED_PONG

RakPeer - Pong from an unconnected system. First byte is ID_UNCONNECTED_PONG, second sizeof(MafiaNet::TimeMS) bytes is the ping, following bytes is system specific enumeration data. Read using bitstreams

enumerator ID_ADVERTISE_SYSTEM

RakPeer - Inform a remote system of our IP/Port. On the recipient, all data past ID_ADVERTISE_SYSTEM is whatever was passed to the data parameter

enumerator ID_DOWNLOAD_PROGRESS

partTotal (unsigned int), partLength (unsigned int), first part data (length <= MAX_MTU_SIZE). See the three parameters partCount, partTotal and partLength in OnFileProgress in FileListTransferCBInterface.h

enumerator ID_REMOTE_DISCONNECTION_NOTIFICATION

ConnectionGraph2 plugin - In a client/server environment, a client other than ourselves has disconnected gracefully. Packet::systemAddress is modified to reflect the systemAddress of this client.

enumerator ID_REMOTE_CONNECTION_LOST

ConnectionGraph2 plugin - In a client/server environment, a client other than ourselves has been forcefully dropped. Packet::systemAddress is modified to reflect the systemAddress of this client.

enumerator ID_REMOTE_NEW_INCOMING_CONNECTION

ConnectionGraph2 plugin: Bytes 1-4 = count. for (count items) contains {SystemAddress, RakNetGUID, 2 byte ping}.

enumerator ID_FILE_LIST_TRANSFER_HEADER

FileListTransfer plugin - Setup data.

enumerator ID_FILE_LIST_TRANSFER_FILE

FileListTransfer plugin - A file.

enumerator ID_FILE_LIST_REFERENCE_PUSH_ACK
enumerator ID_DDT_DOWNLOAD_REQUEST

DirectoryDeltaTransfer plugin - Request from a remote system for a download of a directory.

enumerator ID_TRANSPORT_STRING

RakNetTransport plugin - Transport provider message, used for remote console.

enumerator ID_REPLICA_MANAGER_CONSTRUCTION

ReplicaManager plugin - Create an object.

enumerator ID_REPLICA_MANAGER_SCOPE_CHANGE

ReplicaManager plugin - Changed scope of an object.

enumerator ID_REPLICA_MANAGER_SERIALIZE

ReplicaManager plugin - Serialized data of an object.

enumerator ID_REPLICA_MANAGER_DOWNLOAD_STARTED

ReplicaManager plugin - New connection, about to send all world objects.

enumerator ID_REPLICA_MANAGER_DOWNLOAD_COMPLETE

ReplicaManager plugin - Finished downloading all serialized objects.

enumerator ID_RAKVOICE_OPEN_CHANNEL_REQUEST

RakVoice plugin - Open a communication channel.

enumerator ID_RAKVOICE_OPEN_CHANNEL_REPLY

RakVoice plugin - Communication channel accepted.

enumerator ID_RAKVOICE_CLOSE_CHANNEL

RakVoice plugin - Close a communication channel.

enumerator ID_RAKVOICE_DATA

RakVoice plugin - Voice data.

enumerator ID_AUTOPATCHER_GET_CHANGELIST_SINCE_DATE

Autopatcher plugin - Get a list of files that have changed since a certain date.

enumerator ID_AUTOPATCHER_CREATION_LIST

Autopatcher plugin - A list of files to create.

enumerator ID_AUTOPATCHER_DELETION_LIST

Autopatcher plugin - A list of files to delete.

enumerator ID_AUTOPATCHER_GET_PATCH

Autopatcher plugin - A list of files to get patches for.

enumerator ID_AUTOPATCHER_PATCH_LIST

Autopatcher plugin - A list of patches for a list of files.

enumerator ID_AUTOPATCHER_REPOSITORY_FATAL_ERROR

Autopatcher plugin - Returned to the user: An error from the database repository for the autopatcher.

enumerator ID_AUTOPATCHER_CANNOT_DOWNLOAD_ORIGINAL_UNMODIFIED_FILES

Autopatcher plugin - Returned to the user: The server does not allow downloading unmodified game files.

enumerator ID_AUTOPATCHER_FINISHED_INTERNAL

Autopatcher plugin - Finished getting all files from the autopatcher.

enumerator ID_AUTOPATCHER_FINISHED
enumerator ID_AUTOPATCHER_RESTART_APPLICATION

Autopatcher plugin - Returned to the user: You must restart the application to finish patching.

enumerator ID_NAT_PUNCHTHROUGH_REQUEST

NATPunchthrough plugin: internal.

enumerator ID_NAT_CONNECT_AT_TIME

NATPunchthrough plugin: internal.

NATPunchthrough plugin: internal NATPunchthrough plugin: internal

enumerator ID_NAT_GET_MOST_RECENT_PORT

NATPunchthrough plugin: internal.

enumerator ID_NAT_CLIENT_READY

NATPunchthrough plugin: internal.

enumerator ID_NAT_TARGET_NOT_CONNECTED

NATPunchthrough plugin: internal.

NATPunchthrough plugin: Destination system is not connected to the server. Bytes starting at offset 1 contains the RakNetGUID destination field of NatPunchthroughClient::OpenNAT().

enumerator ID_NAT_TARGET_UNRESPONSIVE

NATPunchthrough plugin: Destination system is not responding to ID_NAT_GET_MOST_RECENT_PORT. Possibly the plugin is not installed. Bytes starting at offset 1 contains the RakNetGUID destination field of NatPunchthroughClient::OpenNAT().

enumerator ID_NAT_CONNECTION_TO_TARGET_LOST

NATPunchthrough plugin: The server lost the connection to the destination system while setting up punchthrough. Possibly the plugin is not installed. Bytes starting at offset 1 contains the RakNetGUID destination field of NatPunchthroughClient::OpenNAT().

enumerator ID_NAT_ALREADY_IN_PROGRESS

NATPunchthrough plugin: This punchthrough is already in progress. Possibly the plugin is not installed. Bytes starting at offset 1 contains the RakNetGUID destination field of NatPunchthroughClient::OpenNAT().

enumerator ID_NAT_PUNCHTHROUGH_FAILED

NATPunchthrough plugin: This message is generated on the local system, and does not come from the network. packet::guid contains the destination field of NatPunchthroughClient::OpenNAT(). Byte 1 contains 1 if you are the sender, 0 if not

enumerator ID_NAT_PUNCHTHROUGH_SUCCEEDED

NATPunchthrough plugin: Punchthrough succeeded. See packet::systemAddress and packet::guid. Byte 1 contains 1 if you are the sender, 0 if not. You can now use RakPeer::Connect() or other calls to communicate with this system.

enumerator ID_READY_EVENT_SET

ReadyEvent plugin - Set the ready state for a particular system First 4 bytes after the message contains the id

enumerator ID_READY_EVENT_UNSET

ReadyEvent plugin - Unset the ready state for a particular system First 4 bytes after the message contains the id

enumerator ID_READY_EVENT_ALL_SET

All systems are in state ID_READY_EVENT_SET First 4 bytes after the message contains the id

enumerator ID_READY_EVENT_QUERY
enumerator ID_LOBBY_GENERAL

Lobby packets. Second byte indicates type.

enumerator ID_RPC_REMOTE_ERROR
enumerator ID_RPC_PLUGIN

Plugin based replacement for RPC system.

enumerator ID_FILE_LIST_REFERENCE_PUSH

FileListTransfer transferring large files in chunks that are read only when needed, to save memory.

enumerator ID_READY_EVENT_FORCE_ALL_SET

Force the ready event to all set.

enumerator ID_ROOMS_EXECUTE_FUNC

Rooms function.

enumerator ID_ROOMS_LOGON_STATUS
enumerator ID_ROOMS_HANDLE_CHANGE
enumerator ID_LOBBY2_SEND_MESSAGE

Lobby2 message.

enumerator ID_LOBBY2_SERVER_ERROR
enumerator ID_FCM2_NEW_HOST

Informs user of a new host GUID. Packet::Guid contains this new host RakNetGuid. The old host can be read out using BitStream->Read(RakNetGuid) starting on byte 1 This is not returned until connected to a remote system If the oldHost is UNASSIGNED_RAKNET_GUID, then this is the first time the host has been determined

enumerator ID_FCM2_REQUEST_FCMGUID
enumerator ID_FCM2_RESPOND_CONNECTION_COUNT
enumerator ID_FCM2_INFORM_FCMGUID
enumerator ID_FCM2_UPDATE_MIN_TOTAL_CONNECTION_COUNT
enumerator ID_FCM2_VERIFIED_JOIN_START

A remote system (not necessarily the host) called FullyConnectedMesh2::StartVerifiedJoin() with our system as the client Use FullyConnectedMesh2::GetVerifiedJoinRequiredProcessingList() to read systems For each system, attempt NatPunchthroughClient::OpenNAT() and/or RakPeerInterface::Connect() When this has been done for all systems, the remote system will automatically be informed of the results

See also

FullyConnectedMesh2::StartVerifiedJoin()

Note

Only the designated client gets this message

Note

You won’t get this message if you are already connected to all target systems

Note

If you fail to connect to a system, this does not automatically mean you will get ID_FCM2_VERIFIED_JOIN_FAILED as that system may have been shutting down from the host too

enumerator ID_FCM2_VERIFIED_JOIN_CAPABLE
enumerator ID_FCM2_VERIFIED_JOIN_FAILED

Client failed to connect to a required systems notified via FullyConnectedMesh2::StartVerifiedJoin() RakPeerInterface::CloseConnection() was automatically called for all systems connected due to ID_FCM2_VERIFIED_JOIN_START Programmer should inform the player via the UI that they cannot join this session, and to choose a different session

Note

Server normally sends us this message, however if connection to the server was lost, message will be returned locally

Note

Only the designated client gets this message

enumerator ID_FCM2_VERIFIED_JOIN_ACCEPTED

The system that called StartVerifiedJoin() got ID_FCM2_VERIFIED_JOIN_CAPABLE from the client and then called RespondOnVerifiedJoinCapable() with true AddParticipant() has automatically been called for this system Use GetVerifiedJoinAcceptedAdditionalData() to read any additional data passed to RespondOnVerifiedJoinCapable()

See also

RespondOnVerifiedJoinCapable()

Note

All systems in the mesh get this message

enumerator ID_FCM2_VERIFIED_JOIN_REJECTED

The system that called StartVerifiedJoin() got ID_FCM2_VERIFIED_JOIN_CAPABLE from the client and then called RespondOnVerifiedJoinCapable() with false CloseConnection() has been automatically called for each system connected to since ID_FCM2_VERIFIED_JOIN_START. The connection is NOT automatically closed to the original host that sent StartVerifiedJoin() Use GetVerifiedJoinRejectedAdditionalData() to read any additional data passed to RespondOnVerifiedJoinCapable()

See also

RespondOnVerifiedJoinCapable()

Note

Only the designated client gets this message

enumerator ID_UDP_PROXY_GENERAL

UDP proxy messages. Second byte indicates type.

enumerator ID_SQLite3_EXEC

SQLite3Plugin - execute.

enumerator ID_SQLite3_UNKNOWN_DB

SQLite3Plugin - Remote database is unknown.

enumerator ID_SQLLITE_LOGGER

Events happening with SQLiteClientLoggerPlugin.

enumerator ID_NAT_TYPE_DETECTION_REQUEST

Sent to NatTypeDetectionServer.

enumerator ID_NAT_TYPE_DETECTION_RESULT

Sent to NatTypeDetectionClient. Byte 1 contains the type of NAT detected.

enumerator ID_ROUTER_2_INTERNAL

Used by the router2 plugin.

enumerator ID_ROUTER_2_FORWARDING_NO_PATH

No path is available or can be established to the remote system Packet::guid contains the endpoint guid that we were trying to reach

enumerator ID_ROUTER_2_FORWARDING_ESTABLISHED

You can now call connect, ping, or other operations to the destination system.

Connect as follows:

MafiaNet::BitStream bs(packet->data, packet->length, false);
bs.IgnoreBytes(sizeof(MessageID));
RakNetGUID endpointGuid;
bs.Read(endpointGuid);
unsigned short sourceToDestPort;
bs.Read(sourceToDestPort);
char ipAddressString[32];
packet->systemAddress.ToString(false, ipAddressString);
rakPeerInterface->Connect(ipAddressString, sourceToDestPort, 0,0);
enumerator ID_ROUTER_2_REROUTED

The IP address for a forwarded connection has changed Read endpointGuid and port as per ID_ROUTER_2_FORWARDING_ESTABLISHED

enumerator ID_TEAM_BALANCER_INTERNAL
enumerator ID_TEAM_BALANCER_REQUESTED_TEAM_FULL

Cannot switch to the desired team because it is full. However, if someone on that team leaves, you will get ID_TEAM_BALANCER_TEAM_ASSIGNED later. For TeamBalancer: Byte 1 contains the team you requested to join. Following bytes contain NetworkID of which member

enumerator ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED

Cannot switch to the desired team because all teams are locked. However, if someone on that team leaves, you will get ID_TEAM_BALANCER_SET_TEAM later. For TeamBalancer: Byte 1 contains the team you requested to join.

enumerator ID_TEAM_BALANCER_TEAM_REQUESTED_CANCELLED
enumerator ID_TEAM_BALANCER_TEAM_ASSIGNED

Team balancer plugin informing you of your team. Byte 1 contains the team you requested to join. Following bytes contain NetworkID of which member.

enumerator ID_LIGHTSPEED_INTEGRATION

Gamebryo Lightspeed integration.

enumerator ID_XBOX_LOBBY

XBOX integration.

enumerator ID_TWO_WAY_AUTHENTICATION_INCOMING_CHALLENGE_SUCCESS

The password we used to challenge the other system passed, meaning the other system has called TwoWayAuthentication::AddPassword() with the same password we passed to TwoWayAuthentication::Challenge() You can read the identifier used to challenge as follows: MafiaNet::BitStream bs(packet->data, packet->length, false); bs.IgnoreBytes(sizeof(MafiaNet::MessageID)); MafiaNet::RakString password; bs.Read(password);

enumerator ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_SUCCESS
enumerator ID_TWO_WAY_AUTHENTICATION_INCOMING_CHALLENGE_FAILURE

A remote system sent us a challenge using TwoWayAuthentication::Challenge(), and the challenge failed. If the other system must pass the challenge to stay connected, you should call RakPeer::CloseConnection() to terminate the connection to the other system.

enumerator ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_FAILURE

The other system did not add the password we used to TwoWayAuthentication::AddPassword() You can read the identifier used to challenge as follows: MafiaNet::BitStream bs(packet->data, packet->length, false); bs.IgnoreBytes(sizeof(MessageID)); MafiaNet::RakString password; bs.Read(password);

enumerator ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_TIMEOUT

The other system did not respond within a timeout threshhold. Either the other system is not running the plugin or the other system was blocking on some operation for a long time. You can read the identifier used to challenge as follows: MafiaNet::BitStream bs(packet->data, packet->length, false); bs.IgnoreBytes(sizeof(MessageID)); MafiaNet::RakString password; bs.Read(password);

enumerator ID_TWO_WAY_AUTHENTICATION_NEGOTIATION
enumerator ID_CLOUD_POST_REQUEST

CloudClient / CloudServer.

enumerator ID_CLOUD_RELEASE_REQUEST
enumerator ID_CLOUD_GET_REQUEST
enumerator ID_CLOUD_GET_RESPONSE
enumerator ID_CLOUD_UNSUBSCRIBE_REQUEST
enumerator ID_CLOUD_SERVER_TO_SERVER_COMMAND
enumerator ID_CLOUD_SUBSCRIPTION_NOTIFICATION
enumerator ID_LIB_VOICE
enumerator ID_RELAY_PLUGIN
enumerator ID_NAT_REQUEST_BOUND_ADDRESSES
enumerator ID_NAT_RESPOND_BOUND_ADDRESSES
enumerator ID_FCM2_UPDATE_USER_CONTEXT
enumerator ID_RESERVED_3
enumerator ID_RESERVED_4
enumerator ID_RESERVED_5
enumerator ID_RESERVED_6
enumerator ID_RESERVED_7
enumerator ID_RESERVED_8
enumerator ID_RESERVED_9
enumerator ID_USER_PACKET_ENUM

Enumerations

Priority

Scoped enum class MafiaNet::Priority (Immediate, High, Medium, Low). Replaces the removed unscoped PacketPriority C enum; enumerator order — and therefore the underlying integer values — is unchanged.

enum class MafiaNet::Priority

These enumerations are used to describe when packets are delivered.

Values:

enumerator Immediate

The highest possible priority. These message trigger sends immediately, and are generally not buffered or aggregated into a single datagram.

enumerator High

For every 2 Immediate messages, 1 High will be sent. Messages at this priority and lower are buffered to be sent in groups at 10 millisecond intervals to reduce UDP overhead and better measure congestion control.

enumerator Medium

For every 2 High messages, 1 Medium will be sent. Messages at this priority and lower are buffered to be sent in groups at 10 millisecond intervals to reduce UDP overhead and better measure congestion control.

enumerator Low

For every 2 Medium messages, 1 Low will be sent. Messages at this priority and lower are buffered to be sent in groups at 10 millisecond intervals to reduce UDP overhead and better measure congestion control.

Reliability

Scoped enum class MafiaNet::Reliability (Unreliable, UnreliableSequenced, Reliable, ReliableOrdered, ReliableSequenced, UnreliableWithAckReceipt, ReliableWithAckReceipt, ReliableOrderedWithAckReceipt). Replaces the removed unscoped PacketReliability C enum; enumerator order is preserved, so the 3-bit reliability wire field stays compatible.

enum class MafiaNet::Reliability

These enumerations are used to describe how packets are delivered.

Note

Note to self: I write this with 3 bits in the stream. If I add more remember to change that

Note

In ReliabilityLayer::WriteToBitStreamFromInternalPacket I assume there are 5 major types

Note

Do not reorder, I check on >= UnreliableWithAckReceipt

Values:

enumerator Unreliable

Same as regular UDP, except that it will also discard duplicate datagrams. RakNet adds (6 to 17) + 21 bits of overhead, 16 of which is used to detect duplicate packets and 6 to 17 of which is used for message length.

enumerator UnreliableSequenced

Regular UDP with a sequence counter. Out of order messages will be discarded. Sequenced and ordered messages sent on the same channel will arrive in the order sent.

enumerator Reliable

The message is sent reliably, but not necessarily in any order. Same overhead as Unreliable.

enumerator ReliableOrdered

This message is reliable and will arrive in the order you sent it. Messages will be delayed while waiting for out of order messages. Same overhead as UnreliableSequenced. Sequenced and ordered messages sent on the same channel will arrive in the order sent.

enumerator ReliableSequenced

This message is reliable and will arrive in the sequence you sent it. Out or order messages will be dropped. Same overhead as UnreliableSequenced. Sequenced and ordered messages sent on the same channel will arrive in the order sent.

enumerator UnreliableWithAckReceipt

Same as Unreliable, however the user will get either ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS based on the result of sending this message when calling RakPeerInterface::Receive(). Bytes 1-4 will contain the number returned from the Send() function. On disconnect or shutdown, all messages not previously acked should be considered lost.

enumerator ReliableWithAckReceipt

Same as Reliable. The user will also get ID_SND_RECEIPT_ACKED after the message is delivered when calling RakPeerInterface::Receive(). ID_SND_RECEIPT_ACKED is returned when the message arrives, not necessarily the order when it was sent. Bytes 1-4 will contain the number returned from the Send() function. On disconnect or shutdown, all messages not previously acked should be considered lost. This does not return ID_SND_RECEIPT_LOSS.

enumerator ReliableOrderedWithAckReceipt

Same as ReliableOrdered. The user will also get ID_SND_RECEIPT_ACKED after the message is delivered when calling RakPeerInterface::Receive(). ID_SND_RECEIPT_ACKED is returned when the message arrives, not necessarily the order when it was sent. Bytes 1-4 will contain the number returned from the Send() function. On disconnect or shutdown, all messages not previously acked should be considered lost. This does not return ID_SND_RECEIPT_LOSS.

StartupResult

enum MafiaNet::StartupResult

Values:

enumerator RAKNET_STARTED
enumerator RAKNET_ALREADY_STARTED
enumerator INVALID_SOCKET_DESCRIPTORS
enumerator INVALID_MAX_CONNECTIONS
enumerator SOCKET_FAMILY_NOT_SUPPORTED
enumerator SOCKET_PORT_ALREADY_IN_USE
enumerator SOCKET_FAILED_TO_BIND
enumerator SOCKET_FAILED_TEST_SEND
enumerator PORT_CANNOT_BE_ZERO
enumerator FAILED_TO_CREATE_NETWORK_THREAD
enumerator COULD_NOT_GENERATE_GUID
enumerator STARTUP_OTHER_FAILURE

ConnectionAttemptResult

enum MafiaNet::ConnectionAttemptResult

Values:

enumerator CONNECTION_ATTEMPT_STARTED
enumerator INVALID_PARAMETER
enumerator CANNOT_RESOLVE_DOMAIN_NAME
enumerator ALREADY_CONNECTED_TO_ENDPOINT
enumerator CONNECTION_ATTEMPT_ALREADY_IN_PROGRESS
enumerator SECURITY_INITIALIZATION_FAILED

Umbrella Header

#include "mafianet/mafianet.h" pulls in the core public API — the peer interface, types, message IDs, Priority / Reliability, BitStream, GetTime, statistics, the canonical aliases, and the RAII handles — behind a single include, so the common client/server path needs only one #include:

#include "mafianet/mafianet.h"

It is purely additive: the granular per-feature headers remain for advanced users. Encryption headers are intentionally omitted — connection security stays opt-in via RakPeerInterface::InitializeSecurity() (see Secure Connections).

Canonical Type Aliases

mafianet/aliases.h (also pulled in by the umbrella header) provides canonical MafiaNet names over the legacy RakNet-named public types. They are using aliases denoting the exact same types/objects, so old and new names interoperate freely:

Canonical alias

Legacy name

MafiaNet::PeerInterface

RakPeerInterface

MafiaNet::Guid

RakNetGUID

MafiaNet::Statistics

RakNetStatistics

MafiaNet::UnassignedGuid

UNASSIGNED_RAKNET_GUID

RAII Handles (Peer / PacketPtr)

mafianet/PeerHandle.h (exported from the umbrella header) provides two RAII owners that remove manual DestroyInstance / DeallocatePacket bookkeeping:

  • MafiaNet::Peer owns a RakPeerInterface instance and destroys it on scope exit.

  • MafiaNet::PacketPtr owns a received Packet and deallocates it automatically.

#include "mafianet/mafianet.h"

MafiaNet::Peer peer;                         // owns a RakPeerInterface
MafiaNet::SocketDescriptor sd(60000, 0);
peer->Startup(8, &sd, 1);                    // operator-> forwards to the interface

while (running) {
    MafiaNet::PacketPtr packet = peer.receive();   // owns the Packet
    if (!packet) continue;
    switch (packet->data[0]) {
        // ... handle message ...
    }
    // no DeallocatePacket / DestroyInstance — destructors handle it
}

Value-Type GUID Helpers

mafianet/guid_util.h provides modern, thread-safe value-type accessors:

  • std::string MafiaNet::to_string(const RakNetGUID&) — owns its buffer and is thread-safe (replaces the removed RakNetGUID::ToString(void)).

  • std::optional<SystemAddress> MafiaNet::connected_address(RakPeerInterface&, const RakNetGUID&) — maps the UNASSIGNED_SYSTEM_ADDRESS sentinel to std::nullopt.

printf("Peer %s connected\n", MafiaNet::to_string(packet->guid).c_str());

if (auto addr = MafiaNet::connected_address(*peer, guid))
    printf("address: %s\n", addr->ToString());