deIPcK

From chipKIT
Jump to: navigation, search
DdeIPcK
Quick Look
Hardware WF32 or Wi-FIRE
Include deIPcK.h

The deIPcK C++ wrapper classes over the Digilent Embedded IP Stack (deIP).


Contents

Detailed Introduction

The deIPcK (Digilent Embedded IP stack for chipKIT) library is a wrapper for the deIP stack. The library is said to be mostly compliant with RFC 1122/793. It can be used to create a TCP or UDP client or server. You can use the deIPcK library to create client and servers for both the TCP and UDP protocols.

Introductory Programs

TCPEchoServer

This is a simple sketch to illistrate a simple TCP Server.

/************************************************************************/
/*                                                                      */
/*  TCPEchoServer                                                       */
/*                                                                      */
/*  A chipKIT DEIPcK TCP Server application to                          */
/*  demonstrate how to use the TcpServer Class.                         */
/*  This can be used in conjuction with TCPEchoClient                   */    
/*                                                                      */
/************************************************************************/
/*  Author:     Keith Vogel                                             */
/*  Copyright 2014, Digilent Inc.                                       */
/************************************************************************/
/* 
*
* Copyright (c) 2013-2014, Digilent <www.digilentinc.com>
* Contact Digilent for the latest version.
*
* This program is free software; distributed under the terms of 
* BSD 3-clause license ("Revised BSD License", "New BSD License", or "Modified BSD License")
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1.    Redistributions of source code must retain the above copyright notice, this
*        list of conditions and the following disclaimer.
* 2.    Redistributions in binary form must reproduce the above copyright notice,
*        this list of conditions and the following disclaimer in the documentation
*        and/or other materials provided with the distribution.
* 3.    Neither the name(s) of the above-listed copyright holder(s) nor the names
*        of its contributors may be used to endorse or promote products derived
*        from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/************************************************************************/
/*                                                                      */
/*                                                                      */
/************************************************************************/
/*  Revision History:                                                   */
/*                                                                      */
/*  5/14/2014(KeithV): Created                                         */
/*                                                                      */
/************************************************************************/
 
/************************************************************************/
/*                       Supported hardware:                            */
/*                                                                      */
/*  MX7cK                                                               */
/*                                                                      */
/************************************************************************/
 
//******************************************************************************************
//******************************************************************************************
//***************************** SET YOUR CONFIGURATION *************************************
//******************************************************************************************
//******************************************************************************************
 
/************************************************************************/
/*                                                                      */
/*              Include ONLY 1 hardware library that matches            */
/*              the network hardware you are using                      */
/*                                                                      */
/*              Refer to the hardware library header file               */
/*              for supported boards and hardware configurations        */
/*                                                                      */
/************************************************************************/
#include <IM8720PHY.h>                      // This is for the the Internal MAC and SMSC 8720 PHY
 
/************************************************************************/
/*                    Required library, Do NOT comment out              */
/************************************************************************/
#include <DEIPcK.h>
/************************************************************************/
/*                                                                      */
/*              SET THESE VALUES FOR YOUR NETWORK                       */
/*                                                                      */
/************************************************************************/
 
IPv4 ipServer = {192,168,1,190};
unsigned short portServer = 44300;    
 
//******************************************************************************************
//******************************************************************************************
//***************************** END OF CONFIGURATION ***************************************
//******************************************************************************************
//******************************************************************************************
 
typedef enum
{
    NONE = 0,
    LISTEN,
    ISLISTENING,
    WAITISLISTENING,
    AVAILABLECLIENT,
    ACCEPTCLIENT,
    READ,
    WRITE,
    CLOSE,
    EXIT,
    DONE
} STATE;
 
STATE state = LISTEN;
 
unsigned tStart = 0;
unsigned tWait = 5000;
 
TCPServer tcpServer;
#define cTcpClients 2
TCPSocket rgTcpClient[cTcpClients];
 
TCPSocket * ptcpClient = NULL;
 
IPSTATUS status;
 
byte rgbRead[1024];
int cbRead = 0;
int count = 0;
 
/***    void setup()
 *
 *    Parameters:
 *          None
 *              
 *    Return Values:
 *          None
 *
 *    Description: 
 *    
 *      Arduino setup function.
 *      
 *      Initialize the Serial Monitor, and initializes the
 *      the IP stack for a static IP of ipServer
 *      No other network addresses are supplied so 
 *      DNS will fail as any name lookup and time servers
 *      will all fail. But since we are only listening, who cares.
 *      
 * ------------------------------------------------------------ */
void setup() {
 
    Serial.begin(9600);
    Serial.println("TCPEchoServer 3.0");
    Serial.println("Digilent, Copyright 2014");
    Serial.println("");
 
    // intialize the stack with a static IP
    deIPcK.begin(ipServer);
}
 
/***    void loop()
 *
 *    Parameters:
 *          None
 *              
 *    Return Values:
 *          None
 *
 *    Description: 
 *    
 *      Arduino loop function.
 *      
 *      We are using the default timeout values for the DNETck and TcpServer class
 *      which usually is enough time for the Tcp functions to complete on their first call.
 *
 *      This code listens for a connection, then echos any strings that come in
 *      After about 5 seconds of inactivity, it will drop the connection.
 *
 *      This is a simple sketch to illistrate a simple TCP Server. 
 *      
 * ------------------------------------------------------------ */
