Basic TCP Server

From NutWiki

Jump to: navigation, search

First register network driver and configure interface by using DHCP.

NutRegisterDevice(&DEV_ETHER, 0, 0);
if (NutDhcpIfConfig(DEV_ETHER_NAME, 0, 60000)) {
    /* Error: Cannot configure interface. */
}

There are several alternatives:

Next, create a socket and wait for client connections at a specified port (8000).

sock = NutTcpCreateSocket();
if (NutTcpAccept(sock, 8000)) {
    /* Error: Cannot connect server. */
}

To prevent DOS attack, set timeout value for established TCP connection:

uint32_t to = 10000;
NutTcpSetSockOpt(sock, SO_RCVTIMEO, &to, sizeof(to));

You may then receive data from the client...

got = NutTcpRecv(sock, buffer, len);
if (got <= 0) {
    /* Error or connection closed by the client. */
}

... or send data to the client.

if (NutTcpSend(sock, buffer, len) != len) {
    /* Error or connection closed by the client. */
}

When done, close the socket. This will also close the connection if it is still established.

NutTcpCloseSocket(sock);

For more advanced applications you can redirect the connected socket to a file stream and use standard I/O functions like fprintf() or fscanf() for sending and receiving data.

FILE *stream;
/* ... more code here ... */
 
stream = _fdopen((int) sock, "r+b");
/* ... more code here ... */
 
/* Sending data. */
fprintf(stream, "Welcome!\r\n");
/* ... more code here ... */
 
/* Receiving data. */
got = fread(buffer, 1, len, stream);
/* ... more code here ... */

Do not forget to close the stream with fclose() and socket with NutTcpCloseSocket().

See also

Personal tools