C
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.
Exercise 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);.
Show example solution
#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;
}
Test yourself
-
Match socket and bind parts
- socket
- Creates socket
- bind
- Binds to address
- sockaddr_un
- UNIX address struct
- memset
- Zeroing
-
What does the bind function do?
- Creates a socket
- Binds socket to address
- Starts listening
- Accepts a connection
Show answer
Binds socket to address — bind links the socket to an address (e.g. a file path).
-
bind call
bind(fd, (struct sockaddr *)&____, sizeof(addr));
Show answer
bind(fd, (struct sockaddr *)&addr, sizeof(addr));
Next lesson: listen and accept