void loop() {
 
    switch(state)
    {
 
    // say to listen on the port
    case LISTEN:
        if(deIPcK.tcpStartListening(portServer, tcpServer))
        {
            for(int i = 0; i < cTcpClients; i++)
            {
                tcpServer.addSocket(rgTcpClient[i]);
            }
        }
        state = ISLISTENING;
        break;
 
    case ISLISTENING:
        count = tcpServer.isListening();
        Serial.print(count, DEC);
        Serial.print(" sockets listening on port: ");
        Serial.println(portServer, DEC);
 
        if(count > 0)
        {
            state = AVAILABLECLIENT;
        }
        else
        {
            state = WAITISLISTENING;
        }
        break;
 
    case WAITISLISTENING:
        if(tcpServer.isListening() > 0)
        {
            state = ISLISTENING;
        }
        break;
 
    // wait for a connection
    case AVAILABLECLIENT:
        if((count = tcpServer.availableClients()) > 0)
        {
            Serial.print("Got ");
            Serial.print(count, DEC);
            Serial.println(" clients pending");
            state = ACCEPTCLIENT;
        }
        break;
 
    // accept the connection
    case ACCEPTCLIENT:
 
        // accept the client
        if((ptcpClient = tcpServer.acceptClient()) != NULL && ptcpClient->isConnected())
        {
            Serial.println("Got a Connection");
            state = READ;
            tStart = (unsigned) millis();
        }
 
        // this probably won't happen unless the connection is dropped
        // if it is, just release our socket and go back to listening
        else
        {
            state = CLOSE;
        }
        break;
 
    // wait fot the read, but if too much time elapses (5 seconds)
    // we will just close the tcpClient and go back to listening
    case READ:
 
        // see if we got anything to read
        if((cbRead = ptcpClient->available()) > 0)
        {
            cbRead = cbRead < sizeof(rgbRead) ? cbRead : sizeof(rgbRead);
            cbRead = ptcpClient->readStream(rgbRead, cbRead);
 
            Serial.print("Got ");
            Serial.print(cbRead, DEC);
            Serial.println(" bytes");
 
            state = WRITE;
        }
 
        // If too much time elapsed between reads, close the connection
        else if( (((unsigned) millis()) - tStart) > tWait )
        {
            state = CLOSE;
        }
        break;
 
    // echo back the string
    case WRITE:
        if(ptcpClient->isConnected())
        {               
            Serial.println("Writing: ");  
            for(int i=0; i < cbRead; i++) 
            {
                Serial.print((char) rgbRead[i]);
            }
            Serial.println("");  
 
            ptcpClient->writeStream(rgbRead, cbRead);
            state = READ;
            tStart = (unsigned) millis();
        }
 
        // the connection was closed on us, go back to listening
        else
        {
            Serial.println("Unable to write back.");  
            state = CLOSE;
        }
        break;
 
    // close our tcpClient and go back to listening
    case CLOSE:
        ptcpClient->close();
        tcpServer.addSocket(*ptcpClient);
        Serial.println("");
        state = ISLISTENING;
        break;
 
    // something bad happen, just exit out of the program
    case EXIT:
        tcpServer.close();
        Serial.println("Something went wrong, sketch is done.");  
        state = DONE;
        break;
 
    // do nothing in the loop
    case DONE:
    default:
        break;
    }
 
    // every pass through loop(), keep the stack alive
    DEIPcK::periodicTasks();
}


TCPEchoClient

This example will write some stings to the server and have the server echo it back

/************************************************************************/
/*                                                                      */
/*    TCPEchoClient                                                     */
/*                                                                      */
/*    A chipKIT DEIPcK TCP Client application to                        */
/*    demonstrate how to use the TcpClient Class.                       */
/*    This can be used in conjuction  with TCPEchoServer                */        
/*                                                                      */
/************************************************************************/
/*    Author:     Keith Vogel                                           */
/*    Copyright 2014, Digilent Inc.                                     */
/************************************************************************/
/* 
*
* Copyright (c) 2013-2014, Digilent <www.digilentinc.com>
* Contact Digilent for the latest version.
*
* This program is free software; distributed under the terms of 
* BSD 3-clause license ("Revised BSD License", "New BSD License", or "Modified BSD License")
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1.    Redistributions of source code must retain the above copyright notice, this
*        list of conditions and the following disclaimer.
* 2.    Redistributions in binary form must reproduce the above copyright notice,
*        this list of conditions and the following disclaimer in the documentation
*        and/or other materials provided with the distribution.
* 3.    Neither the name(s) of the above-listed copyright holder(s) nor the names
*        of its contributors may be used to endorse or promote products derived
*        from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/************************************************************************/
/*                                                                      */
/*                                                                      */
/************************************************************************/
/*  Revision History:                                                   */
/*                                                                      */
/*    5/14/2014 (KeithV): Created                                       */
/*                                                                      */
/************************************************************************/
 
/************************************************************************/
/*                       Supported hardware:                            */
/*                                                                      */
/*  MX7cK                                                               */
/*                                                                      */
/************************************************************************/
 
//******************************************************************************************
//******************************************************************************************
//***************************** SET YOUR CONFIGURATION *************************************
//******************************************************************************************
//******************************************************************************************
 
/************************************************************************/
/*                                                                      */
/*              Include ONLY 1 hardware library that matches            */
/*              the network hardware you are using                      */
/*                                                                      */
/*              Refer to the hardware library header file               */
/*              for supported boards and hardware configurations        */
/*                                                                      */
/************************************************************************/
#include <IM8720PHY.h>                      // This is for the the Internal MAC and SMSC 8720 PHY
 
/************************************************************************/
/*                    Required library, Do NOT comment out              */
/************************************************************************/
#include <DEIPcK.h>
 
/************************************************************************/
/*                                                                      */
/*              SET THESE VALUES FOR YOUR NETWORK                       */
/*                                                                      */
/************************************************************************/
 
const char * szIPServer = "192.168.1.180";    // server to connect to
unsigned short portServer = 44300;    
 
