libpromeki main
PROfessional MEdia toolKIt
 
Loading...
Searching...
No Matches
RawSocket Class Reference

Raw Ethernet frame socket. More...

#include <rawsocket.h>

Inheritance diagram for RawSocket:
Collaboration diagram for RawSocket:

Public Member Functions

 RawSocket (ObjectBase *parent=nullptr)
 Constructs a RawSocket.
 
 ~RawSocket () override
 Destructor.
 
void setInterface (const String &interfaceName)
 Sets the network interface to bind to.
 
const Stringinterface () const
 Returns the configured interface name.
 
void setProtocol (uint16_t ethertype)
 Sets the Ethernet protocol filter.
 
uint16_t protocol () const
 Returns the configured protocol filter.
 
Error open (OpenMode mode) override
 Opens the raw socket.
 
Error close () override
 Closes the socket.
 
bool isOpen () const override
 Returns true if the socket is open.
 
int64_t read (void *data, int64_t maxSize) override
 Reads a raw Ethernet frame.
 
int64_t write (const void *data, int64_t maxSize) override
 Writes a raw Ethernet frame.
 
Error setPromiscuous (bool enable)
 Enables or disables promiscuous mode.
 
- Public Member Functions inherited from AbstractSocket
 AbstractSocket (SocketType type, ObjectBase *parent=nullptr)
 Constructs an AbstractSocket.
 
virtual ~AbstractSocket ()
 Destructor. Closes the socket if open.
 
SocketType socketType () const
 Returns the socket type.
 
SocketState state () const
 Returns the current socket state.
 
Error bind (const SocketAddress &address)
 Binds the socket to a local address.
 
Error connectToHost (const SocketAddress &address)
 Initiates a connection to a remote host.
 
void disconnectFromHost ()
 Disconnects from the remote host.
 
SocketAddress localAddress () const
 Returns the local address the socket is bound to.
 
SocketAddress peerAddress () const
 Returns the address of the connected peer.
 
Error waitForConnected (unsigned int timeoutMs=0)
 Blocks until the socket is connected or timeout.
 
int socketDescriptor () const
 Returns the raw socket file descriptor.
 
void setSocketDescriptor (int fd)
 Adopts an existing file descriptor as the socket.
 
Error setSocketOption (int level, int option, int value)
 Sets a raw socket option via setsockopt().
 
Result< int > socketOption (int level, int option) const
 Gets a raw socket option via getsockopt().
 
bool isSequential () const override
 Returns true — sockets are sequential (non-seekable).
 
 PROMEKI_SIGNAL (connected)
 Emitted when a connection is established.
 
 PROMEKI_SIGNAL (disconnected)
 Emitted when the socket is disconnected.
 
 PROMEKI_SIGNAL (stateChanged, SocketState)
 Emitted when the socket state changes.
 
- Public Member Functions inherited from IODevice
 IODevice (ObjectBase *parent=nullptr)
 Constructs an IODevice.
 
virtual ~IODevice ()
 Destructor.
 
virtual void flush ()
 Flushes any buffered output data to the underlying device.
 
virtual int64_t bytesAvailable () const
 Returns the number of bytes available for reading.
 
virtual bool waitForReadyRead (unsigned int timeoutMs=0)
 Waits until data is available for reading or timeout.
 
virtual bool waitForBytesWritten (unsigned int timeoutMs=0)
 Waits until all pending data has been written or timeout.
 
virtual Error seek (int64_t pos)
 Seeks to the given byte offset from the beginning.
 
virtual int64_t pos () const
 Returns the current read/write position.
 
virtual Result< int64_tsize () const
 Returns the total size of the device in bytes.
 
virtual bool atEnd () const
 Returns true if the current position is at the end.
 
OpenMode openMode () const
 Returns the current open mode.
 
bool isReadable () const
 Returns true if the device is readable.
 
bool isWritable () const
 Returns true if the device is writable.
 
Error error () const
 Returns the current error state.
 
