INET Framework for OMNeT++/OMNEST
inet::TcpSocket Class Reference

TcpSocket is a convenience class, to make it easier to manage TCP connections from your application models. More...

#include <TcpSocket.h>

Inheritance diagram for inet::TcpSocket:
inet::ISocket

Classes

class  ICallback
 Callback interface for TCP sockets, see setCallback() and processMessage() for more info. More...
 
class  ReceiveQueueBasedCallback
 

Public Types

enum  State {
  NOT_BOUND, BOUND, LISTENING, CONNECTING,
  CONNECTED, PEER_CLOSED, LOCALLY_CLOSED, CLOSED,
  SOCKERROR
}
 

Public Member Functions

 TcpSocket ()
 Constructor. More...
 
 TcpSocket (cMessage *msg)
 Constructor, to be used with forked sockets (see listen()). More...
 
 TcpSocket (TcpAvailableInfo *availableInfo)
 Constructor, to be used with forked sockets (see listen()). More...
 
 ~TcpSocket ()
 Destructor. More...
 
int getSocketId () const override
 Returns the internal connection Id. More...
 
ChunkQueuegetReceiveQueue ()
 
void * getUserData () const
 
void setUserData (void *userData)
 
TcpSocket::State getState () const
 Returns the socket state, one of NOT_BOUND, CLOSED, LISTENING, CONNECTING, CONNECTED, etc. More...
 
void setState (TcpSocket::State state)
 
Getter functions
L3Address getLocalAddress () const
 
int getLocalPort () const
 
L3Address getRemoteAddress () const
 
int getRemotePort () const
 
Opening and closing connections, sending data
void setOutputGate (cGate *toTcp)
 Sets the gate on which to send to TCP. More...
 
void bind (int localPort)
 Bind the socket to a local port number. More...
 
void bind (L3Address localAddr, int localPort)
 Bind the socket to a local port number and IP address (useful with multi-homing). More...
 
const char * getTCPAlgorithmClass () const
 Returns the current tcpAlgorithmClass parameter. More...
 
void setTCPAlgorithmClass (const char *tcpAlgorithmClass)
 Sets the tcpAlgorithmClass parameter of the next connect() or listen() call. More...
 
void listen ()
 Initiates passive OPEN, creating a "forking" connection that will listen on the port you bound the socket to. More...
 
void listenOnce ()
 Initiates passive OPEN to create a non-forking listening connection. More...
 
void accept (int socketId)
 Accepts a new incoming connection reported as available. More...
 
void connect (L3Address remoteAddr, int remotePort)
 Active OPEN to the given remote socket. More...
 
virtual void send (Packet *msg) override
 Sends data packet. More...
 
void sendCommand (Request *msg)
 Sends command. More...
 
void close () override
 Closes the local end of the connection. More...
 
void abort ()
 Aborts the connection. More...
 
virtual void destroy () override
 Destroy the connection. More...
 
void requestStatus ()
 Causes TCP to reply with a fresh TcpStatusInfo, attached to a dummy message as getControlInfo(). More...
 
void setTimeToLive (int ttl)
 Set the TTL (Ipv6: Hop Limit) field on sent packets. More...
 
void setDscp (short dscp)
 Sets the Ipv4 / Ipv6 dscp fields of packets sent from the TCP socket. More...
 
void setTos (short tos)
 Sets the Ipv4 Type of Service / Ipv6 Traffic Class fields of packets sent from the TCP socket. More...
 
void renewSocket ()
 Required to re-connect with a "used" TcpSocket object. More...
 
virtual bool isOpen () const override
 
Handling of messages arriving from TCP
virtual bool belongsToSocket (cMessage *msg) const override
 Returns true if the message belongs to this socket instance (message has a TcpCommand as getControlInfo(), and the connId in it matches that of the socket.) More...
 
void setCallback (ICallback *cb)
 Sets a callback object, to be used with processMessage(). More...
 
void processMessage (cMessage *msg) override
 Examines the message (which should have arrived from TCP), updates socket state, and if there is a callback object installed (see setCallback(), class ICallback), dispatches to the appropriate method. More...
 
- Public Member Functions inherited from inet::ISocket
virtual ~ISocket ()
 

Static Public Member Functions

static const char * stateName (TcpSocket::State state)
 Returns name of socket state code returned by getState(). More...
 

Protected Member Functions

void sendToTcp (cMessage *msg, int c=-1)
 
void listen (bool fork)
 

Protected Attributes

int connId = -1
 
State sockstate = NOT_BOUND
 
L3Address localAddr
 
int localPrt = -1
 
L3Address remoteAddr
 
int remotePrt = -1
 
ICallbackcb = nullptr
 
void * userData = nullptr
 
cGate * gateToTcp = nullptr
 
std::string tcpAlgorithmClass
 
ChunkQueuereceiveQueue = nullptr
 

Detailed Description

TcpSocket is a convenience class, to make it easier to manage TCP connections from your application models.

You'd have one (or more) TcpSocket object(s) in your application simple module class, and call its member functions (bind(), listen(), connect(), etc.) to open, close or abort a TCP connection.

