CSSE 132 Mini-reading · Socket Programming II

Socket Servers: Bind, Listen, Accept

Continue from the client side to the server side. Allow about 6–8 minutes.

Why This Matters

In the client reading, your program knew an address and called connect. What must happen on the other end? A server prepares a place for connections, accepts one, and exchanges bytes. This reading helps you explain the workflow in Worksheet 23 and follow the server videos.

Core Idea: One Listener, a New Socket for Each Connection

The client initiates a connection. The server uses bind to choose a local address and port, then listen to become ready for incoming connections. Calling accept gives the server a new connected socket for one client.

Keep the two server descriptors separate: srv_sock listens; sess_sock exchanges bytes. The client has its own descriptor in its own process. Descriptor numbers are local handles, so the programs’ numbers need not match.

The listener remains separate from an accepted connection Inside the server, srv_sock accepts new connections. A separate sess_sock exchanges data with the client's socket. Closing sess_sock does not close srv_sock. Server process srv_sock: listening socket accept creates a new descriptor sess_sock: connected socket ↔ Client processclient socket
Send and receive on the connected pair. Keep the listener available for the next connection.

Start the server first. Once it is listening, the client can call connect. The server’s accept waits for a connection and returns a socket for communicating with that client.

Worked Examples

1. Choose an address and start listening

These fragments belong inside int main(void) and use <arpa/inet.h>, <sys/socket.h>, <stdio.h>, and <unistd.h>. Read setup first, then acceptance below. They demonstrate one connection; the application’s data exchange is left as a comment.

Prepare a local listener
C codeWhat this does
int srv_sock = socket(AF_INET, SOCK_STREAM, 0);
if (srv_sock == -1) { perror("socket"); return 1; }
Create the listening socket. A nonnegative descriptor is success; −1 is failure.
struct sockaddr_in srv_addr = {0};
srv_addr.sin_family = AF_INET;
srv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
srv_addr.sin_port = htons(9000);
Use IPv4 and 127.0.0.1 (this computer), just as in the client reading. htons converts the port to network byte order.
if (bind(srv_sock, (struct sockaddr *)&srv_addr,
         sizeof srv_addr) == -1) {
    perror("bind"); close(srv_sock); return 1;
}
Associate the socket with the local address and port. A bind failure must stop setup; release the socket before returning.
if (listen(srv_sock, 5) == -1) {
    perror("listen"); close(srv_sock); return 1;
}
Make the socket ready for incoming connections. The second argument sets a limit on connections waiting to be accepted; use 5 for this example.

The client must use the same address and port: 127.0.0.1 and 9000. Both programs run on your computer. The address selects the computer; the port selects the service.

2. Accept and track the two descriptors

Continue after successful listen
C codeWhat this does
int sess_sock = accept(srv_sock, NULL, NULL);
if (sess_sock == -1) {
    perror("accept"); close(srv_sock); return 1;
}
Wait for a connection and obtain a new connected descriptor. The two NULL arguments mean we do not need to collect the client’s address here. Check for failure before continuing.
/* Exchange bytes using sess_sock here. */
if (close(sess_sock) == -1) perror("close session");
if (close(srv_sock) == -1) {
    perror("close listener"); return 1;
}
Use sess_sock for this client’s data. Close the session when finished, then close the listener when the server stops. This example handles one connection.

Closing sess_sock leaves srv_sock available to accept another connection. A server can repeat the accept, exchange, and session-close steps for the next client.

3. Follow the bytes across several calls

Suppose three successful sends place AB, CD, and EF into one TCP connection, in that order. A receive requesting six bytes might return AB, ABC, or ABCDEF, depending on what is available. With a one-byte request, it can return only A. These are examples of permitted boundaries, not a required sequence.

The next receive continues after the bytes already consumed. TCP does not discard the earlier bytes just because a later send occurred. A large receiving buffer allows a larger result; it does not guarantee all six bytes arrive in one call. The application must decide when a complete request or response has arrived.

Carry forward the client reading’s rules: check the signed return value, reserve a byte when receiving text for %s, and add '\0' only after a positive count. Both endpoints can send and receive.

Common Mistakes

Using the listener for data

Use the descriptor returned by accept for this client’s send/recv calls.

Closing the wrong socket

Closing a session ends that local connection handle. Closing the listener stops accepting new connections; it does not close existing sessions.

Skipping an error check

Do not accept after bind or listen fails, and do not use a −1 session descriptor. Check results before proceeding.

Counting calls instead of bytes

Three sends do not imply three receives. Use actual return counts and the application’s completion rule.

Quick Reference

OperationPurpose / result
socketCreate a descriptor; −1 means failure.
bindChoose local address and port; 0 succeeds, −1 fails.
listenBecome ready for incoming connections; 0 succeeds, −1 fails.
acceptReturn a new connected descriptor, or −1 on error.
send / recvUse the connected descriptor and check signed byte counts.
closeRelease each descriptor when its job ends.

Check Yourself

  1. What must a server prepare before a client can connect? Which call gives the server its connected descriptor?
  2. Suppose socket returns 3 and accept returns 4. Which descriptor carries the client’s data? Which stays for future connections?
  3. After bind succeeds, listen returns −1. Should the program continue to accept? What needs cleanup?
  4. Three sends supply AB, CD, EF. The first receive returns ABC. Which bytes remain, and must the next receive return them all?
  5. The server uses port 9000, but the client tries port 9001. What should you check?

Answers

Show the answers
  1. Create the socket, set its local address, bind, and listen. Accept returns the connected descriptor.
  2. Use 4 for data and retain 3 as the listener. These numbers are illustrative, not fixed values to hard-code.
  3. No. Report the failure and close the socket already created; there is no accepted session to close.
  4. DEF remain in order. A later receive can still return a smaller portion; its requested size and actual return count matter.
  5. The client must connect to the port where this server listens. Use port 9000 in both programs; 9001 identifies a different service.

Next Step

Watch the server videos, then work through Worksheet 23. Explain why each step belongs on the server side, and track the two descriptors separately. Use the byte-stream example to reason about receive boundaries.

Use this reading with Worksheet 23 and the server lecture videos. Revisit the client reading for receiving text safely.