void clearError ()
 Clears the error state to Ok.
 
 PROMEKI_SIGNAL (readyRead)
 Emitted when data is available for reading.
 
 PROMEKI_SIGNAL (bytesWritten, int64_t)
 Emitted when bytes have been written.
 
 PROMEKI_SIGNAL (errorOccurred, Error)
 Emitted when an error occurs.
 
 PROMEKI_SIGNAL (aboutToClose)
 Emitted just before the device is closed.
 
- Public Member Functions inherited from ObjectBase
 ObjectBase (ObjectBase *p=nullptr)
 Default ObjectBase constructor.
 
virtual ~ObjectBase ()
 Destructor. Emits aboutToDestroy, detaches from parent, and destroys children.
 
ObjectBaseparent () const
 Returns the parent object, if one. nullptr if none.
 
void setParent (ObjectBase *p)
 Sets the parent of this object. If the object already has a parent, it will be removed as a child from the old parent and added as a child to the new one.
 
const ObjectBaseListchildList () const
 Returns a list of children of this object.
 
template<typename... Args>
int registerSlot (Slot< Args... > *slot)
 Registers a slot with this object and assigns it an ID.
 
EventLoopeventLoop () const
 Returns the EventLoop this object is affiliated with.
 
void moveToThread (EventLoop *loop)
 Changes the EventLoop affinity of this object.
 
int startTimer (unsigned int intervalMs, bool singleShot=false)
 Starts a timer on this object's EventLoop.
 
void stopTimer (int timerId)
 Stops a timer previously started with startTimer().
 
template<typename... Args>
PROMEKI_NAMESPACE_BEGIN void connect (Signal< Args... > *signal, Slot< Args... > *slot)
 

Additional Inherited Members

- Public Types inherited from AbstractSocket
enum  SocketType { TcpSocketType , UdpSocketType , RawSocketType }
 The type of socket. More...
 
enum  SocketState {
  Unconnected , Connecting , Connected , Bound ,
  Closing , Listening
}
 The current state of the socket. More...
 
- Public Types inherited from IODevice
enum  OpenMode {
  NotOpen = 0x00 , ReadOnly = 0x01 , WriteOnly = 0x02 , ReadWrite = ReadOnly | WriteOnly ,
  Append = 0x04 | WriteOnly
}
 Mode flags controlling how a device is opened. More...
 
- Public Types inherited from ObjectBase
using SlotVariantFunc = std::function< void(const VariantList &)>
 Function type for invoking a slot with a list of Variants.
 
- Static Public Member Functions inherited from ObjectBase
static const MetaInfometaInfo ()
 Returns the MetaInfo for the ObjectBase class.
 
template<typename... Args>
static void connect (Signal< Args... > *signal, Slot< Args... > *slot)
 connects a signal and slot together. This function assumes both the signal and slot exist in a ObjectBase or derived object
 
- Public Attributes inherited from ObjectBase
Signal< ObjectBase * > aboutToDestroySignal = Signal< ObjectBase * >(this, aboutToDestroySignalName)
 
- Static Public Attributes inherited from ObjectBase
static constexpr const charaboutToDestroySignalName = PROMEKI_STRINGIFY( aboutToDestroy ) "(" PROMEKI_STRINGIFY_ARGS( ObjectBase * ) ")"
 
static SignalMeta aboutToDestroySignalMeta = SignalMeta(metaInfo(), aboutToDestroySignalName)
 
- Protected Member Functions inherited from AbstractSocket
Error createSocket (int domain, int type, int protocol=0)
 Creates the underlying socket descriptor.
 
void closeSocket ()
 Closes the socket descriptor.
 
Error setNonBlocking (bool enable)
 Sets the socket to non-blocking mode.
 
void updateLocalAddress ()
 Updates the local address from the socket descriptor.
 
void setState (SocketState state)
 Sets the socket state and emits stateChanged.
 
- Protected Member Functions inherited from IODevice
void setOpenMode (OpenMode mode)
 Sets the open mode.
 
