<< Prev | Beej's Guide to Network Programming | Next >> |
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.
In usual usage, you get the values for these parameters from a call to getaddrinfo(), as shown in the example below. But you can fill them in by hand if you really want to.
The new socket descriptor to be used in subsequent calls, or -1 on error (and errno will be set accordingly.)
struct addrinfo hints, *res; int sockfd; // first, load up address structs with getaddrinfo(): memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; // AF_INET, AF_INET6, or AF_UNSPEC hints.ai_socktype = SOCK_STREAM; // SOCK_STREAM or SOCK_DGRAM getaddrinfo("www.example.com", "3490", &hints, &res); // make a socket using the information gleaned from getaddrinfo(): sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
accept(), bind(), getaddrinfo(), listen()
<< Prev | Beej's Guide to Network Programming | Next >> |