Beej’s <strong>Guide</strong> <strong>to</strong> <strong>Network</strong> <strong>Programming</strong> <strong>Using</strong> <strong>Internet</strong> <strong>Sockets</strong> 698.20. socket()Allocate a socket descrip<strong>to</strong>rPro<strong>to</strong>types#include #include int socket(int domain, int type, int pro<strong>to</strong>col);DescriptionReturns a new socket descrip<strong>to</strong>r that you can use <strong>to</strong> do sockety things with. This is generallythe first call in the whopping process of writing a socket program, and you can use the result forsubsequent calls <strong>to</strong> listen(), bind(), accept(), or a variety of other functions.domaindomain 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’sgoing <strong>to</strong> be PF_INET for you. And, correspondingly, when you load upyour struct sockaddr_in <strong>to</strong> use with this socket, you’re going <strong>to</strong> set thesin_family field <strong>to</strong> AF_INET(Also of interest is PF_INET6 if you’re going <strong>to</strong> be doing IPv6 stuff. Ifyou don’t know what that is, don’t worry about it...yet.)typepro<strong>to</strong>colAlso, the type parameter can be a number of things, but you’ll probablybe setting it <strong>to</strong> either SOCK_STREAM for reliable TCP sockets (send(),recv()) or SOCK_DGRAM for unreliable fast UDP sockets (send<strong>to</strong>(),recvfrom().)(Another interesting socket type is SOCK_RAW which can be used <strong>to</strong> constructpackets by hand. It’s pretty cool.)Finally, the pro<strong>to</strong>col parameter tells which pro<strong>to</strong>col <strong>to</strong> use with a certainsocket type. Like I’ve already said, for instance, SOCK_STREAM uses TCP.Fortunately for you, when using SOCK_STREAM or SOCK_DGRAM, you canjust set the pro<strong>to</strong>col <strong>to</strong> 0, and it’ll use the proper pro<strong>to</strong>col au<strong>to</strong>matically.Otherwise, you can use getpro<strong>to</strong>byname() <strong>to</strong> look up the proper pro<strong>to</strong>colnumber.Return ValueThe new socket descrip<strong>to</strong>r <strong>to</strong> be used in subsequent calls, or -1 on error (and errno will be setaccordingly.)Exampleint s1, s2;s1 = socket(PF_INET, SOCK_STREAM, 0);s2 = socket(PF_INET, SOCK_DGRAM, 0);
Beej’s <strong>Guide</strong> <strong>to</strong> <strong>Network</strong> <strong>Programming</strong> <strong>Using</strong> <strong>Internet</strong> <strong>Sockets</strong> 70if (s1 == -1) {perror("socket");}See Alsoaccept(), bind(), listen()