Networking

Networking Overview

OSI Model

TCP vs UDP

Differences

We focus on TCP in this class.

TCP Handshakes

SYN SYN-ACK ACK

TCP Packet Layout

TCP Packets

Networking Functions

Socket

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

image

Bind

bind associates an abstract network socket created with socket to an actual networking interface/address.

Listen

listen marks a socket as “passive”, or ready to accept incoming connections.

Accept

accept accepts an incoming connection on a socket that has been listening.

Connect

connect is used to connect a socket to a given address (which might have a socket listening for connections).

Error checking

Make sure to check errors for every call, networking can fail at any point! All networking functions specify in their manpages what types of errors you might have to deal with.

A few gotchas

Byte Ordering

  • Convert your data to/from the “network byte order” to be architecture-agnostic.
  • See man 3 htonl for more info.

Socket Options

  • Use setsockopt to set SO_REUSEADDR on your socket.
  • Otherwise the system won’t immediately reallow you to use a socket after it’s been closed.

Signal Handler Safety

  • Most server applications are interupted through a signal.
  • Don’t do cleanup in the signal handler! Not every function is signal handler safe.
  • Do this instead:
    int is_running = 1;
    int handler(){
      is_running = 0;
    }
    int main(){
      while(is_running){ /*...*/};
    
      close(...);
    }
    

Fun Facts: Latency

Latency numbers you should know