Network Sockets, Explained | Introduction to Operating Systems

UPI Study › Courses › Introduction to Operating Systems › Free lessons › Lesson 8.5 Free with a free account

Network Sockets

Introduction to Operating Systems · Chapter 8: The Internet, Connectivity, and Network OperationsSection 8.5 · lesson 66 of 838 min · free with a free account

← Network ProtocolsNext lesson: Network Operating Systems →

A free account plays all of Chapter 1 and 3 more lessons of Introduction to Operating Systems. Create a free account →

Earn 3 college credits for Introduction to Operating SystemsRecommended for credit by NCCRS · Computer Science 354 · self-paced · one payment, lifetime access

In this lesson

How programs use sockets and system calls to talk over networks.

  • Define a socket by its IP address, port, and protocol
  • Describe the system calls a TCP server and a TCP client make, in order
  • Explain why accept returns a new socket for every caller
  • Compare stream sockets for TCP with datagram sockets for UDP

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (1,142 words). Read along, or search it.

Opening Analogy

A Socket Is the Program's Handset

A phone call needs a phone. You can know a friend's number, and all the rules of conversation, but without a handset, nothing happens. For a program, the handset is called a socket. It's the one doorway through which a program sends data into the network, and gets data back.

Definition

Address, Port, and Protocol Name a Socket

A socket is an endpoint for communication: a handle that the operating system gives a program, so it can use the network. The program never touches the wire. It reads and writes the socket much like a file, from lesson 6.2. The OS network code does the rest: packets, resending, and addresses. Three values name a socket. The IP address picks the computer. The port picks the program on that computer. And the protocol says how to talk, normally TCP or UDP. So a web server's socket might be 192.0.2.7, port 443, TCP. A connection is a pair of sockets, one at each end. So it's named by both addresses, and both ports.

System Calls

Socket, Bind, Listen, Accept, Connect

Sockets are created and driven by a few system calls, from lesson 2.3. Linux, macOS, and Windows all have the same set, with small differences. A TCP server makes four calls, in a fixed order. Socket asks the OS for a new socket. Bind attaches it to an address and a port, so clients know where to knock. Listen marks it as a socket that waits for callers, with a small waiting line. And accept waits for a caller, then returns a new socket for that one client. The client is simpler: socket, then connect, which calls the server's address and port. The TCP handshake from lesson 7.6 happens right there. Then both sides send and receive bytes, and close the socket to hang up.

Code Setup

An Echo Server on the Loopback Address

Now see it work, with no network at all. Every computer has a loopback address, 127.0.0.1, which means this same machine. Packets sent there never leave the computer, but they travel through the real OS network code, and real sockets. This one Python script plays both parts. An echo server, which sends back whatever it receives, runs in a background thread, from lesson 2.8. The main part of the script is the client, which calls the server and waits for its reply.

Server Code

Binding to Port Zero for a Free Port

The server part first. Line six asks the OS for a TCP socket. AF_INET means IPv4 addresses, and SOCK_STREAM means TCP. Bind attaches it to the loopback address, with port zero. Port zero means: OS, please pick any free port for me. Listen starts the waiting line. Then getsockname asks which address and port the OS chose, so the client knows where to call. We never print that port number, because it changes from run to run. But it's always a real port.

Server Code

Accept, Receive, and Send It Back

Inside serve, accept waits for a caller. When one arrives, it returns a brand-new socket, called conn, just for that conversation. Recv reads up to 1,024 bytes of what arrived. The server prints what it got, and sendall sends the same bytes straight back. Then it closes that one conversation's socket.

Client Code

Connect, Send Hello, Wait for the Echo

The client half starts the server's thread first, so a caller can be accepted. Then it makes its own TCP socket. Connect calls the server's address and port. That's where the TCP handshake happens. Sendall sends the message, the bytes hello. Recv waits for the echo, and the client prints what came back. Finally, it closes its socket, waits for the server thread with join, and closes the listening socket too.

Program Output

Why the Server Line Prints First

Run it. Server got hello, then client got hello. The same bytes came back, and the socket was AF_INET, SOCK_STREAM: IPv4, and TCP. Notice the order. The server line came first, and it always will. The server prints just before it sends the echo, and the client can print only after the echo arrives. So this output is the same on every run.

Try a Change

Echoing a New Message

Change one thing. Make the message rye loaf, please, and run it again. The server got the new bytes, and echoed every one of them back. Whatever port the OS picked this time, the output doesn't depend on it.

Quick Check

Why a Phone Cannot Reach 127.0.0.1