//******************************************************************************************
//******************************************************************************************
//***************************** END OF CONFIGURATION ***************************************
//******************************************************************************************
//******************************************************************************************
 
typedef enum
{
    NONE = 0,
    CONNECT,
    WRITE,
    READ,
    CLOSE,
    DONE,
} STATE;
 
STATE state = CONNECT;
IPSTATUS    status;
 
unsigned tStart = 0;
unsigned tWait = 5000;
 
TCPSocket tcpClient;
byte rgbRead[1024];
int cbRead = 0;
 
// this is for Print.write to print
byte rgbWrite[] = {'*','W','r','o','t','e',' ','f','r','o','m',' ','p','r','i','n','t','.','w','r','i','t','e','*','\n'};
int cbWrite = sizeof(rgbWrite);
 
// this is for tcpClient.writeStream to print
byte rgbWriteStream[] = {'*','W','r','o','t','e',' ','f','r','o','m',' ','t','c','p','C','l','i','e','n','t','.','w','r','i','t','e','S','t','r','e','a','m','*','\n'};
int cbWriteStream = sizeof(rgbWriteStream);
 
/***    void setup()
 *
 *    Parameters:
 *          None
 *              
 *    Return Values:
 *          None
 *
 *    Description: 
 *    
 *      Arduino setup function.
 *      
 *      Initialize the Serial Monitor, and initializes the
 *      connection to the TCPEchoServer
 *      Use DHCP to get the IP, mask, and gateway
 *      by default we connect to port 11000
 *      
 * ------------------------------------------------------------ */
void setup() {
 
    Serial.begin(9600);
    Serial.println("TCPEchoClient 3.0");
    Serial.println("Digilent, Copyright 2014");
    Serial.println("");
 
    // use DHCP to get our IP and network addresses
    deIPcK.begin();
}
 
/***    void loop()
 *
 *    Parameters:
 *          None
 *              
 *    Return Values:
 *          None
 *
 *    Description: 
 *    
 *      Arduino loop function.
 *      
 *      We are using the default timeout values for the DNETck and TcpClient class
 *      which usually is enough time for the Tcp functions to complete on their first call.
 *
 *      This code will write  some stings to the server and have the server echo it back
 *      
 * ------------------------------------------------------------ */
void loop() {
    int cbRead = 0;
 
    switch(state)
    {
        case CONNECT:
            if(deIPcK.tcpConnect(szIPServer, portServer, tcpClient, &status))
            {
                state = WRITE;
            }
            break;
 
       // write out the strings  
       case WRITE:
            if(tcpClient.isEstablished())
                {     
                Serial.println("Got Connection");
 
                tcpClient.writeStream(rgbWriteStream, cbWriteStream);
 
                Serial.println("Bytes Read Back:");
                state = READ;
                tStart = (unsigned) millis();
                }
            break;
 
        // look for the echo back
        case READ:
 
            // see if we got anything to read
            if((cbRead = tcpClient.available()) > 0)
            {
                cbRead = cbRead < sizeof(rgbRead) ? cbRead : sizeof(rgbRead);
                cbRead = tcpClient.readStream(rgbRead, cbRead);
 
                for(int i=0; i < cbRead; i++) 
                {
                    Serial.print((char) rgbRead[i]);
                }
            }
 
            // give us some time to get everything echo'ed back
            else if( (((unsigned) millis()) - tStart) > tWait )
            {
                Serial.println("");
                state = CLOSE;
            }
            break;
 
        // done, so close up the tcpClient
        case CLOSE:
            tcpClient.close();
            Serial.println("Closing TcpClient, Done with sketch.");
            state = DONE;
            break;
 
        case DONE:
        default:
            break;
    }
 
    // keep the stack alive each pass through the loop()
    DEIPcK::periodicTasks();
}


Full library usage

deIPcK

Constructor

begin(void)

 
bool begin(void);


begin(const IPv4& ip)

 
bool begin(const IPv4& ip);


begin(const IPv4& ip, const IPv4& ipGateway)

 
bool begin(const IPv4& ip, const IPv4& ipGateway);


begin(const IPv4& ip, const IPv4& ipGateway, const IPv4& subnetMask)

 
bool begin(const IPv4& ip, const IPv4& ipGateway, const IPv4& subnetMask);


Public Functions


tcpStartListening(uint16_t listeningPort, TCPServer& tcpServer, IPSTATUS * pStatus)

 
bool tcpStartListening(uint16_t listeningPort, TCPServer& tcpServer, IPSTATUS * pStatus);

Listen on the port


tcpStartListening(uint16_t listeningPort, TCPServer& tcpServer)

 
bool tcpStartListening(uint16_t listeningPort, TCPServer& tcpServer)

Listen on the port


udpStartListening(uint16_t listeningPort, UDPServer& udpServer, IPSTATUS * pStatus)

bool udpStartListening(uint16_t listeningPort, UDPServer& udpServer, IPSTATUS * pStatus);

Listen on the port


udpStartListening(uint16_t listeningPort, UDPServer& udpServer)

bool udpStartListening(uint16_t listeningPort, UDPServer& udpServer)

Listen on the port


end(void)

 
bool end(void);

Stops and releases the IP Stack and disables the Ethernet hardware. This disables the Ethernet hardware. Begin can be called to re-initialize the hardware and set new IP parameters.

isIPReady(void)

 
bool isIPReady(void);

In general, this will return false until DHCP has finished supplying the network information.


periodicTasks(void)

static void periodicTasks(void);

Executes needed periodic stack tasks. This should be run once thru the loop() code to keep the stack alive. This is a critical function and should be called often so incoming UDP/TCP messages are not missed.