TcpSocket chooses and remembers the connId for you, assembles and sends command packets (such as OPEN_ACTIVE, OPEN_PASSIVE, CLOSE, ABORT, etc.) to TCP, and can also help you deal with packets and notification messages arriving from TCP.

A session which opens a connection from local port 1000 to 10.0.0.2:2000, sends 16K of data and closes the connection may be as simple as this (the code can be placed in your handleMessage() or activity()):

  TcpSocket socket;
  socket.connect(Address("10.0.0.2"), 2000);
  msg = new cMessage("data1");
  msg->setByteLength(16*1024);  // 16K
  socket.send(msg);
  socket.close();

Dealing with packets and notification messages coming from TCP is somewhat more cumbersome. Basically you have two choices: you either process those messages yourself, or let TcpSocket do part of the job. For the latter, you give TcpSocket a callback object on which it'll invoke the appropriate member functions: socketEstablished(), socketDataArrived(), socketFailure(), socketPeerClosed(), etc (these are methods of TcpSocket::ICallback)., The callback object can be your simple module class too.

This code skeleton example shows how to set up a TcpSocket to use the module itself as callback object:

class MyModule : public cSimpleModule, public TcpSocket::ICallback
{
    TcpSocket socket;
    virtual void socketDataArrived(TcpSocket *tcpSocket, cPacket *msg, bool urgent);
    virtual void socketFailure(int connId, int code);
    ...
};
void MyModule::initialize() {
    socket.setCallback(this);
}
void MyModule::handleMessage(cMessage *msg) {
    if (socket.belongsToSocket(msg))
        socket.processMessage(msg); // dispatch to socketTODOX() methods
    else
        ...
}
void MyModule::socketDataArrived(TcpSocket *tcpSocket, cPacket *msg, bool) {
    EV << "Received TCP data, " << msg->getByteLength() << " bytes\\n";
    delete msg;
}
void MyModule::socketFailure(TcpSocket *tcpSocket, int code) {
    if (code==TCP_I_CONNECTION_RESET)
        EV << "Connection reset!\\n";
    else if (code==TCP_I_CONNECTION_REFUSED)
        EV << "Connection refused!\\n";
    else if (code==TCP_I_TIMEOUT)
        EV << "Connection timed out!\\n";
}

If you need to manage a large number of sockets (e.g. in a server application which handles multiple incoming connections), the SocketMap class may be useful. The following code fragment to handle incoming connections is from the Ldp module:

TcpSocket *socket = check_and_cast_nullable<TcpSocket*>socketMap.findSocketFor(msg);
if (!socket)
{
    // not yet in socketMap, must be new incoming connection: add to socketMap
    socket = new TcpSocket(msg);
    socket->setOutputGate(gate("tcpOut"));
    socket->setCallback(this);
    socketMap.addSocket(socket);
}
// dispatch to socketEstablished(), socketDataArrived(), socketPeerClosed()
// or socketFailure()
socket->processMessage(msg);
See also
TcpSocketMap

Member Enumeration Documentation

◆ State

Enumerator
NOT_BOUND 
BOUND 
LISTENING 
CONNECTING 
CONNECTED 
PEER_CLOSED 
LOCALLY_CLOSED 
CLOSED 
SOCKERROR 

Constructor & Destructor Documentation

◆ TcpSocket() [1/3]

inet::TcpSocket::TcpSocket ( )

Constructor.

The getConnectionId() method returns a valid Id right after constructor call.

17 {
18  // don't allow user-specified connIds because they may conflict with
19  // automatically assigned ones.
20  connId = getEnvir()->getUniqueNumber();
21 }

◆ TcpSocket() [2/3]

inet::TcpSocket::TcpSocket ( cMessage *  msg)

Constructor, to be used with forked sockets (see listen()).

The new connId will be picked up from the message: it should have arrived from TCP and contain TCPCommmand control info.

24 {
25  connId = check_and_cast<Indication *>(msg)->getTag<SocketInd>()->getSocketId();
27 
28  if (msg->getKind() == TCP_I_AVAILABLE) {
29  TcpAvailableInfo *availableInfo = check_and_cast<TcpAvailableInfo *>(msg->getControlInfo());
30  connId = availableInfo->getNewSocketId();
31  localAddr = availableInfo->getLocalAddr();
32  remoteAddr = availableInfo->getRemoteAddr();
33  localPrt = availableInfo->getLocalPort();
34  remotePrt = availableInfo->getRemotePort();
35  }
36  else if (msg->getKind() == TCP_I_ESTABLISHED) {
37  // management of stockstate is left to processMessage() so we always
38  // set it to CONNECTED in the ctor, whatever TCP_I_xxx arrives.
39  // However, for convenience we extract TcpConnectInfo already here, so that
40  // remote address/port can be read already after the ctor call.
41 
42  TcpConnectInfo *connectInfo = check_and_cast<TcpConnectInfo *>(msg->getControlInfo());
43  localAddr = connectInfo->getLocalAddr();
44  remoteAddr = connectInfo->getRemoteAddr();
45  localPrt = connectInfo->getLocalPort();
46  remotePrt = connectInfo->getRemotePort();
47  }
48 }

◆ TcpSocket() [3/3]