Quick check. Sam, who runs a small online bakery, starts this exact server on the shop laptop, and leaves it waiting. A phone on the same Wi-Fi tries to connect to the laptop. What happens? Pause, and decide. The phone can't reach it. 127.0.0.1 means this laptop only. Packets to it never leave the machine, so nothing from outside can arrive. Both connect options fail for one reason: nothing listens on the laptop's network address, so the phone's call is refused. Ivy, who looks after the computers at a school, once spotted this on Sam's test server. Bind to the laptop's real network address, and the phone can call it.

Key Details

New Sockets per Caller and Byte Streams

Two details make servers special. First, accept hands back a new socket for each caller, while the first socket keeps listening. That's how a web server holds thousands of connections at once, each with its own socket. Second, a TCP socket carries a stream of bytes, with no built-in message boundaries. One send may arrive as two receives, or two sends as one. So a single receive can return just part of a message. Real programs loop until they have everything their protocol promises, using a rule for where a message ends, like the Content-Length header from lesson 8.4.

Quick Check

Counting Sockets After Two Hang Ups

Quick check. A chat server is listening, and it has accepted five callers. Then two of them hang up, and the server closes those connections. Count every socket the server holds now. Pause, and predict. Four. One listening socket, still waiting in accept, plus one socket for each of the three callers still connected. Three is the tempting pick, but it forgets the listening socket. And six forgets that closed connections are gone.

Code Proof

Three Clients Make Four Sockets

This short program checks it, on loopback. Three clients connect, the server accepts each one, and then it counts its own sockets. Run it, and the server holds four.

Other Socket Types

Datagram Sockets and netstat

The echo script used a stream socket, SOCK_STREAM, which means TCP. A datagram socket, SOCK_DGRAM, means UDP. It skips listen, accept, and connect. A program just sends each datagram to an address and a port, with no connection, and no guarantee. Other families exist too. Local sockets let two programs on one machine talk through a file name, like the cooperating processes of lesson 3.7. On your own computer, the command netstat dash a n lists the sockets in use. Lines marked LISTEN are servers, waiting in accept.

Key Takeaways

Socket Calls and Streams Reviewed

To recap. A socket is a program's doorway to the network, named by an IP address, a port, and a protocol. A TCP server calls socket, bind, listen, and accept. A client calls socket and connect. Then both send, receive, and close. Accept hands back a new socket for every caller. And TCP is a stream, so programs need a rule for where a message ends.

About Introduction to Operating Systems at UPI Study

Introduction to Operating Systems (Computer Science 354) is a self-paced online course of 83 video lessons in 10 chapters, from what an operating system does and process scheduling to concurrency, memory, devices, file systems, networks, the internet, security and virtual machines. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: Linux vs Operating Systems

Why take it here

Why students take Introduction to Operating Systems with UPI Study

What happens under every app you runIntroduction to Operating Systems explains the software that runs a computer: processes and scheduling, threads and synchronization, deadlock, memory and paging, devices and storage, file systems, networking, security and virtualization. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Introduction to Operating Systems carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Network Sockets

What is a network socket?
A network socket is an endpoint that the operating system gives a program so it can send and receive data over a network. It is named by three values: an IP address that picks the computer, a port that picks the program, and a protocol, usually TCP or UDP. A connection is a pair of sockets, one at each end, so it is identified by both addresses and both ports.
In what order does a TCP server call socket, bind, listen, and accept?
A TCP server calls socket to get a new socket, bind to attach it to an address and port, listen to mark it as waiting with a small queue, and accept to wait for a caller. Accept returns a brand-new socket for that one client while the original keeps listening. A client only calls socket and then connect, which is where the TCP handshake happens.
Why can't other devices connect to a server bound to 127.0.0.1?
The address 127.0.0.1 is the loopback address, which always means this same machine. Packets sent to it pass through the real operating system network code but never leave the computer, so a phone or laptop elsewhere on the network cannot reach it. To accept outside connections, a server must bind to the computer's real network address, or to all of its addresses, instead.
Why might one TCP send arrive as several receives?
TCP carries a continuous stream of bytes with no built-in message boundaries. One send may arrive as two receives, and two sends may arrive as one, so a single receive can return only part of a message. Programs therefore loop until they have everything their protocol promises, using a rule for where a message ends, such as a length header.

About the Introduction to Operating Systems course

How many college credits is Introduction to Operating Systems?
Introduction to Operating Systems (Computer Science 354) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Introduction to Operating Systems cost and what is included?
$250, paid once, with lifetime access: all 83 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Introduction to Operating Systems take?
It is self-paced with no deadlines. The 83 lessons total about 10 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Introduction to Operating Systems.

83 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Updated

Introduction to Operating Systems
3 credits · NCCRS
Enroll →