Mistake on this page?
Report an issue in GitHub or email us

Socket

Socket class hierarchy

Socket is the abstract base class for all of the protocol-specific socket types. It defines all of the functions that comprise the Mbed OS Socket API. You cannot directly create a Socket object because it is abstract, but you can upcast any protocol-specific object to an abstract Socket object.

You can use this interface when designing portable application interfaces that do not require specific protocol to be defined. For example, instead of using TCPSocket* in methods, the application can use Socket* to allow either UDP or TCP to work, or even TLS.

The Socket class defines the Mbed OS Socket API and loosely follows the POSIX standard (IEEE Std 1003.1). The following table lists the methods from the Socket API and their relevant POSIX standards:

Method Description POSIX standard
Socket::connect() Connect socket to a remote address connect
Socket::close Closes any open connection and deallocates any memory associated with the socket close
Socket::send() Send data over a socket send
Socket::recv() Receive data from a socket recv
Socket::sendto() Sends data to the specified address. sendto
Socket::recvfrom() Receives data and stores the source address recvfrom
Socket::bind() Bind a specific address to a socket bind
Socket::listen() Listen for incoming connections listen
Socket::accept() Accept incoming connection accept
Socket::setsockopt() Set the socket options setsockopt
Socket::getsockopt() Get the socket options getsockopt

Not all protocols implement every function from the Socket API. For example, UDP does not implement the listen() and accept() functions. Also, socket options are mostly specific to the IP stack; they are not implemented on all stacks.

Socket class reference

Public Member Functions
virtual ~Socket ()
 Destroy a socket. More...
virtual nsapi_error_t close ()=0
 Closes the socket. More...
virtual nsapi_error_t connect (const SocketAddress &address)=0
 Connects socket to a remote address. More...
virtual nsapi_size_or_error_t send (const void *data, nsapi_size_t size)=0
 Send data on a socket. More...
virtual nsapi_size_or_error_t recv (void *data, nsapi_size_t size)=0
 Receive data from a socket. More...
virtual nsapi_size_or_error_t sendto (const SocketAddress &address, const void *data, nsapi_size_t size)=0
 Send a message on a socket. More...
virtual nsapi_size_or_error_t recvfrom (SocketAddress *address, void *data, nsapi_size_t size)=0
 Receive a data from a socket. More...
virtual nsapi_error_t bind (const SocketAddress &address)=0
 Bind a specific address to a socket. More...
virtual void set_blocking (bool blocking)=0
 Set blocking or non-blocking mode of the socket. More...
virtual void set_timeout (int timeout)=0
 Set timeout on blocking socket operations. More...
virtual void sigio (mbed::Callback< void()> func)=0
 Register a callback on state change of the socket. More...
virtual nsapi_error_t setsockopt (int level, int optname, const void *optval, unsigned optlen)=0
 Set socket options. More...
virtual nsapi_error_t getsockopt (int level, int optname, void *optval, unsigned *optlen)=0
 Get socket options. More...
virtual Socketaccept (nsapi_error_t *error=NULL)=0
 Accepts a connection on a socket. More...
virtual nsapi_error_t listen (int backlog=1)=0
 Listen for incoming connections. More...
virtual nsapi_error_t getpeername (SocketAddress *address)=0
 Get the remote-end peer associated with this socket. More...

Socket example

Here is a client example of HTTP transaction over TCPSocket:

#include "mbed.h"

// Network interface
NetworkInterface *net;

// Socket demo
int main() {
    int remaining;
    int rcount;
    char *p;
    char *buffer = new char[256];
    nsapi_size_or_error_t r;

    // Bring up the ethernet interface
    printf("Mbed OS Socket example\n");

#ifdef MBED_MAJOR_VERSION
    printf("Mbed OS version: %d.%d.%d\n\n", MBED_MAJOR_VERSION, MBED_MINOR_VERSION, MBED_PATCH_VERSION);
#endif

    net = NetworkInterface::get_default_instance();

    if (!net) {
        printf("Error! No network inteface found.\n");
        return 0;
    }

    r = net->connect();
    if (r != 0) {
        printf("Error! net->connect() returned: %d\n", r);
        return r;
    }

    // Show the network address
    const char *ip = net->get_ip_address();
    const char *netmask = net->get_netmask();
    const char *gateway = net->get_gateway();
    printf("IP address: %s\n", ip ? ip : "None");
    printf("Netmask: %s\n", netmask ? netmask : "None");
    printf("Gateway: %s\n", gateway ? gateway : "None");

    // Open a socket on the network interface, and create a TCP connection to mbed.org
    TCPSocket socket;
    // Send a simple http request
    char sbuffer[] = "GET / HTTP/1.1\r\nHost: api.ipify.org\r\nConnection: close\r\n\r\n";
    nsapi_size_t size = strlen(sbuffer);

    r = socket.open(net);
    if (r != 0) {
        printf("Error! socket.open() returned: %d\n", r);
    }

    r = socket.connect("api.ipify.org", 80);
    if (r != 0) {
        printf("Error! socket.connect() returned: %d\n", r);
        goto DISCONNECT;
    }

    // Loop until whole request send
    while(size) {
        r = socket.send(sbuffer+r, size);
        if (r < 0) {
            printf("Error! socket.send() returned: %d\n", r);
            goto DISCONNECT;
        }
        size -= r;
        printf("sent %d [%.*s]\n", r, strstr(sbuffer, "\r\n")-sbuffer, sbuffer);
    }

    // Receieve an HTTP response and print out the response line
    remaining = 256;
    rcount = 0;
    p = buffer;
    while (0 < (r = socket.recv(p, remaining))) {
        p += r;
        rcount += r;
        remaining -= r;
    }
    if (r < 0) {
        printf("Error! socket.recv() returned: %d\n", r);
        goto DISCONNECT;
    }

    printf("recv %d [%.*s]\n", rcount, strstr(buffer, "\r\n")-buffer, buffer);

    // The api.ipify.org service also gives us the device's external IP address
    p = strstr(buffer, "\r\n\r\n")+4;
    printf("External IP address: %.*s\n", rcount-(p-buffer), p);
    delete[] buffer;

DISCONNECT:
    // Close the socket to return its memory and bring down the network interface
    socket.close();

    // Bring down the ethernet interface
    net->disconnect();
    printf("Done\n");
}

Important Information for this Arm website

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies. If you are not happy with the use of these cookies, please review our Cookie Policy to learn how they can be disabled. By disabling cookies, some features of the site will not work.