inet::TcpSocket::TcpSocket ( TcpAvailableInfo availableInfo)

Constructor, to be used with forked sockets (see listen()).

51 {
52  connId = availableInfo->getNewSocketId();
54  localAddr = availableInfo->getLocalAddr();
55  remoteAddr = availableInfo->getRemoteAddr();
56  localPrt = availableInfo->getLocalPort();
57  remotePrt = availableInfo->getRemotePort();
58 }

◆ ~TcpSocket()

inet::TcpSocket::~TcpSocket ( )

Destructor.

61 {
62  if (cb) {
63  cb->socketDeleted(this);
64  cb = nullptr;
65  }
66  delete receiveQueue;
67 }

Member Function Documentation

◆ abort()

void inet::TcpSocket::abort ( )

Aborts the connection.

176 {
178  auto request = new Request("ABORT", TCP_C_ABORT);
179  TcpCommand *cmd = new TcpCommand();
180  request->setControlInfo(cmd);
181  sendToTcp(request);
182  }
183  sockstate = CLOSED;
184 }

Referenced by inet::bgp::BgpRouter::openTCPConnectionToPeer(), and inet::NetPerfMeter::teardownConnection().

◆ accept()

void inet::TcpSocket::accept ( int  socketId)

Accepts a new incoming connection reported as available.

115 {
116  auto request = new Request("ACCEPT", TCP_C_ACCEPT);
117  TcpAcceptCommand *acceptCmd = new TcpAcceptCommand();
118  request->setControlInfo(acceptCmd);
119  sendToTcp(request, socketId);
120 }

Referenced by inet::TcpServerSocketIo::acceptSocket(), processMessage(), inet::TcpServerHostApp::socketAvailable(), inet::TcpAppBase::socketAvailable(), inet::TcpServerThreadBase::socketAvailable(), inet::bgp::BgpRouter::socketAvailable(), and inet::Ldp::socketAvailable().

◆ belongsToSocket()

bool inet::TcpSocket::belongsToSocket ( cMessage *  msg) const
overridevirtual

Returns true if the message belongs to this socket instance (message has a TcpCommand as getControlInfo(), and the connId in it matches that of the socket.)

Implements inet::ISocket.

366 {
367  auto& tags = check_and_cast<ITaggedObject *>(msg)->getTags();
368  const auto& socketInd = tags.findTag<SocketInd>();
369  return socketInd != nullptr && socketInd->getSocketId() == connId;
370 }

Referenced by inet::TcpClientSocketIo::handleMessage(), inet::TcpServerSocketIo::handleMessage(), inet::TcpServerListener::handleMessageWhenUp(), inet::TcpServerHostApp::handleMessageWhenUp(), inet::Ldp::handleMessageWhenUp(), and processMessage().

◆ bind() [1/2]

void inet::TcpSocket::bind ( int  localPort)

Bind the socket to a local port number.

70 {
71  if (sockstate != NOT_BOUND)
72  throw cRuntimeError("TcpSocket::bind(): socket already bound");
73 
74  if (lPort < 0 || lPort > 65535)
75  throw cRuntimeError("TcpSocket::bind(): invalid port number %d", lPort);
76 
77  localPrt = lPort;
78  sockstate = BOUND;
79 }

Referenced by inet::TcpAppBase::connect(), inet::NetPerfMeter::createAndBindSocket(), inet::TcpServerListener::handleStartOperation(), inet::TcpServerHostApp::handleStartOperation(), inet::TcpAppBase::initialize(), inet::TcpGenericServerApp::initialize(), inet::Ldp::initialize(), inet::TcpClientSocketIo::open(), inet::bgp::BgpRouter::openTCPConnectionToPeer(), and inet::Ldp::openTCPConnectionToPeer().

◆ bind() [2/2]

void inet::TcpSocket::bind ( L3Address  localAddr,
int  localPort 
)

Bind the socket to a local port number and IP address (useful with multi-homing).

82 {
83  if (sockstate != NOT_BOUND)
84  throw cRuntimeError("TcpSocket::bind(): socket already bound");
85 
86  // allow -1 here, to make it possible to specify address only
87  if ((lPort < 0 || lPort > 65535) && lPort != -1)
88  throw cRuntimeError("TcpSocket::bind(): invalid port number %d", lPort);
89 
90  localAddr = lAddr;
91  localPrt = lPort;
92  sockstate = BOUND;
93 }

◆ close()

void inet::TcpSocket::close ( )
overridevirtual

Closes the local end of the connection.

With TCP, a CLOSE operation means "I have no more data to send", and thus results in a one-way connection until the remote TCP closes too (or the FIN_WAIT_1 timeout expires)

Implements inet::ISocket.

162 {
164 // throw cRuntimeError("TcpSocket::close(): not connected or close() already called (sockstate=%s)", stateName(sockstate));
165  }
166  else {
167  auto request = new Request("CLOSE", TCP_C_CLOSE);
168  TcpCommand *cmd = new TcpCommand();
169  request->setControlInfo(cmd);
170  sendToTcp(request);
172  }
173 }

