#include "net\udp.h" //The following code is for the Microchip MPLAB C18 compiler. For the //Hi-Tech compiler, the #pragma's are not required #pragma udata BUFFER1_256BYTES BYTE udpRxBuf[256]; #pragma udata //Return to default section //Remember number of bytes received from the UDP socket BYTE udpBytesReceived; //Create a UDP socket for receiving and one for transmitting static UDP_SOCKET udpSocketUserRx = INVALID_UDP_SOCKET; static UDP_SOCKET udpSocketUserTx = INVALID_UDP_SOCKET; void main(void) { BYTE c; NODE_INFO udpServerNode; //Initialize remote IP and MAC address of udpServerNode with 0, seeing that //we don't know them for the node that will send us an UDP message. The first //time a message is received addressed to this port, the remote IP and MAC //addresses are automatically updated with the addresses of the remote node. memclr(&udpServerNode, sizeof(udpServerNode)); //Configure for local port 54123 and remote port INVALID_UDP_PORT. This opens //the socket to listed on the given port. udpSocketUserRx = UDPOpen(54123, &udpServerNode, INVALID_UDP_PORT); //An error occurred during the UDPOpen() function if (udpSocketUserRx == INVALID_UDP_SOCKET) { //Take any additional action that is required when an error occurs } //Infinite loop. Check if anything is received on UDP port while(1) { //Is there any data waiting for us on the UDP socket? //Because of the design of the Modtronix TCP/IP stack we have to consume //all data sent to us as soon as we detect it. Store all data to a buffer //as soon as it is detected if (UDPIsGetReady(udpSocketUserRx)) { udpBytesReceived = UDPGetArray(udpRxBuf, 256); //Discard the socket buffer. UDPDiscard(); //Check if the UDP socket for transmitting has been created yet. We //only create this socket after we have received a UDP datagram from //the client. The reason is that we use the IP and MAC address //from the received UDP datagram if (udpSocketUserTx == INVALID_UDP_SOCKET) { //Create UDP socket for sending data to remote client on port 54124. //We use the UDPGetNodeInfo() go get the IP and MAC address of the //remote client. Configure for local port 54130 and remote port 54124. udpSocketUserTx = UDPOpen((WORD)54130, UDPGetNodeInfo(), (WORD)54124); //An error occurred during the UDPOpen() function if (udpSocketUserTx == INVALID_UDP_SOCKET) { //Take any additional action that is required when an error occurs } } } //Does the UDP receive buffer contain any data? if(udpBytesReceived > 0) { //Checks if there is a transmit buffer ready for accepting data, and //that the given socket is valid (not equal to INVALID_UDP_SOCKET for example) if (UDPIsPutReady(udpSocketUserTx)) { //Send all bytes received UDPPutArray(udpRxBuf, udpBytesReceived); udpBytesReceived = 0; //Indicate all bytes have been sent // Now send it. UDPFlush(); } } //This task performs normal stack task including checking for incoming packet, //type of packet and calling appropriate stack entity to process it. StackTask(); } }