8.20. socket()

Allocate a socket descriptor


#include <sys/types.h>
#include <sys/socket.h>

int socket(int domain, int type, int protocol);


Returns a new socket descriptor that you can use to do sockety things with. This is generally the first call in the whopping process of writing a socket program, and you can use the result for subsequent calls to listen(), bind(), accept(), or a variety of other functions.


domain describes what kind of socket you're interested in. This can, believe me, be a wide variety of things, but since this is a socket guide, it's going to be PF_INET for you. And, correspondingly, when you load up your struct sockaddr_in to use with this socket, you're going to set the sin_family field to AF_INET

(Also of interest is PF_INET6 if you're going to be doing IPv6 stuff. If you don't know what that is, don't worry about it...yet.)


Also, the type parameter can be a number of things, but you'll probably be setting it to either SOCK_STREAM for reliable TCP sockets (send(), recv()) or SOCK_DGRAM for unreliable fast UDP sockets (sendto(), recvfrom().)

(Another interesting socket type is SOCK_RAW which can be used to construct packets by hand. It's pretty cool.)


Finally, the protocol parameter tells which protocol to use with a certain socket type. Like I've already said, for instance, SOCK_STREAM uses TCP. Fortunately for you, when using SOCK_STREAM or SOCK_DGRAM, you can just set the protocol to 0, and it'll use the proper protocol automatically. Otherwise, you can use getprotobyname() to look up the proper protocol number.

Return Value

The new socket descriptor to be used in subsequent calls, or -1 on error (and errno will be set accordingly.)


int s1, s2;

s1 = socket(PF_INET, SOCK_STREAM, 0);
s2 = socket(PF_INET, SOCK_DGRAM, 0);

if (s1 == -1) {

See Also

accept(), bind(), listen()