CodeBlanks Logo Icon CodeBlanks

socket and bind

Learn to set up a server with socket and bind.

socket and bind

socket(domain, type, protocol) creates a new socket and returns a descriptor. You pass AF_UNIX for domain, SOCK_STREAM for type, 0 (default) for protocol.

bind(fd, (struct sockaddr *)&addr, sizeof(addr)) binds the socket to an address. addr is of type struct sockaddr_un; you set sun_family to AF_UNIX and sun_path to a file path. Returns 0 on success, -1 on error.

Preparing the address struct

Before bind you must fill the address struct correctly. First zero it with memset(&addr, 0, sizeof(addr)); this ensures sun_path is clean.

Then set addr.sun_family = AF_UNIX; and copy the path with strncpy(addr.sun_path, "/tmp/sock", sizeof(addr.sun_path) - 1);. The trailing -1 in strncpy prevents overflow. Removing the old socket file with unlink is a good habit; otherwise bind fails.

Practice Create and bind a socket

Create a socket with int fd = socket(AF_UNIX, SOCK_STREAM, 0);. Declare struct sockaddr_un addr;; set memset(&addr, 0, sizeof(addr)), addr.sun_family = AF_UNIX;, strncpy(addr.sun_path, "/tmp/cb.sock", sizeof(addr.sun_path) - 1);. Call unlink("/tmp/cb.sock"); and bind(fd, (struct sockaddr *)&addr, sizeof(addr));. Print printf("bound\n"); and close(fd);.

Starter code

main.c
#include <stdio.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <string.h>

// Create socket
// Fill address struct and call bind
// Print bound and close

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <string.h>

int main(void) {
    int fd = socket(AF_UNIX, SOCK_STREAM, 0);
    struct sockaddr_un addr;
    memset(&addr, 0, sizeof(addr));
    addr.sun_family = AF_UNIX;
    strncpy(addr.sun_path, "/tmp/cb.sock", sizeof(addr.sun_path) - 1);
    unlink("/tmp/cb.sock");
    bind(fd, (struct sockaddr *)&addr, sizeof(addr));
    printf("bound\n");
    close(fd);
    return 0;
}

Expected output

bound

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match socket and bind parts

Term Meaning
socket Creates socket
bind Binds to address
sockaddr_un UNIX address struct
memset Zeroing

2 What does the bind function do?

  • Creates a socket
  • Binds socket to address Correct answer
  • Starts listening
  • Accepts a connection

Explanation: bind links the socket to an address (e.g. a file path).

3 bind call

Question
bind(fd, (struct sockaddr *)&____, sizeof(addr));
Answer
bind(fd, (struct sockaddr *)&addr, sizeof(addr));

Explanation: bind links the addr struct to the socket.

All lessons in Advanced