mbed socket API

Dependents:   EthernetInterface EthernetInterface_RSF EthernetInterface EthernetInterface ... more

Deprecated

This is an mbed 2 sockets library. For mbed 5, network sockets have been revised to better support additional network stacks and thread safety here.

Files at this revision

API Documentation at this revision

Comitter:
emilmont
Date:
Thu Jul 26 15:07:32 2012 +0000
Parent:
4:75988d748e4d
Child:
6:cd2e5559786d
Commit message:
Add Endpoint class and UDPPacket class

Changed in this revision

Endpoint.cpp Show annotated file Show diff for this revision Revisions of this file
Endpoint.h Show annotated file Show diff for this revision Revisions of this file
Socket.cpp Show annotated file Show diff for this revision Revisions of this file
Socket.h Show annotated file Show diff for this revision Revisions of this file
TCPSocketConnection.cpp Show annotated file Show diff for this revision Revisions of this file
TCPSocketConnection.h Show annotated file Show diff for this revision Revisions of this file
TCPSocketServer.cpp Show annotated file Show diff for this revision Revisions of this file
UDPPacket.cpp Show annotated file Show diff for this revision Revisions of this file
UDPPacket.h Show annotated file Show diff for this revision Revisions of this file
UDPSocket.cpp Show annotated file Show diff for this revision Revisions of this file
UDPSocket.h Show annotated file Show diff for this revision Revisions of this file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Endpoint.cpp	Thu Jul 26 15:07:32 2012 +0000
@@ -0,0 +1,59 @@
+/* Copyright (C) 2012 mbed.org, MIT License
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
+ * and associated documentation files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge, publish, distribute,
+ * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+#include "Socket/Socket.h"
+#include "Socket/Endpoint.h"
+#include <cstring>
+
+using std::memset;
+
+Endpoint::Endpoint()  {}
+Endpoint::~Endpoint() {}
+
+void Endpoint::reset_address(void) {
+    memset(&_remoteHost, 0, sizeof(struct sockaddr_in));
+    _ipAddress[0] = '\0';
+}
+
+int Endpoint::set_address(const char* host, const int port) {
+    //Resolve DNS address or populate hard-coded IP address
+    struct hostent *server = ::gethostbyname(host);
+    if (server == NULL)
+        return -1; //Could not resolve address
+    
+    reset_address();
+    
+    // Set IP address
+    std::memcpy((char*) &_remoteHost.sin_addr.s_addr,
+                (char*) server->h_addr_list[0], server->h_length);
+    _remoteHost.sin_family = AF_INET;
+    
+    // Set port
+    _remoteHost.sin_port = htons(port);
+    
+    return 0;
+}
+
+char* Endpoint::get_address() {
+    if ((_ipAddress[0] == '\0') && (_remoteHost.sin_addr.s_addr != 0))
+            inet_ntoa_r(_remoteHost.sin_addr, _ipAddress, sizeof(_ipAddress));
+    return _ipAddress;
+}
+
+int   Endpoint::get_port() {
+    return ntohs(_remoteHost.sin_port);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Endpoint.h	Thu Jul 26 15:07:32 2012 +0000
@@ -0,0 +1,40 @@
+/* Copyright (C) 2012 mbed.org, MIT License
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
+ * and associated documentation files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge, publish, distribute,
+ * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+#ifndef ENDPOINT_H
+#define ENDPOINT_H
+
+class Endpoint {
+
+public:
+    Endpoint(void);
+    
+    ~Endpoint(void);
+    
+    void reset_address(void);
+    int  set_address(const char* host, const int port);
+    
+    char* get_address(void);
+    int   get_port(void);
+
+protected:
+    char _ipAddress[16];
+    struct sockaddr_in _remoteHost;
+
+};
+
+#endif
--- a/Socket.cpp	Thu Jul 26 10:07:43 2012 +0000
+++ b/Socket.cpp	Thu Jul 26 15:07:32 2012 +0000
@@ -24,7 +24,7 @@
     
 }
 
-int Socket::init(int type) {
+int Socket::init_socket(int type) {
     if (_sock_fd != -1)
         return -1;
     
--- a/Socket.h	Thu Jul 26 10:07:43 2012 +0000
+++ b/Socket.h	Thu Jul 26 15:07:32 2012 +0000
@@ -38,7 +38,7 @@
     
 protected:
     int _sock_fd;
-    int init(int type);
+    int init_socket(int type);
     
     void set_timeout(int timeout);
     int wait_readable(void);
--- a/TCPSocketConnection.cpp	Thu Jul 26 10:07:43 2012 +0000
+++ b/TCPSocketConnection.cpp	Thu Jul 26 15:07:32 2012 +0000
@@ -23,24 +23,15 @@
 
 TCPSocketConnection::TCPSocketConnection() :
         _closedByRemoteHost(false) {
-    memset(&_remoteHost, 0, sizeof(struct sockaddr_in));
-    _ipAddress[0] = '\0';
 }
 
 int TCPSocketConnection::connect(const char* host, const int port) {
-    if (init(SOCK_STREAM) < 0)
+    if (init_socket(SOCK_STREAM) < 0)
         return -1;
     
-    //Resolve DNS address or populate hard-coded IP address
-    struct hostent *server = gethostbyname(host);
-    if (server == NULL)
-        return -1; //Could not resolve address
+    if (set_address(host, port) != 0)
+        return -1;
     
-    memcpy((char*) &_remoteHost.sin_addr.s_addr,
-           (char*) server->h_addr_list[0], server->h_length);
-    
-    _remoteHost.sin_family = AF_INET;
-    _remoteHost.sin_port = htons(port);
     if (lwip_connect(_sock_fd, (const struct sockaddr *) &_remoteHost, sizeof(_remoteHost)) < 0) {
         close();
         return -1;
@@ -129,18 +120,6 @@
     return readLen;
 }
 
-char* TCPSocketConnection::get_address() {
-    if (_ipAddress[0] == '\0') {
-        if (_remoteHost.sin_addr.s_addr == 0)
-            return NULL;
-        inet_ntoa_r(_remoteHost.sin_addr, _ipAddress, sizeof(_ipAddress));
-    }
-    return _ipAddress;
-}
-int   TCPSocketConnection::get_port() {
-    return ntohs(_remoteHost.sin_port);
-}
-
 TCPSocketConnection::~TCPSocketConnection() {
     close(); //Don't want to leak 
 }
--- a/TCPSocketConnection.h	Thu Jul 26 10:07:43 2012 +0000
+++ b/TCPSocketConnection.h	Thu Jul 26 15:07:32 2012 +0000
@@ -20,11 +20,12 @@
 #define TCPSOCKET_H
 
 #include "Socket/Socket.h"
+#include "Socket/Endpoint.h"
 
 /**
 This is a C++ abstraction for TCP networking sockets.
 */