Referenced by inet::TcpAppBase::close(), inet::TcpGenericServerThread::dataArrived(), inet::TcpServerListener::handleStopOperation(), inet::TcpServerHostApp::handleStopOperation(), inet::Ldp::handleStopOperation(), inet::NetPerfMeter::handleTimer(), inet::bgp::BgpRouter::processMessageFromTCP(), and inet::Ldp::socketAvailable().

◆ connect()

void inet::TcpSocket::connect ( L3Address  remoteAddr,
int  remotePort 
)

Active OPEN to the given remote socket.

123 {
124  if (sockstate != NOT_BOUND && sockstate != BOUND)
125  throw cRuntimeError("TcpSocket::connect(): connect() or listen() already called (need renewSocket()?)");
126 
127  if (remotePort < 0 || remotePort > 65535)
128  throw cRuntimeError("TcpSocket::connect(): invalid remote port number %d", remotePort);
129 
130  auto request = new Request("ActiveOPEN", TCP_C_OPEN_ACTIVE);
131 
132  remoteAddr = remoteAddress;
133  remotePrt = remotePort;
134 
135  TcpOpenCommand *openCmd = new TcpOpenCommand();
136  openCmd->setLocalAddr(localAddr);
137  openCmd->setLocalPort(localPrt);
138  openCmd->setRemoteAddr(remoteAddr);
139  openCmd->setRemotePort(remotePrt);
140  openCmd->setTcpAlgorithmClass(tcpAlgorithmClass.c_str());
141 
142  request->setControlInfo(openCmd);
143  sendToTcp(request);
145 }

Referenced by inet::TcpAppBase::connect(), inet::NetPerfMeter::establishConnection(), inet::TcpClientSocketIo::open(), inet::bgp::BgpRouter::openTCPConnectionToPeer(), and inet::Ldp::openTCPConnectionToPeer().

◆ destroy()

void inet::TcpSocket::destroy ( )
overridevirtual

Destroy the connection.

Implements inet::ISocket.

187 {
188  auto request = new Request("DESTROY", TCP_C_DESTROY);
189  TcpCommand *cmd = new TcpCommand();
190  request->setControlInfo(cmd);
191  sendToTcp(request);
192  sockstate = CLOSED;
193 }

Referenced by inet::TcpServerListener::handleCrashOperation(), inet::TelnetApp::handleCrashOperation(), inet::TcpBasicClientApp::handleCrashOperation(), inet::TcpSessionApp::handleCrashOperation(), inet::TcpServerHostApp::handleCrashOperation(), and inet::Ldp::handleCrashOperation().

◆ getLocalAddress()

L3Address inet::TcpSocket::getLocalAddress ( ) const
inline

◆ getLocalPort()

int inet::TcpSocket::getLocalPort ( ) const
inline
230 { return localPrt; }

Referenced by inet::operator<<().

◆ getReceiveQueue()

ChunkQueue* inet::TcpSocket::getReceiveQueue ( )
inline

◆ getRemoteAddress()

L3Address inet::TcpSocket::getRemoteAddress ( ) const
inline

◆ getRemotePort()

int inet::TcpSocket::getRemotePort ( ) const
inline
232 { return remotePrt; }

Referenced by inet::operator<<().

◆ getSocketId()

int inet::TcpSocket::getSocketId ( ) const
inlineoverridevirtual

Returns the internal connection Id.

TCP uses the (gate index, connId) pair to identify the connection when it receives a command from the application (or TcpSocket).

Implements inet::ISocket.

206 { return connId; }

Referenced by inet::bgp::BgpRouter::findIdFromSocketConnId(), inet::operator<<(), inet::TcpServerHostApp::socketAvailable(), inet::bgp::BgpRouter::socketDataArrived(), inet::bgp::BgpRouter::socketEstablished(), inet::bgp::BgpRouter::socketFailure(), and TcpSocket().

◆ getState()

TcpSocket::State inet::TcpSocket::getState ( ) const
inline

◆ getTCPAlgorithmClass()

const char* inet::TcpSocket::getTCPAlgorithmClass ( ) const
inline

Returns the current tcpAlgorithmClass parameter.

258 { return tcpAlgorithmClass.c_str(); }

◆ getUserData()

void* inet::TcpSocket::getUserData ( ) const
inline

◆ isOpen()

bool inet::TcpSocket::isOpen ( ) const
overridevirtual

Implements inet::ISocket.

258 {
259  switch (sockstate) {
260  case BOUND:
261  case LISTENING:
262  case CONNECTING:
263  case CONNECTED:
264  case PEER_CLOSED:
265  case LOCALLY_CLOSED:
266  case SOCKERROR: // TODO check SOCKERROR is opened or is closed socket
267  return true;
268  case NOT_BOUND:
269  case CLOSED:
270  return false;
271  default:
272  throw cRuntimeError("invalid TcpSocket state: %d", sockstate);
273  }
274 }

Referenced by inet::Ldp::handleMessageWhenUp(), inet::TelnetApp::handleStopOperation(), inet::TcpSessionApp::handleStopOperation(), inet::TelnetApp::socketClosed(), inet::TcpServerListener::socketClosed(), inet::TcpServerHostApp::socketClosed(), and inet::TcpSessionApp::socketClosed().

◆ listen() [1/2]

