Application interface for TCP sockets. More...
![]() |
Application interface for TCP sockets.
TCP clients typically use this order of API calls
This is quite similar to the traditional Berkley TCP Socket API used on desktop PCs.
The order of API calls for TCP servers is
Note, that this differs slightly from the Berkley API, where the initial socket is bound to a port and an additional socket is created when a connection is accepted. Nut/Net doesn't provide a bind call.
Most Nut/OS applications make use of the ability to assign a TCP socket to a stream and replace the somewhat primitive functions NutTcpSend() and NutTcpReceive() with stdio calls like fprintf() or fscanf().
#include <stdio.h> #include <sys/socket.h> ... TCPSOCKET *sock; FILE *stream; ... stream = _fdopen((int) sock, "r+b"); fprintf(stream, "Hello peer\r\n");
Remember, that Nut/OS streams are opened in text mode by default. Thus, we explicitly specify binary mode for the stream.
The application programmer can modify some default values of the TCP stack by calling NutTcpSetSockOpt(). This could be useful to fine tune the stack for maximum performance at minimum resource usage.
In addition you may call NutTcpSetSockOpt() to set a receive timeout in order to detect broken connections. That's often required, because TCP relies on a gracefully closed connection on the remote side. If the remote crashes or if the physical connection breaks, then NutTcpReceive() will never return unless a receive timeout value had been set. At least this is true for Nut/Net, which currently doesn't support the SO_KEEPALIVE option.
#include <sys/socket.h> ... UDPSOCKET *sock; u_long tmo = 3000; int rc; char buff[128]; ... NutTcpSetSockOpt(sock, SO_RCVTIMEO, &tmo, sizeof(tmo)); ... rc = NutTcpReceive(sock, buff, sizeof(buf)); if (rc == 0) { /* * A timeout occured. We will now perform an application specific * action to check wether our remote is still alive. */ ... }
Note again the difference to the Berkley API, where select() is used to determine receive timeouts.
Most socket API calls return -1 in case of a failure. The function NutTcpError() can be used to query a more specific error code.
#include <stdio.h> #include <sys/socket.h> ... TCPSOCKET *sock; u_long ip = inet_addr("192.168.1.100"); u_short port = 20191; int tcperr; ... if (NutTcpConnect(sock, ip, port)) { tcperr = NutTcpError(sock); printf("TCP Error: "); switch(tcperr) { case EHOSTUNREACH: printf("No route to %s\n", inet_ntoa(ip)); break; default: printf("%d\n", tcperr); break; } }