Skip to content
i99dev edited this page Jan 6, 2023 · 2 revisions

Create Socket

Overview.

open_socket.png

socket() — Create a socket

creates an endpoint for communication and returns a file descriptor that refers to that endpoint.

Socket:

int socket(int domain, int type, int protocol);

Domain

Name Purpose
AF_UNIX Local communication
AF_LOCAL Synonym for AF_UNIX
AF_INET IPv4 Internet protocols
AF_AX25 Amateur radio AX.25 protocol
AF_IPX IPX - Novell protocols

For more domain Link.

Type

type description
SOCK_STREAM Provides sequenced, reliable, two-way, connection-based byte streams. An out-of-band data transmission mechanism may be supported.

more type Link.

protocol.

use 0 for default.

socket(AF_INET, SOCK_STREAM, 0);

return will be int

int fd = socket(AF_INET, SOCK_STREAM, 0);

If is -1 that’s a means error.

socketopt

get and set options on sockets

set option for socket

int setsockopt(int sockfd, int level, int optname,
                      const void *optval, socklen_t optlen);

sockfd : its socket return fd. level : level is specified as SOL_SOCKET . optname : Linux will allow port reuse only with the SO_REUSEADDR .

opt : is default 1.

sizeof(opt)

setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

bind

int bind(int sockfd, const struct sockaddr *addr,
                socklen_t addrlen);

When a socket is created with socket(2), it exists in a name space (address family) but has no address assigned to it.

listen

marks the socket referred to by sockfd as a passive socket, that is, as a socket that will be used to accept incoming connection requests using accept(2)

Clone this wiki locally