void inet::TcpSocket::listen ( )
inline

Initiates passive OPEN, creating a "forking" connection that will listen on the port you bound the socket to.

Every incoming connection will get a new connId (and thus, must be handled with a new TcpSocket object), while the original connection (original connId) will keep listening on the port. The new TcpSocket object must be created with the TcpSocket(cMessage *msg) constructor.

If you need to handle multiple incoming connections, the TcpSocketMap class can also be useful, and TcpServerHostApp shows how to put it all together. See also TcpOpenCommand documentation (neddoc) for more info.

277 { listen(true); }

Referenced by listen().

◆ listen() [2/2]

void inet::TcpSocket::listen ( bool  fork)
protected
96 {
97  if (sockstate != BOUND)
98  throw cRuntimeError(sockstate == NOT_BOUND ? "TcpSocket: must call bind() before listen()"
99  : "TcpSocket::listen(): connect() or listen() already called");
100 
101  auto request = new Request("PassiveOPEN", TCP_C_OPEN_PASSIVE);
102 
103  TcpOpenCommand *openCmd = new TcpOpenCommand();
104  openCmd->setLocalAddr(localAddr);
105  openCmd->setLocalPort(localPrt);
106  openCmd->setFork(fork);
107  openCmd->setTcpAlgorithmClass(tcpAlgorithmClass.c_str());
108 
109  request->setControlInfo(openCmd);
110  sendToTcp(request);
112 }

Referenced by inet::NetPerfMeter::createAndBindSocket(), inet::TcpServerListener::handleStartOperation(), inet::TcpServerHostApp::handleStartOperation(), inet::TcpGenericServerApp::initialize(), and inet::Ldp::initialize().

◆ listenOnce()

void inet::TcpSocket::listenOnce ( )
inline

Initiates passive OPEN to create a non-forking listening connection.

Non-forking means that TCP will accept the first incoming connection, and refuse subsequent ones.

See TcpOpenCommand documentation (neddoc) for more info.

286 { listen(false); }

◆ processMessage()

void inet::TcpSocket::processMessage ( cMessage *  msg)
overridevirtual

Examines the message (which should have arrived from TCP), updates socket state, and if there is a callback object installed (see setCallback(), class ICallback), dispatches to the appropriate method.

The method deletes the message, unless (1) there is a callback object installed AND (2) the message is payload (message kind TCP_I_DATA or TCP_I_URGENT_DATA) when the responsibility of destruction is on the socketDataArrived() callback method.

IMPORTANT: for performance reasons, this method doesn't check that the message belongs to this socket, i.e. belongsToSocket(msg) would return true!

Implements inet::ISocket.

282 {
283  ASSERT(belongsToSocket(msg));
284 
285  TcpStatusInfo *status;
286  TcpAvailableInfo *availableInfo;
287  TcpConnectInfo *connectInfo;
288 
289  switch (msg->getKind()) {
290  case TCP_I_DATA:
291  if (cb)
292  cb->socketDataArrived(this, check_and_cast<Packet *>(msg), false);
293  else
294  delete msg;
295  break;
296 
297  case TCP_I_URGENT_DATA:
298  if (cb)
299  cb->socketDataArrived(this, check_and_cast<Packet *>(msg), true);
300  else
301  delete msg;
302  break;
303 
304  case TCP_I_AVAILABLE:
305  availableInfo = check_and_cast<TcpAvailableInfo *>(msg->getControlInfo());
306  if (cb)
307  cb->socketAvailable(this, availableInfo);
308  else
309  accept(availableInfo->getNewSocketId());
310  delete msg;
311  break;
312 
313  case TCP_I_ESTABLISHED:
314  // Note: this code is only for sockets doing active open, and nonforking
315  // listening sockets. For a forking listening sockets, TCP_I_ESTABLISHED
316  // carries a new connId which won't match the connId of this TcpSocket,
317  // so you won't get here. Rather, when you see TCP_I_ESTABLISHED, you'll
318  // want to create a new TcpSocket object via new TcpSocket(msg).
320  connectInfo = check_and_cast<TcpConnectInfo *>(msg->getControlInfo());
321  localAddr = connectInfo->getLocalAddr();
322  remoteAddr = connectInfo->getRemoteAddr();
323  localPrt = connectInfo->getLocalPort();
324  remotePrt = connectInfo->getRemotePort();
325  if (cb)
326  cb->socketEstablished(this);
327  delete msg;
328  break;
329 
330  case TCP_I_PEER_CLOSED:
332  if (cb)
333  cb->socketPeerClosed(this);
334  delete msg;
335  break;
336 
337  case TCP_I_CLOSED:
338  sockstate = CLOSED;
339  if (cb)
340  cb->socketClosed(this);
341  delete msg;
342  break;
343 
346  case TCP_I_TIMED_OUT:
348  if (cb)
349  cb->socketFailure(this, msg->getKind());
350  delete msg;
351  break;
352 
353  case TCP_I_STATUS:
354  status = check_and_cast<TcpStatusInfo *>(msg->getControlInfo());
355  if (cb)
356  cb->socketStatusArrived(this, status);
357  delete msg;
358  break;
359 
360  default:
361  throw cRuntimeError("TcpSocket: invalid msg kind %d, one of the TCP_I_xxx constants expected", msg->getKind());
362  }
363 }

Referenced by inet::TcpClientSocketIo::handleMessage(), inet::TcpServerSocketIo::handleMessage(), inet::TcpGenericServerApp::handleMessage(), inet::TcpServerListener::handleMessageWhenUp(), inet::TcpServerHostApp::handleMessageWhenUp(), inet::TcpAppBase::handleMessageWhenUp(), inet::Ldp::handleMessageWhenUp(), and inet::bgp::BgpRouter::processMessageFromTCP().

◆ renewSocket()

void inet::TcpSocket::renewSocket ( )

Required to re-connect with a "used" TcpSocket object.

By default, a TcpSocket object is tied to a single TCP connection, via the connectionId. When the connection gets closed or aborted, you cannot use the socket to connect again (by connect() or listen()) unless you obtain a new connectionId by calling this method.

BEWARE if you use TcpSocketMap! TcpSocketMap uses connectionId to find TCPSockets, so after calling this method you have to remove the socket from your TcpSocketMap, and re-add it. Otherwise TcpSocketMap will get confused.

The reason why one must obtain a new connectionId is that TCP still has to maintain the connection data structure (identified by the old connectionId) internally for a while (2 maximum segment lifetimes = 240s) after it reported "connection closed" to us.

250 {
251  connId = getEnvir()->getUniqueNumber();
252  remoteAddr = localAddr = L3Address();
253  remotePrt = localPrt = -1;
255 }

Referenced by inet::TcpAppBase::connect(), inet::NetPerfMeter::establishConnection(), and inet::bgp::BgpRouter::openTCPConnectionToPeer().

◆ requestStatus()

void inet::TcpSocket::requestStatus ( )

Causes TCP to reply with a fresh TcpStatusInfo, attached to a dummy message as getControlInfo().

The reply message can be recognized by its message kind TCP_I_STATUS, or (if a callback object is used) the socketStatusArrived() method of the callback object will be called.

196 {
197  auto request = new Request("STATUS", TCP_C_STATUS);
198  TcpCommand *cmd = new TcpCommand();
199  request->setControlInfo(cmd);
200  sendToTcp(request);
201 }

◆ send()

void inet::TcpSocket::send ( Packet msg)
overridevirtual

◆ sendCommand()

void inet::TcpSocket::sendCommand ( Request msg)

Sends command.

157 {
158  sendToTcp(msg);
159 }

Referenced by inet::NetPerfMeter::sendTCPQueueRequest().

◆ sendToTcp()

void inet::TcpSocket::sendToTcp ( cMessage *  msg,
int  c = -1 
)
protected
239 {
240  if (!gateToTcp)
241  throw cRuntimeError("TcpSocket: setOutputGate() must be invoked before socket can be used");
242 
243  auto& tags = check_and_cast<ITaggedObject *>(msg)->getTags();
244  tags.addTagIfAbsent<DispatchProtocolReq>()->setProtocol(&Protocol::tcp);
245  tags.addTagIfAbsent<SocketReq>()->setSocketId(connId == -1 ? this->connId : connId);
246  check_and_cast<cSimpleModule *>(gateToTcp->getOwnerModule())->send(msg, gateToTcp);
247 }

Referenced by abort(), accept(), close(), connect(), destroy(), listen(), requestStatus(), send(), sendCommand(), setDscp(), setTimeToLive(), and setTos().

◆ setCallback()

void inet::TcpSocket::setCallback ( ICallback cb)

Sets a callback object, to be used with processMessage().