secondsSinceEpoch(IPSTATUS * pStatus)

    unsigned long secondsSinceEpoch(IPSTATUS * pStatus);

Returns the number of seconds since Epoch (Jan 1, 1970). pStatus is A pointer to receive the status of the clock. If the clock is not initialized or DNS is not available the time returned is seconds since powerup (ipsTimeSincePowerUp), and not epoch time (ipsTimeSinceEpoch).


secondsSinceEpoch(void)

    unsigned long secondsSinceEpoch(void)

Returns the number of seconds since Epoch (Jan 1, 1970).


getMyMac(MACADDR& mac))

 
bool getMyMac(MACADDR& mac);

Returns the currently active MAC address being used. max is A pointer to a MAC variable to receive the MAC address. Returns true if the MAC address is valid and false if the MAC address has not be set yet. This value will not be accruate until the Ethernet and IP Stack is fully initialized.


getMyIP(IPv4& ip)

bool getMyIP(IPv4& ip);

Returns the currently active IP address being used. ip is A pointer to an IPv4 variable to receive the IP address. Returns true if the IP address is valid and false if the IP address has not be set yet. This value will not be accruate until the Ethernet and IP Stack is fully initialized.


getGateway(IPv4& gateway)

bool getGateway(IPv4& gateway);

Returns the currently active Gateway address being used. gateway is A pointer to an IPv4 variable to receive the IP address. Returns true if the IP address is valid and false if the IP address has not be set yet. This value will not be accruate until the Ethernet and IP Stack is fully initialized.


getSubnetMask(IPv4& subnetMask)

bool getSubnetMask(IPv4& subnetMask);

Returns the currently active subnet Mask being used. subnetMask is A pointer to an IPv4 variable to receive the subnet mask. Returns true if the subnet mask is valid and false if the subnet mask has not be set yet. This value will not be accruate until the Ethernet and IP Stack is fully initialized.


getDNS(int index, IPv4& ipDNS)

bool getDNS(int index, IPv4& ipDNS);

Returns the currently active 1st DNS address being used. ipDNS is A pointer to an IPv4 variable to receive the IP address. Returns true if the IP address is valid ans false if the IP address has not be set yet. This value will not be accruate until the Ethernet and IP Stack is fully initialized.


setDNS(int index, const IPv4& ipDNS)

bool setDNS(int index, const IPv4& ipDNS);

Sets the DNS at the given index. ipDNS is A pointer to an IPv4 variable to which contains the IP address. getcMaxDNS(void) can be used to obtain the max possible index count.


getcDhcpNS(void)

unsigned long getcDhcpNS(void)


getcMaxDNS(void)

unsigned long getcMaxDNS(void)


resolveIPtoMAC(const IPv4& ip, MACADDR& mac, IPSTATUS * pStatus)

bool resolveIPtoMAC(const IPv4& ip, MACADDR& mac, IPSTATUS * pStatus);

Checks to see if anyone responded with a MAC address for the requested IP. ip is the IP address of the MAC requested. mac is A pointer to a MAC variable to receive the MAC address. pStatus is A pointer to receive the connect status.


resolveIPtoMAC(const IPv4& ip, MACADDR& mac)

bool resolveIPtoMAC(const IPv4& ip, MACADDR& mac)

Checks to see if anyone responded with a MAC address for the requested IP. ip is the IP address of the MAC requested. mac is A pointer to a MAC variable to receive the MAC address.


resolveDomainName(const char * szDomanName, IPv4& ip, IPSTATUS * pStatus)

bool resolveDomainName(const char * szDomanName, IPv4& ip, IPSTATUS * pStatus);

Checks to see if a DNS lookup is finished.


resolveDomainName(const char * szDomanName, IPv4& ip)

bool resolveDomainName(const char * szDomanName, IPv4& ip)

Checks to see if a DNS lookup is finished.


terminateDNS(void)

void terminateDNS(void);

Terminate any currently active DNS lookup.


resolveEndPoint(const char *szRemoteHostName, uint16_t remotePort, IPEndPoint& epRemote, IPSTATUS * pStatus)

bool resolveEndPoint(const char *szRemoteHostName, uint16_t remotePort, IPEndPoint& epRemote, IPSTATUS * pStatus);


resolveEndPoint(const char *szRemoteHostName, uint16_t remotePort, IPEndPoint& epRemote)

bool resolveEndPoint(const char *szRemoteHostName, uint16_t remotePort, IPEndPoint& epRemote)


terminateResolveEndPoint(void)

void terminateResolveEndPoint(void)


udpSetEndPoint(const IPv4& remoteIP, uint16_t remotePort, UDPSocket& udpSocket, uint16_t localPort, IPSTATUS * pStatus)

bool udpSetEndPoint(const IPv4& remoteIP, uint16_t remotePort, UDPSocket& udpSocket, uint16_t localPort, IPSTATUS * pStatus);


udpSetEndPoint(const IPv4& remoteIP, uint16_t remotePort, UDPSocket& udpSocket, uint16_t localPort)

bool udpSetEndPoint(const IPv4& remoteIP, uint16_t remotePort, UDPSocket& udpSocket, uint16_t localPort)


udpSetEndPoint(IPEndPoint& epRemote, UDPSocket& udpSocket, uint16_t localPort, IPSTATUS * pStatus)

bool udpSetEndPoint(IPEndPoint& epRemote, UDPSocket& udpSocket, uint16_t localPort, IPSTATUS * pStatus)


udpSetEndPoint(IPEndPoint& epRemote, UDPSocket& udpSocket, uint16_t localPort)

bool udpSetEndPoint(IPEndPoint& epRemote, UDPSocket& udpSocket, uint16_t localPort)