void setError (const Error &err)
 Sets the error state and emits errorOccurred.
 
- Protected Member Functions inherited from ObjectBase
ObjectBasesignalSender ()
 Returns the ObjectBase that emitted the signal currently being handled.
 
virtual void event (Event *e)
 Called by EventLoop to deliver events to this object.
 
virtual void timerEvent (TimerEvent *e)
 Called when a timer fires for this object.
 
- Protected Attributes inherited from AbstractSocket
int _fd = -1
 Socket file descriptor.
 
SocketState _state = Unconnected
 Current socket state.
 
SocketType _type
 Socket type.
 
SocketAddress _localAddress
 Local bound address.
 
SocketAddress _peerAddress
 Connected peer address.
 

Detailed Description

Raw Ethernet frame socket.

RawSocket provides send/receive access to raw Ethernet frames. On Linux this uses AF_PACKET/SOCK_RAW. On macOS, BPF would be used (not yet implemented).

Opening a raw socket requires root privileges or the CAP_NET_RAW capability. The open() method returns Error::PermissionDenied if insufficient permissions are available.

This class must only be used from the thread that created it (or moved to via moveToThread()).

Example
sock.setInterface("eth0");
sock.setProtocol(0x0800); // IPv4
Lightweight error code wrapper for the promeki library.
Definition error.h:39
@ ReadWrite
Open for reading and writing.
Definition iodevice.h:37
Dynamic array container wrapping std::vector.
Definition list.h:40
Raw Ethernet frame socket.
Definition rawsocket.h:37

Constructor & Destructor Documentation

◆ RawSocket()

RawSocket::RawSocket ( ObjectBase parent = nullptr)

Constructs a RawSocket.

Parameters
parentThe parent object, or nullptr.

Member Function Documentation

◆ close()

Error RawSocket::close ( )
overridevirtual

Closes the socket.

Returns
Error::Ok on success, or an error on failure.

Implements IODevice.

◆ isOpen()

bool RawSocket::isOpen ( ) const
inlineoverridevirtual

Returns true if the socket is open.

Implements IODevice.

◆ open()

Error RawSocket::open ( OpenMode  mode)
overridevirtual

Opens the raw socket.

Creates an AF_PACKET/SOCK_RAW socket on Linux. If an interface was set, the socket is bound to that interface.

Parameters
modeThe open mode (typically ReadWrite).
Returns
Error::Ok on success, Error::PermissionDenied if insufficient privileges, or another error.

Implements IODevice.

◆ read()

int64_t RawSocket::read ( void data,
int64_t  maxSize 
)
overridevirtual

Reads a raw Ethernet frame.

Parameters
dataBuffer to read into.
maxSizeMaximum bytes to read.
Returns
Bytes read, or -1 on error.

Implements IODevice.

◆ setInterface()

void RawSocket::setInterface ( const String interfaceName)
inline

Sets the network interface to bind to.

Must be called before open().

Parameters
interfaceNameThe interface name (e.g. "eth0").

◆ setPromiscuous()

Error RawSocket::setPromiscuous ( bool  enable)

Enables or disables promiscuous mode.

Parameters
enableTrue to enable promiscuous mode.
Returns
Error::Ok on success, or an error on failure.

◆ setProtocol()

void RawSocket::setProtocol ( uint16_t  ethertype)
inline

Sets the Ethernet protocol filter.

Only frames matching this EtherType are received. Must be called before open(). Common values:

  • 0x0800 — IPv4
  • 0x0806 — ARP
  • 0x86DD — IPv6
  • ETH_P_ALL (0x0003) — all protocols
Parameters
ethertypeThe EtherType value.

◆ write()

int64_t RawSocket::write ( const void data,
int64_t  maxSize 
)
overridevirtual

Writes a raw Ethernet frame.

Parameters
dataThe complete Ethernet frame to send.
maxSizeFrame size in bytes.
Returns
Bytes sent, or -1 on error.

Implements IODevice.


The documentation for this class was generated from the following file: