Sikau

Computer networks · Day 5 · about 35 min

Ports, UDP and checksums

Ports pick the program; checksums catch corrupted bits.

Which program, and is it intact?

IP gets a packet to a computer. The transport layer adds a port number to reach the right program (80 for web servers, 53 for DNS). UDP stops there — fast, no guarantees, great for games and video calls. TCP adds ordering and retransmission. Both carry a checksum so corrupted packets are thrown away.

The Internet checksum

// A real IPv4 header (20 bytes) with its checksum field (bytes 10-11) set to zero.
const HEADER = [0x45, 0x00, 0x00, 0x73, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11, 0x00, 0x00, 0xc0, 0xa8, 0x00, 0x01, 0xc0, 0xa8, 0x00, 0xc7];

function checksum(bytes) {
  let sum = 0;
  for (let i = 0; i < bytes.length; i += 2) {
    sum += (bytes[i] << 8) + (bytes[i + 1] ?? 0);              // add 16-bit words
    while (sum > 0xffff) sum = (sum & 0xffff) + (sum >>> 16); // wrap the carry around
  }
  return ~sum & 0xffff;                                        // ones' complement
}

function verify(bytes) {
  return checksum(bytes) === 0;
}

The rest of this lesson

  • Choosing UDP or TCPexplain
  • How the checksum foldsexplain
  • TCP or UDP?match
  • Port to servicematch
  • Compute a checksumwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 12 lessons of Computer networks