tcpConnect


The following parameters apply to all overloaded methods of tcpConnect. tcpConnect Starts the connection process to connect a TCPSocket to a remote host. In itself, this does not "finish" the connection, to determine if the connection has successfully been made, IsConnected should be called.

Name Description
szRemoteHostName A pointer to a zero terminated string holding the hostname of the to connect to. This will call the underlying DNS service to r to an IPv4 address. If no DNS servers were specified or DHCP intialize DEIPcK, then the DNS lookup will fail. The hostname until IsConnected succeeds, or a hard failure status is retur IsStatusAnError can be used to identify a hard failure status
remotePort The port on the remote machine you want to connect too.
remoteIP The IPv4 address of the remote machine you want to connect to. This will call the underlying APR service to resolve the IP address to a MAC.
epRemote A IPEndPoint containing the remote IPv4 address and remote port to connect to. This will call the underlying APR service to resolve the IP address to a MAC.
pStatus A pointer to receive the connect status. This is a status and may not be a failure. Use IsStatusAnError to determine if this is a hard failure.


tcpConnect(const char *szRemoteHostName, uint16_t remotePort, TCPSocket& tcpSocket, uint16_t localPort, IPSTATUS * pStatus)
bool tcpConnect(const char *szRemoteHostName, uint16_t remotePort, TCPSocket& tcpSocket, uint16_t localPort, IPSTATUS * pStatus);


tcpConnect(const char *szRemoteHostName, TCPSocket& tcpSocket)
bool tcpConnect(const char *szRemoteHostName, TCPSocket& tcpSocket)


tcpConnect(const char *szRemoteHostName, TCPSocket& tcpSocket, IPSTATUS * pStatus)
bool tcpConnect(const char *szRemoteHostName, TCPSocket& tcpSocket, IPSTATUS * pStatus)


tcpConnect(const char *szRemoteHostName, TCPSocket& tcpSocket, uint16_t localPort)
bool tcpConnect(const char *szRemoteHostName, TCPSocket& tcpSocket, uint16_t localPort)


tcpConnect(const char *szRemoteHostName, TCPSocket& tcpSocket, uint16_t localPort, IPSTATUS * pStatus)
bool tcpConnect(const char *szRemoteHostName, TCPSocket& tcpSocket, uint16_t localPort, IPSTATUS * pStatus)


tcpConnect(const char *szRemoteHostName, uint16_t remotePort, TCPSocket& tcpSocket)
bool tcpConnect(const char *szRemoteHostName, uint16_t remotePort, TCPSocket& tcpSocket)


tcpConnect(const char *szRemoteHostName, uint16_t remotePort, TCPSocket& tcpSocket, IPSTATUS * pStatus)
bool tcpConnect(const char *szRemoteHostName, uint16_t remotePort, TCPSocket& tcpSocket, IPSTATUS * pStatus)


tcpConnect(const char *szRemoteHostName, uint16_t remotePort, TCPSocket& tcpSocket, uint16_t localPort)
bool tcpConnect(const char *szRemoteHostName, uint16_t remotePort, TCPSocket& tcpSocket, uint16_t localPort)


tcpConnect(const IPv4& remoteIP, uint16_t remotePort, TCPSocket& tcpSocket, uint16_t localPort, IPSTATUS * pStatus)
bool tcpConnect(const IPv4& remoteIP, uint16_t remotePort, TCPSocket& tcpSocket, uint16_t localPort, IPSTATUS * pStatus);


tcpConnect(const IPv4& remoteIP, uint16_t remotePort, TCPSocket& tcpSocket)
bool tcpConnect(const IPv4& remoteIP, uint16_t remotePort, TCPSocket& tcpSocket)


tcpConnect(const IPv4& remoteIP, uint16_t remotePort, TCPSocket& tcpSocket, IPSTATUS * pStatus)
bool tcpConnect(const IPv4& remoteIP, uint16_t remotePort, TCPSocket& tcpSocket, IPSTATUS * pStatus)


tcpConnect(const IPv4& remoteIP, uint16_t remotePort, TCPSocket& tcpSocket, uint16_t localPort)
bool tcpConnect(const IPv4& remoteIP, uint16_t remotePort, TCPSocket& tcpSocket, uint16_t localPort)


tcpConnect(const IPEndPoint& epRemote, TCPSocket& tcpSocket)
bool tcpConnect(const IPEndPoint& epRemote, TCPSocket& tcpSocket)


tcpConnect(const IPEndPoint& epRemote, TCPSocket& tcpSocket, IPSTATUS * pStatus)
bool tcpConnect(const IPEndPoint& epRemote, TCPSocket& tcpSocket, IPSTATUS * pStatus)


tcpConnect(const IPEndPoint& epRemote, TCPSocket& tcpSocket, uint16_t localPort)
bool tcpConnect(const IPEndPoint& epRemote, TCPSocket& tcpSocket, uint16_t localPort)


tcpConnect(const IPEndPoint& epRemote, TCPSocket& tcpSocket, uint16_t localPort, IPSTATUS * pStatus)
bool tcpConnect(const IPEndPoint& epRemote, TCPSocket& tcpSocket, uint16_t localPort, IPSTATUS * pStatus)


TCPSocket

Constructor

TCPSocket()

 
TCPSocket();

Initializes an empty, not connected TCPSocket instance

Public Functions


setSocketMem(HPMGR hPMGR)

 
setSocketMem(HPMGR hPMGR);


close(void)

 
close(void);


isEstablished(IPSTATUS * pStatus))

 
isEstablished(IPSTATUS * pStatus)


isEstablished(void)

 
isEstablished(void)


isConnected(IPSTATUS * pStatus)

 
isConnected(IPSTATUS * pStatus)


discardReadBuffer(void)

 
void discardReadBuffer(void);

Empties (flushes) the input (read) buffer. All bytes are discarded. This call is safe to make without checking the connection status.


available(void)

 
int available(void);

Returns the number of bytes available for reading. The actual number of bytes available in the socket ready for reading, 0 if none or the connection is lost.


peekByte(void)

 
int peekByte(void);

Gets the first byte from the socket buffer without removing the byte from the socket.


peekByte(size_t index)

 
int peekByte(size_t index);

Gets the indicated byte from the socket buffer without removing the byte from the socket. index is Zero based index of the byte within the socket to return, should be less than whats Available. Returns the actual byte, casted to an integer. -1 is returned if no byte was returned or an error occured. This call is safe to make without checking the connection status.


peek()

 
int peek() { return peekByte(); }

Gets the first byte from the socket buffer without removing the byte from the socket.


peekStream


The following parameters apply to peekStream.

Name Description
rgbPeek A pointer to a buffer to receive the bytes.
cbPeekMax The maximum size of rgbPeek
index Zero based index of where in the socket buffer to start copying bytes from.
pStatus A pointer to receive the status of the call, usually the connection status, or an index out of bounds error.
peekStream(byte *rgbPeek, size_t cbPeekMax)
 
size_t peekStream(byte *rgbPeek, size_t cbPeekMax);

Gets an array of bytes from the socket buffer without removing the bytes from the socket. Gets an array of bytes from the socket buffer without removing the bytes from the socket.


peekStream(byte *rgbPeek, size_t cbPeekMax, size_t index)
 
size_t peekStream(byte *rgbPeek, size_t cbPeekMax, size_t index);

Gets an array of bytes from the socket buffer without removing the bytes from the socket. Returns the actual number of bytes coped. 0 is returned if no bytes were copied or an error occured. This call is safe to make without checking the connection status.


readByte(void)

 
int readByte(void);

Reads the next available byte out of the socket buffer (removing the byte from the socket) Returns the actual byte, casted to an integer. -1 is returned if no byte was returned or an error occured. This call is safe to make without checking the connection status.

read()

 
int read() { return readByte(); }

Same as above.


readStream(byte *rgbRead, size_t cbReadMax)

 
size_t readStream(byte *rgbRead, size_t cbReadMax);

Reads an array of bytes from the socket buffer (and removes the bytes from the socket). rgbRead is A pointer to a buffer to receive the bytes. Returns the actual number of bytes read. 0 is returned if no bytes were read or an error occured. This call is safe to make without checking the connection status.


writeByte(byte bData)

 
int writeByte(byte bData);

Write a byte out on the TcpIP connection. bData is the byte to write out. Returns 1 if the byte was written. 0 is returned if no bytes were written or an error occured. This call is safe to make without checking the connection status. However, This is a very costly call to make as the byte is flushed out on to the wire. No caching of intermediate written bytes are done because it is impossible to know if the caller only wants to write 1 byte, or has a sequence to write. If more than 1 byte is to be put on the wire in one packet, Write should be used.


writeByte(byte bData, IPSTATUS * pStatus)

 
int writeByte(byte bData, IPSTATUS * pStatus);

Write a byte out on the TcpIP connection. bData is the byte to write out. pStatus is A pointer to receive the status of the call, usually the connection status. Returns 1 if the byte was written. 0 is returned if no bytes were written or an error occured. This call is safe to make without checking the connection status. However, This is a very costly call to make as the byte is flushed out on to the wire. No caching of intermediate written bytes are done because it is impossible to know if the caller only wants to write 1 byte, or has a sequence to write. If more than 1 byte is to be put on the wire in one packet, Write should be used.


write(byte d)

 
size_t write(byte d) { return writeByte(d); }

Same as writeByte(byte bData)


writeStream


The following parameters apply to writeStream.

Name Description
rgbWrite A pointer to an array of bytes to write out.
cbWrite The number of bytes to write out.
msBlockMax The maximum amount of time that should be spent attempting to write out the buffer. Typically this parameter is not needed and the default value can be used. However, if writing a buffer larger than the internal TcpIP socket buffer, multiple writes will be used to write the whole buffer out and this could take some time depending on the speed of the network and the size of the array. If the timeout occurs before all of the bytes are written, the number of bytes actually written will be returned to the caller and Write will have to be called again to write out the un-written bytes.
pStatus A pointer to receive the status of the call, usually the connection status.
writeStream(const byte *rgbWrite, size_t cbWrite)
 
size_t writeStream(const byte *rgbWrite, size_t cbWrite);

Write an array of bytes out on the TcpIP connection.


writeStream(const byte *rgbWrite, size_t cbWrite, IPSTATUS * pStatus)
 
size_t writeStream(const byte *rgbWrite, size_t cbWrite, IPSTATUS * pStatus);


flush(void)

 
void flush(void) {TCPFlush(&_socket);}


getRemoteEndPoint(IPEndPoint& epRemote)

 
bool getRemoteEndPoint(IPEndPoint& epRemote);

Gets the endpoint for the remote connection. epRemote is A pointer to an IPEndPoint to receive the remote endpoint information. If false is returned, then *epRemote will be garbage. If true it will be the remote endpoint information even for machines not on the local area network.


getLocalEndPoint(IPEndPoint& epLocal)

 
bool getLocalEndPoint(IPEndPoint& epLocal);

Gets the endpoint for this connection. epLocal is A pointer to an IPEndPoint to receive the local endpoint information. It will be the local machines IP address and the port by this machine to talk to the remote machine. If false is returned, then *epLocal will be garbage.


getRemoteMAC(MACADDR& remoteMAC)

 
bool getRemoteMAC(MACADDR& remoteMAC);

Gets the MAC address of the remote endpoint. pRemoteMAC is A pointer to a MAC to receive the remote MAC address. If false is returned, then *pRemoteMAC will be garbage. This is the MAC address as returned by ARP, it will be the actual MAC address for any machine on the local area netowrk, but will typically be the MAC address of your router if the remote connection is not local to your network.


UDPSocket

Constructor

UDPSocket constructors are made private so the user must supply a datagram cache buffer.


Public Functions


setSocketMem(HPMGR hPMGR)

 
bool setSocketMem(HPMGR hPMGR);


close(void)

 
void close(void);

Closes the socket and clears the UDPSocket instance; Returns the instance to a just constructed state releasing all resources except the user supplied datagram cache buffer which will be reused if SetEndPoint is called again. Returns the UDPSocket instance to a state just as if the instance had just been constructed. The user supplied datagram cache should still be kept valid.


discardDatagram(void)

 
void discardDatagram(void);

Throws out the next datagram (if any) in the datagram cache.


available(void)

 
size_t available(void);

Returns the number of bytes in the next available datagram. Returns the actual number of bytes available in the datagram ready for reading, 0 if no datagrams are in the cache. If you read a partial datagram on a previous ReadDatagram, this call will return the number of unread bytes in the remaining datagram. If other datagrams are in the cache, they will not be visible until the previous datagram is read and removed from the cache.


peekByte(void)

 
int peekByte(void);

Gets the first byte from the datagram without removing the byte from the datagram. Returns the actual byte, casted to an integer. -1 is returned if no byte was returned or an error occured.


peekByte(size_t index)

 
int peekByte(size_t index);

Gets the indicated byte from the datagram without removing the byte from the datagram. index is Zero based index of the byte within the datagram to return, should be less than what Available. Returns the actual byte, casted to an integer. -1 is returned if no byte was returned or an error occured.


peekDatagram


The following parameters apply to peekDatagram.

Name Description
rgbPeek A pointer to a buffer to receive the bytes.
cbPeekMax The maximum size of rgbPeek
index Zero based index of where in the datagram to start copying bytes from.
peekDatagram(byte *rgbPeek, size_t cbPeekMax)
 
size_t peekDatagram(byte *rgbPeek, size_t cbPeekMax);

Gets an array of bytes from the datagram without removing the bytes from the datagram. Returns the actual number of bytes coped. 0 is returned if no bytes were copied or an error occured. Index out of bounds, or no bytes available, this is specified by a return of 0.


peekDatagram(byte *rgbPeek, size_t cbPeekMax, size_t index)
 
size_t peekDatagram(byte *rgbPeek, size_t cbPeekMax, size_t index);

Gets an array of bytes from the datagram without removing the bytes from the datagram. Returns the actual number of bytes coped. 0 is returned if no bytes were copied or an error occured. Index out of bounds, or no bytes available, this is specified by a return of 0.


readDatagram(byte *rgbRead, size_t cbReadMax)

 
size_t readDatagram(byte *rgbRead, size_t cbReadMax);

Reads an array of bytes from the datagram (and removes the bytes from the datagram). rgbRead is A pointer to a buffer to receive the bytes. cbReadMax is The maximum size of rgbPeek. Returns the actual number of bytes read. 0 is returned if no bytes were read.


writeDatagram(const byte *rgbWrite, size_t cbWrite)

 
long int writeDatagram(const byte *rgbWrite, size_t cbWrite);

Writes the buffer out as a datagram and sends it to the instances remote endpoint. rgbWrite is A pointer to an array of bytes that composes the datagram. cbWrite is The number of bytes in the datagram. Returns the number of bytes actually written. 0 is returned if no bytes were written or an error occured. Because Udp is a datagram protocol, this always transmits the buffer immediately as a complete datagram.

getRemoteEndPoint(IPEndPoint& epRemote)

 
bool getRemoteEndPoint(IPEndPoint& epRemote);

Gets the remote endpoint as resolved. pRemoteEP is A pointer to an IPEndPoint to receive the remote endpoint information. If false is returned, then *pRemoteEP will be garbage.


getLocalEndPoint(IPEndPoint& epLocal)

 
bool getLocalEndPoint(IPEndPoint& epLocal);

Gets the endpoint for this socket. It will be the local machines IP address and the port that this machine will use to talk to the remote machine. epLocal is A pointer to an IPEndPoint to receive the local endpoint information. If false is returned, then *epLocal will be garbage.


getRemoteMAC(MACADDR& remoteMAC)

 
bool getRemoteMAC(MACADDR& remoteMAC);

Gets the MAC address of the remote endpoint. pRemoteMAC is A pointer to a MAC to receive the remote MAC address. If false is returned, then *pRemoteMAC will be garbage. This is the MAC address as returned by ARP, it will be the actual MAC address for any machine on the local area netowrk, but will typically be the MAC address of your router if the remote connection is not local to your network.


TCPServer

Constructor

TCPServer()

 
TCPServer();

Initialize a new TCPServer Instance and specify maximum number of sockets that it will use. Only 1 socket is listening at a time on the port however there may be many sockets pending and accept. Once all sockets are consumed by unaccepted clients TCPServer will stop listening on the port until a client is accepted and a socket opens up.


Public Functions


addSocket(TCPSocket& tcpSocket, IPSTATUS * pStatus)

bool addSocket(TCPSocket& tcpSocket, IPSTATUS * pStatus);


addSocket(TCPSocket& tcpSocket)

bool addSocket(TCPSocket& tcpSocket)


close(void)

