c

Definition

bind (C)

#include <sys/socket.h>
 
int bind(
	int sockfd,
	const struct sockaddr *addr,
	socklen_t addrlen
);

When a socket is created with socket, it exists in a name space (address family) but has no address assigned to it. bind() assigns the address specified by addr to the socket referred to by the file descriptor sockfd. addrlen specifies the size, in bytes, of the address structure pointed to by addr. Traditionally, this operation is called “assigning a name to a socket”.

Includes: socket.h

Examples

Example: HTTP Server

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
 
int main() {
    // 1. setup hints for "binding" (AI_PASSIVE)
    struct addrinfo hints = {0};
	hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE; // Wildcard IP (0.0.0.0 or ::)
 
    struct addrinfo *res;
    getaddrinfo(NULL, "8080", &hints, &res);
 
    // 2. create socket, set reuse, bind, and listen
    int s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    
    // critical: allows restarting server immediately after crash/close
    int opt = 1;
    setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
 
    if (bind(s, res->ai_addr, res->ai_addrlen) < 0) return 1;
	
	// ...
}