Socket

Questions

  • Where sockets stored?
  • If you use REUSEADDR can you create multiple bindings to the same socket?
    • How will the traffic flow if multiple processes bind to same port
  • Where are bindings stored
  • File vs File Descriptors vs File Descriptions
  • Does UDP split data or send the data as is?

Types of Sockets

  • Stream Sockets
    • Connection oriented
    • can use TCP (Transmission Control Protocol), SCTP (Stream Control Transmission Protocol) or DCCP (Datagram Congestion Control Protocol)
  • Datagram Sockets
    • Connectionless
    • uses UDP (User Datagram Protocol)
  • Raw Sockets

Sockets API in OS

Source Code

Methods

  • https://www.beej.us/guide/bgnet/
  • https://www.cs.dartmouth.edu/~campbell/cs60/socketprogramming.html
  • socket(int domain, int type, int protocol): int
    • domain: PF_INET or PF_INET6 (Protocol Family)
    • type: SOCK_STREAM or SOCK_DGRAM
    • protocol: 0 (auto-select)
    • returns socket file descriptor
  • bind(int sockfd, struct sockaddr *my_addr, int addrlen): int
    • server calls to bind a port
    • myaddr->sin_family: AF_INET or AF_INET6 (Address Family)
    • myaddr->sin_addr.s_addr: INADDR_ANY
    • returns -1 on error
  • connect(int sockfd, struct sockaddr *serv_addr, int addrlen): int
    • client calls to connect to server
    • returns -1 on error
  • listen(int sockfd, int backlog): int
    • wait for the connection
    • returns -1 on error
  • accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen): int
    • get the pending connection from client
    • returns new socket file descriptor
  • send(int sockfd, const void *msg, int len, int flags): int
    • sends data
    • returns number of bytes sent, else -1 on error
  • recv(int sockfd, void *buf, int len, int flags): int
    • receives data
    • returns number of bytes received, else -1 on error
  • sendto(int sockfd, const void *msg, int len, unsigned int flags, const struct sockaddr *to, socklen_t tolen): int
    • sends UDP Data
    • returns number of bytes sent, else -1 on error
  • recvfrom(int sockfd, void *buf, int len, unsigned int flags, struct sockaddr *from, int *fromlen): int
    • receives UDP Data
    • returns number of bytes received, else -1 on error
  • close(sockfd): void
    • close connection
  • shutdown(int sockfd, int how): int
    • close connection on certain direction
    • how:
      • 0: receive closed
      • 1: send closed
      • 2: send and receive both closed
    • returns -1 on error

Listing Sockets in OS

  • netstator ss can be used to list established sockets

Sockets in programming languages