-class TCPSocketConnection : public Socket {
+class TCPSocketConnection : public Socket, Endpoint {
     friend class TCPSocketServer;
     
 public:
@@ -72,15 +73,9 @@
     \return the number of received bytes on success (>=0) or -1 on failure
     */
     int receive_all(char* data, int length, int timeout=0);
-    
-    char* get_address();
-    int   get_port();
-    
+
 private:
-    char _ipAddress[16];
-    
     bool _closedByRemoteHost;
-    struct sockaddr_in _remoteHost;
 
 };
 
--- a/TCPSocketServer.cpp	Thu Jul 26 10:07:43 2012 +0000
+++ b/TCPSocketServer.cpp	Thu Jul 26 15:07:32 2012 +0000
@@ -27,7 +27,7 @@
 }
 
 int TCPSocketServer::bind(int port) {
-    if (init(SOCK_STREAM) < 0)
+    if (init_socket(SOCK_STREAM) < 0)
         return -1;
     
     struct sockaddr_in localHost;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/UDPPacket.cpp	Thu Jul 26 15:07:32 2012 +0000
@@ -0,0 +1,31 @@
+/* Copyright (C) 2012 mbed.org, MIT License
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
+ * and associated documentation files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge, publish, distribute,
+ * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+#include "Socket/UDPPacket.h"
+
+#include <cstring>
+
+using std::memset;
+
+UDPPacket::UDPPacket(char* buffer, unsigned int length) {
+    set_data(buffer, length);
+}
+
+void UDPPacket::set_data(char* buffer, unsigned int length) {
+    _buffer = buffer;
+    _length = length;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/UDPPacket.h	Thu Jul 26 15:07:32 2012 +0000
@@ -0,0 +1,41 @@
+/* Copyright (C) 2012 mbed.org, MIT License
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
+ * and associated documentation files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge, publish, distribute,
+ * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+#ifndef UDPPACKET_H
+#define UDPPACKET_H
+
+#include "Socket/Socket.h"
+#include "Socket/Endpoint.h"
+
+// Forward declaration
+class UDPSocket;
+
+class UDPPacket : public Endpoint {
+    friend class UDPSocket;
+
+public:
+    UDPPacket(char* buffer, unsigned int length);
+    ~UDPPacket() {}
+    
+    void set_data(char* buffer, unsigned int length);
+
+private:
+    unsigned int   _length;
+    char* _buffer;
+};
+
+#endif
--- a/UDPSocket.cpp	Thu Jul 26 10:07:43 2012 +0000
+++ b/UDPSocket.cpp	Thu Jul 26 15:07:32 2012 +0000
@@ -16,7 +16,7 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  */
 
-#include "UDPSocket.h"
+#include "Socket/UDPSocket.h"
 
 #include <cstring>
 
@@ -25,9 +25,13 @@
 UDPSocket::UDPSocket() {
 }
 
+int UDPSocket::init(void) {
+    return init_socket(SOCK_DGRAM);
+}
+
 // Server initialization
 int UDPSocket::bind(int port) {
-    if (init(SOCK_DGRAM) < 0)
+    if (init_socket(SOCK_DGRAM) < 0)
         return -1;
     
     struct sockaddr_in localHost;
@@ -46,72 +50,33 @@
 }
 
 // -1 if unsuccessful, else number of bytes written
-int UDPSocket::sendTo(char* data, int length, char* host, int port, int timeout) {
+int UDPSocket::sendTo(UDPPacket& packet, int timeout) {
     if (_sock_fd < 0)
         return -1;
     
-    struct sockaddr_in remoteHost;
-    
-    //Populate m_remoteHost
-    std::memset(&remoteHost, 0, sizeof(struct sockaddr_in));
-    
-    //Resolve DNS address or populate hard-coded IP address
-    struct hostent *server = ::gethostbyname(host);
-    if (server == NULL) {
-        return -1; //Could not resolve address
-    }
-    std::memcpy((char*) &remoteHost.sin_addr.s_addr,
-            (char*) server->h_addr_list[0], server->h_length);
-    
-    remoteHost.sin_family = AF_INET;
-    remoteHost.sin_port = htons(port);
-    
-    size_t writtenLen = 0;
-    set_timeout(timeout);
-    while (writtenLen < length) {
-        //Wait for socket to be writeable
-        //Creating FS set
+    if (timeout != 0) {
+        set_timeout(timeout);
         if (wait_writable() != 0)
-            return writtenLen; //Timeout -- FIXME should we return -1 or writtenLength ?
-        
-        int ret = lwip_sendto(_sock_fd, data + writtenLen, length - writtenLen, 0,
-                (const struct sockaddr *) &remoteHost, sizeof(remoteHost));
-        if (ret > 0) {
-            writtenLen += ret;
-        } else if (ret == 0) {
-            return writtenLen; //Connection was closed by server -- FIXME how do we signal that the connection was closed ?
-        } else {
-            return -1; //Connnection error
-        }
+            return -1;
     }
     
-    return writtenLen;
+    return lwip_sendto(_sock_fd, packet._buffer, packet._length, 0, (const struct sockaddr *) &packet._remoteHost, sizeof(packet._remoteHost));
 }
 
 // -1 if unsuccessful, else number of bytes received
-int UDPSocket::receiveFrom(char* data, int length, char** host, int* port, int timeout) {
+int UDPSocket::receiveFrom(UDPPacket& packet, int timeout) {
     if (_sock_fd < 0)
         return -1;
     
-    set_timeout(timeout);
-    if (wait_readable() != 0)
-        return -1;
-    
-    struct sockaddr_in remoteHost;
-    std::memset(&remoteHost, 0, sizeof(struct sockaddr_in));
+    if (timeout != 0) {
+        set_timeout(timeout);
+        if (wait_readable() != 0)
+            return -1;
+    }
     
-    socklen_t remoteHostLen = sizeof(remoteHost);
-    int n = lwip_recvfrom(_sock_fd, data, length, 0, (struct sockaddr*) &remoteHost, &remoteHostLen);
-    if (n < 0)
-        return -1;
-    
-    static char hostBuf[16];
-    inet_ntoa_r(remoteHost.sin_addr, hostBuf, sizeof(hostBuf));
-    
-    *host = hostBuf;
-    *port = ntohs(remoteHost.sin_port);
-    
-    return n;
+    packet.reset_address();
+    socklen_t remoteHostLen = sizeof(packet._remoteHost);
+    return lwip_recvfrom(_sock_fd, packet._buffer, packet._length, 0, (struct sockaddr*) &packet._remoteHost, &remoteHostLen);
 }
 
 UDPSocket::~UDPSocket() {
--- a/UDPSocket.h	Thu Jul 26 10:07:43 2012 +0000
+++ b/UDPSocket.h	Thu Jul 26 15:07:32 2012 +0000
@@ -20,45 +20,45 @@
 #define UDPSOCKET_H
 
 #include "Socket/Socket.h"
+#include "Socket/UDPPacket.h"
 #include <cstdint>
 
 /**
 This is a C++ abstraction for UDP networking sockets.
 */
 class UDPSocket : public Socket {
-  public:
+
+public:
     /** Instantiate a UDP Socket.
     */
     UDPSocket();
     
     ~UDPSocket();
     
+    int init(void);
+    
     /** Bind a UDP Server Socket to a specific port
     For a listening socket, bind the socket to the following port.
     \param port The port to listen for incoming connections on, using 0 here will select a random port.
     \return 0 on success, -1 on failure.
     */
     int bind(int port);
-
-    /** Send data to a remote host.
-    \param data The buffer to send to the host.
-    \param length The length of the buffer to send.
-    \param host The host to send data to. It can either be an IP Address or a hostname that will be resolved with DNS.
-    \param port The host's port to send data to.
+    
+    /** Send a packet to the remote host.
+    \param packet UDP Packet to be sent to the remote host
     \param timeout The maximum amount of time in ms to wait while trying to send the buffer.
     \return the number of written bytes on success (>=0) or -1 on failure
     */
-    int sendTo(char* data, int length, char* host, int port, int timeout = 0);
-
+    int sendTo(UDPPacket& packet, int timeout=0);
+    
     /** Receive data from a remote host.
-    \param data The buffer in which to store the data received from the host.
-    \param length The maximum length of the buffer.
-    \param host The reference that will point to the client's IP address.
-    \param port The reference that will point to the client's port.
+    If a message is too long to fit in the supplied packet, excess bytes are
+    discarded.
+    \param packet UDP Packet received from the remote host
     \param timeout The maximum amount of time in ms to wait while trying to receive data.
     \return the number of received bytes on success (>=0) or -1 on failure
     */
-    int receiveFrom(char* data, int length, char** host, int* port, int timeout = 0);
+    int receiveFrom(UDPPacket& packet, int timeout=0);
 };
 
 #endif