void close(void);

Stops Listening and closes all unaccepted sockets/connections and clears everything back to it's originally constructed state.


availableClients(int& cListening, int& cWaiting, IPSTATUS * pStatus)

int availableClients(int& cListening, int& cWaiting, IPSTATUS * pStatus);

availableClients

availableClients(void)
int availableClients(void)

Checks to see how many pending clients are availabe to be accepted. Returns the number of waiting TCPSockets to be accepted.


availableClients(IPSTATUS * pStatus)
int availableClients(IPSTATUS * pStatus)

Checks to see how many pending clients are availabe to be accepted. Returns the number of waiting TCPSockets to be accepted.


availableClients(int& cWaiting)
int availableClients(int& cWaiting)

Checks to see how many pending clients are availabe to be accepted. Returns the number of waiting TCPSockets to be accepted.


availableClients(int& cWaiting, IPSTATUS * pStatus)
int availableClients(int& cWaiting, IPSTATUS * pStatus)

Checks to see how many pending clients are availabe to be accepted. Returns the number of waiting TCPSockets to be accepted.


isListening(void)

int isListening(void)


isListening(IPSTATUS * pStatus)

int isListening(IPSTATUS * pStatus)


acceptClient(int index)

TCPSocket * acceptClient(int index);

Removes a pending TCPSocket by accepting it from the server. pTCPSocket is A pointer to a newly constructed client TCPSocket. index is the zero based index of the client you want to accept. index must be less than AvailableClients. pStatus is A pointer to receive the status of AcceptClient. Yhis call should be made immediately after AvailableClients or GetAvailableClientsRemoteEndPoint. o not run PeriodicTasks between AvailableClients and this call because the client count could change. In order to keep the indexes within the range of AvailableClients and consistent with what returned, do not run AvailableClients or PeriodicTasks inbetween them. That is, do not run any stack task as that would change the AvailableClients count and order.


getAvailableClientsRemoteEndPoint(IPEndPoint& epRemote, int index)

bool getAvailableClientsRemoteEndPoint(IPEndPoint& epRemote, int index);

Returns endpoint information about a TCPSocket waiting to be accepted. pRemoteEP A pointer to an IPEndPoint to receive the remote endpoint information for the client waiting to be accepted. This may be NULL if you don't want the info. pRemoteMAC is A pointer to a MAC to receive the remote MAC address of the client waiting to be accepted. This will be the MAC address as known by ARP and will only have MAC address of machines on your local area network. If the IP is not local, the MAC will most probably be the MAC of your router. This may be NULL if you don't want the info. index is a zero based index and must be less than what AvailableClients returns. It selects the Client within the server list that you want remote endpoint information on. This allows you to determine if you want to accept this endpoint before removing it from the server. It allows you to accept other clients first and out of order. This call should be made immediately after AvailableClients and immediately before AcceptClient so that the servers pending list does not change due to another connection.


getAvailableClientsRemoteEndPoint(IPEndPoint& epRemote)

bool getAvailableClientsRemoteEndPoint(IPEndPoint& epRemote)


getListeningEndPoint(IPEndPoint& epLocal)

bool getListeningEndPoint(IPEndPoint& epLocal);

Gets the endpoint that the server is listening on. This is both the IP and port the server is on. pLocalEP is A pointer to an IPEndPoint to receive the local endpoint information. If false is returned, then *pLocalEP will be garbage.


UDPServer

Constructor

UDPServer()

 
UDPServer();

Initialize a new UDPServer Instance and specify maximum number of sockets that it will use. Only 1 socket is listening at a time on the port however there may be many sockets pending and accept. Once all sockets are consumed by unaccepted clients UDPServer will stop listening on the port until a client is accepted and a socket opens up.


Public Functions


UDPServer()

bool addSocket(UDPSocket& udpSocket, IPSTATUS * pStatus);


addSocket(UDPSocket& udpSocket)

bool addSocket(UDPSocket& udpSocket)


close(void)

void close(void);

Stops Listening and closes all unaccepted sockets/connections and clears everything back to it's originally constructed state.


availableClients

Checks to see how many pending clients are availabe to be accepted.


This is the workhorse of the UDPServer Class. It will update pending clients if a connection is detected. It will attempt to start listening if a socket comes avalialbe for listening. It will clean up disconnected clients.


availableClients(int& cListening, IPSTATUS * pStatus)
int availableClients(int& cListening, IPSTATUS * pStatus);


availableClients(void)
int availableClients(void)


availableClients(IPSTATUS * pStatus)
int availableClients(IPSTATUS * pStatus)


availableClients(int& cListening)
int availableClients(int& cListening)


isListening(void)

int isListening(void)


isListening(IPSTATUS * pStatus)

int isListening(IPSTATUS * pStatus)


acceptClient(int index)

UDPSocket * acceptClient(int index);

Removes a pending UDPSocket by accepting it from the server.


acceptClient(void)

UDPSocket * acceptClient(void)

Removes a pending UDPSocket by accepting it from the server.


getAvailableClientsRemoteEndPoint(IPEndPoint& epRemote, int index)

bool getAvailableClientsRemoteEndPoint(IPEndPoint& epRemote, int index);

Returns endpoint information about a UDPSocket waiting to be accepted.


getAvailableClientsRemoteEndPoint(IPEndPoint& epRemote)

bool getAvailableClientsRemoteEndPoint(IPEndPoint& epRemote)

Returns endpoint information about a UDPSocket waiting to be accepted.


getListeningEndPoint(IPEndPoint& epLocal)

bool getListeningEndPoint(IPEndPoint& epLocal);

Gets the endpoint that the server is listening on. This is both the IP and port the server is on.


External Links