This callback object may be your simple module itself (if it multiply inherits from ICallback too, that is you declared it as

class MyAppModule : public cSimpleModule, public TcpSocket::ICallback

and redefined the necessary virtual functions; or you may use dedicated class (and objects) for this purpose.

TcpSocket doesn't delete the callback object in the destructor or on any other occasion.

277 {
278  cb = callback;
279 }

Referenced by inet::TcpServerSocketIo::acceptSocket(), inet::TcpServerListener::handleStartOperation(), inet::TcpServerHostApp::handleStartOperation(), inet::TcpAppBase::initialize(), inet::TcpClientSocketIo::open(), inet::bgp::BgpRouter::openTCPConnectionToPeer(), inet::Ldp::openTCPConnectionToPeer(), inet::bgp::BgpRouter::processMessageFromTCP(), inet::TcpServerHostApp::socketAvailable(), and inet::Ldp::socketAvailable().

◆ setDscp()

void inet::TcpSocket::setDscp ( short  dscp)

Sets the Ipv4 / Ipv6 dscp fields of packets sent from the TCP socket.

217 {
218  auto request = new Request("setDscp", TCP_C_SETOPTION);
219  auto *cmd = new TcpSetDscpCommand();
220  cmd->setDscp(dscp);
221  request->setControlInfo(cmd);
222  sendToTcp(request);
223 }

Referenced by inet::TcpAppBase::connect().

◆ setOutputGate()

◆ setState()

void inet::TcpSocket::setState ( TcpSocket::State  state)
inline
225 { sockstate = state; }

◆ setTCPAlgorithmClass()

void inet::TcpSocket::setTCPAlgorithmClass ( const char *  tcpAlgorithmClass)
inline

Sets the tcpAlgorithmClass parameter of the next connect() or listen() call.

◆ setTimeToLive()

void inet::TcpSocket::setTimeToLive ( int  ttl)

Set the TTL (Ipv6: Hop Limit) field on sent packets.

208 {
209  auto request = new Request("setTTL", TCP_C_SETOPTION);
210  TcpSetTimeToLiveCommand *cmd = new TcpSetTimeToLiveCommand();
211  cmd->setTtl(ttl);
212  request->setControlInfo(cmd);
213  sendToTcp(request);
214 }

Referenced by inet::TcpAppBase::connect(), and inet::bgp::BgpRouter::openTCPConnectionToPeer().

◆ setTos()

void inet::TcpSocket::setTos ( short  tos)

Sets the Ipv4 Type of Service / Ipv6 Traffic Class fields of packets sent from the TCP socket.

226 {
227  auto request = new Request("setTOS", TCP_C_SETOPTION);
228  auto *cmd = new TcpSetTosCommand();
229  cmd->setTos(dscp);
230  request->setControlInfo(cmd);
231  sendToTcp(request);
232 }

Referenced by inet::TcpAppBase::connect().

◆ setUserData()

◆ stateName()

const char * inet::TcpSocket::stateName ( TcpSocket::State  state)
static

Returns name of socket state code returned by getState().

373 {
374 #define CASE(x) case x: \
375  s = #x; break
376  const char *s = "unknown";
377  switch (state) {
378  CASE(NOT_BOUND);
379  CASE(BOUND);
380  CASE(LISTENING);
381  CASE(CONNECTING);
382  CASE(CONNECTED);
383  CASE(PEER_CLOSED);
385  CASE(CLOSED);
386  CASE(SOCKERROR);
387  }
388  return s;
389 #undef CASE
390 }

Referenced by inet::operator<<(), inet::TcpAppBase::refreshDisplay(), inet::TcpSinkAppThread::refreshDisplay(), inet::TcpSessionApp::refreshDisplay(), inet::TcpServerThreadBase::refreshDisplay(), and send().

Member Data Documentation

◆ cb

ICallback* inet::TcpSocket::cb = nullptr
protected

◆ connId

int inet::TcpSocket::connId = -1
protected

◆ gateToTcp

cGate* inet::TcpSocket::gateToTcp = nullptr
protected

Referenced by sendToTcp().

◆ localAddr

L3Address inet::TcpSocket::localAddr
protected

◆ localPrt

int inet::TcpSocket::localPrt = -1
protected

◆ receiveQueue

ChunkQueue* inet::TcpSocket::receiveQueue = nullptr
protected

Referenced by ~TcpSocket().

◆ remoteAddr

L3Address inet::TcpSocket::remoteAddr
protected

◆ remotePrt

int inet::TcpSocket::remotePrt = -1
protected

◆ sockstate

State inet::TcpSocket::sockstate = NOT_BOUND
protected

◆ tcpAlgorithmClass

std::string inet::TcpSocket::tcpAlgorithmClass
protected

Referenced by connect(), and listen().

◆ userData

void* inet::TcpSocket::userData = nullptr
protected

The documentation for this class was generated from the following files:
inet::TCP_I_TIMED_OUT
@ TCP_I_TIMED_OUT
Definition: TcpCommand_m.h:133
inet::TcpSocket::cb
ICallback * cb
Definition: TcpSocket.h:164
inet::TcpSocket::localAddr
L3Address localAddr
Definition: TcpSocket.h:159
inet::TCP_C_SETOPTION
@ TCP_C_SETOPTION
Definition: TcpCommand_m.h:92
inet::TcpSocket::ICallback::socketDataArrived
virtual void socketDataArrived(TcpSocket *socket, Packet *packet, bool urgent)=0
Notifies about data arrival, packet ownership is transferred to the callee.
inet::TcpSocket::gateToTcp
cGate * gateToTcp
Definition: TcpSocket.h:166
inet::TCP_I_CLOSED
@ TCP_I_CLOSED
Definition: TcpCommand_m.h:130
inet::TcpSocket::ICallback::socketClosed
virtual void socketClosed(TcpSocket *socket)=0
inet::TcpSocket::LISTENING
@ LISTENING
Definition: TcpSocket.h:153
inet::TcpSocket::ICallback::socketDeleted
virtual void socketDeleted(TcpSocket *socket)=0
inet::Protocol::tcp
static const Protocol tcp
Definition: Protocol.h:112
inet::TCP_I_ESTABLISHED
@ TCP_I_ESTABLISHED
Definition: TcpCommand_m.h:128
inet::TcpSocket::getSocketId
int getSocketId() const override
Returns the internal connection Id.
Definition: TcpSocket.h:206
inet::TcpSocket::NOT_BOUND
@ NOT_BOUND
Definition: TcpSocket.h:153
inet::TcpSocket::stateName
static const char * stateName(TcpSocket::State state)
Returns name of socket state code returned by getState().
Definition: TcpSocket.cc:372
inet::TCP_I_PEER_CLOSED
@ TCP_I_PEER_CLOSED
Definition: TcpCommand_m.h:129
inet::TCP_I_AVAILABLE
@ TCP_I_AVAILABLE
Definition: TcpCommand_m.h:127
DispatchProtocolReq
removed DscpReq Ipv4ControlInfo Ipv6ControlInfo up L3AddressInd DispatchProtocolReq L4PortInd Ipv4ControlInfo Ipv6ControlInfo down DispatchProtocolReq
Definition: IUdp-gates.txt:25
inet::TcpSocket::userData
void * userData
Definition: TcpSocket.h:165
inet::TcpSocket::localPrt
int localPrt
Definition: TcpSocket.h:160
inet::TCP_C_ACCEPT
@ TCP_C_ACCEPT
Definition: TcpCommand_m.h:84
inet::TcpSocket::accept
void accept(int socketId)
Accepts a new incoming connection reported as available.
Definition: TcpSocket.cc:114
inet::TCP_I_CONNECTION_RESET
@ TCP_I_CONNECTION_RESET
Definition: TcpCommand_m.h:132
inet::TCP_I_URGENT_DATA
@ TCP_I_URGENT_DATA
Definition: TcpCommand_m.h:126
inet::TcpSocket::belongsToSocket
virtual bool belongsToSocket(cMessage *msg) const override
Returns true if the message belongs to this socket instance (message has a TcpCommand as getControlIn...
Definition: TcpSocket.cc:365
inet::TcpSocket::LOCALLY_CLOSED
@ LOCALLY_CLOSED
Definition: TcpSocket.h:153
inet::TcpSocket::listen
void listen()
Initiates passive OPEN, creating a "forking" connection that will listen on the port you bound the so...
Definition: TcpSocket.h:277
inet::TCP_C_SEND
@ TCP_C_SEND
Definition: TcpCommand_m.h:85
inet::TcpSocket::ICallback::socketPeerClosed
virtual void socketPeerClosed(TcpSocket *socket)=0
inet::units::values::s
value< double, units::s > s
Definition: Units.h:1235
inet::TCP_C_STATUS
@ TCP_C_STATUS
Definition: TcpCommand_m.h:88
inet::TcpSocket::BOUND
@ BOUND
Definition: TcpSocket.h:153
inet::TcpSocket::ICallback::socketFailure
virtual void socketFailure(TcpSocket *socket, int code)=0
inet::TCP_C_OPEN_PASSIVE
@ TCP_C_OPEN_PASSIVE
Definition: TcpCommand_m.h:83
inet::TcpSocket::tcpAlgorithmClass
std::string tcpAlgorithmClass
Definition: TcpSocket.h:167
CASE
#define CASE(x)
inet::TCP_C_CLOSE
@ TCP_C_CLOSE
Definition: TcpCommand_m.h:86
inet::TcpSocket::ICallback::socketEstablished
virtual void socketEstablished(TcpSocket *socket)=0
inet::TcpSocket::CONNECTED
@ CONNECTED
Definition: TcpSocket.h:153
inet::TCP_C_ABORT
@ TCP_C_ABORT
Definition: TcpCommand_m.h:87
inet::TCP_C_DESTROY
@ TCP_C_DESTROY
Definition: TcpCommand_m.h:91
inet::TcpSocket::connId
int connId
Definition: TcpSocket.h:156
inet::TcpSocket::CONNECTING
@ CONNECTING
Definition: TcpSocket.h:153
tags
* tags
Definition: IUdp-gates.txt:3
inet::TcpSocket::CLOSED
@ CLOSED
Definition: TcpSocket.h:153
inet::TcpSocket::PEER_CLOSED
@ PEER_CLOSED
Definition: TcpSocket.h:153
inet::TcpSocket::sockstate
State sockstate
Definition: TcpSocket.h:157
inet::TcpSocket::ICallback::socketStatusArrived
virtual void socketStatusArrived(TcpSocket *socket, TcpStatusInfo *status)=0
inet::TcpSocket::remotePrt
int remotePrt
Definition: TcpSocket.h:162
inet::TCP_I_STATUS
@ TCP_I_STATUS
Definition: TcpCommand_m.h:134
inet::TCP_I_DATA
@ TCP_I_DATA
Definition: TcpCommand_m.h:125
inet::TcpSocket::ICallback::socketAvailable
virtual void socketAvailable(TcpSocket *socket, TcpAvailableInfo *availableInfo)=0
inet::TcpSocket::remoteAddr
L3Address remoteAddr
Definition: TcpSocket.h:161
inet::TcpSocket::SOCKERROR
@ SOCKERROR
Definition: TcpSocket.h:153
inet::TcpSocket::receiveQueue
ChunkQueue * receiveQueue
Definition: TcpSocket.h:169
inet::TcpSocket::sendToTcp
void sendToTcp(cMessage *msg, int c=-1)
Definition: TcpSocket.cc:238
inet::TCP_I_CONNECTION_REFUSED
@ TCP_I_CONNECTION_REFUSED
Definition: TcpCommand_m.h:131
inet::TCP_C_OPEN_ACTIVE
@ TCP_C_OPEN_ACTIVE
Definition: TcpCommand_m.h:82