Basic TCP Client

From Nutwiki
Revision as of 18:44, 2 December 2008 by Daniel (Talk) (See also)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

First register network driver and configure interface by using DHCP.

<source lang="c"> NutRegisterDevice(&DEV_ETHER, 0, 0); if (NutDhcpIfConfig(DEV_ETHER_NAME, 0, 60000)) {

   /* Error: Cannot configure interface. */

} </source>

There are several alternatives:

Next, connect the server with the given IP address (192.168.1.100) at a specified port (8000).

<source lang="c"> sock = NutTcpCreateSocket(); if (NutTcpConnect(sock, inet_addr("192.168.1.100"), 8000)) {

   /* Error: Cannot connect server. */

} </source>

You may then send data to the server...

<source lang="c"> if (NutTcpSend(sock, buffer, len) != len) {

   /* Error: Cannot send data. */

} </source>

... or receive data from the server.

<source lang="c"> got = NutTcpRecv(sock, buffer, len); if (got <= 0) {

   /* Error: Cannot receive data. */

} </source>

When done, close the connection by closing the socket.

<source lang="c"> NutTcpCloseSocket(sock); </source>

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().

<source lang="c"> 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 ... */ </source>

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

See also