Basic TCP Client

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, connect the server with the given IP address (192.168.1.100) at a specified port (8000).

sock = NutTcpCreateSocket();
if (NutTcpConnect(sock, inet_addr("192.168.1.100"), 8000)) {
    /* Error: Cannot connect server. */
}

You may then send data to the server...

if (NutTcpSend(sock, buffer, len) != len) {
    /* Error: Cannot send data. */
}

... or receive data from the server.

got = NutTcpRecv(sock, buffer, len);
if (got <= 0) {
    /* Error: Cannot receive data. */
}

When done, close the connection by closing the socket.

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. The snippet below used fwrite() and fread().

FILE *stream;
/* ... more code here ... */
 
stream = _fdopen((int) sock, "r+b");
/* ... more code here ... */
 
/* Sending data. */
fwrite(buffer, 1, len, stream);
/* ... 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