9.4. close()

Close a socket descriptor

#include <unistd.h>

int close(int s);

After you've finished using the socket for whatever demented scheme you have concocted and you don't want to send() or recv() or, indeed, do anything else at all with the socket, you can close() it, and it'll be freed up, never to be used again.

The remote side can tell if this happens one of two ways. One: if the remote side calls recv(), it will return 0. Two: if the remote side calls send(), it'll receive a signal SIGPIPE and send() will return -1 and errno will be set to EPIPE.

Windows users: the function you need to use is called closesocket(), not close(). If you try to use close() on a socket descriptor, it's possible Windows will get angry... And you wouldn't like it when it's angry.

Return Value
Returns zero on success, or -1 on error (and errno will be set accordingly.)

s = socket(PF_INET, SOCK_DGRAM, 0);
// a whole lotta stuff...*BRRRONNNN!*
close(s); // not much to it, really.
See Also
socket(), shutdown()