CSSE 132 · Lab 7 Reference
Client-Server Programming in C: A Visual Guide
The worksheet’s five client steps, with the server alongside. Allow about 8–10 minutes. Keep this page open while working on Lab 7.
Why This Matters
Lab 7 extends your database so another program can interact with it over a network. Your server manages the database; your client passes input and displays responses. Understand the order and purpose of the operations, and consult the reference for syntax.
The Big Picture
A client initiates a connection. A server listens for connections and handles requests. Both can send and receive. A socket is an operating-system communication endpoint, represented in C by an integer file descriptor.
An IP address identifies a network interface on a computer; a port identifies the service endpoint there. Lab 7’s server uses port 20000. Use 127.0.0.1 when both programs run in the same VM; to reach your partner, use the partner VM’s reachable address. Loopback always means your own machine.
The Five Steps
These are the five boxes in the client worksheet. The server has extra setup inside step 3. Fragments below are syntax reminders, not a complete client or server.
| Client | Server / what this does |
|---|---|
1. Create a socket | Both programs create an IPv4 TCP socket. AF_INET selects IPv4; SOCK_STREAM selects a byte stream. Save the returned descriptor. If it is −1, setup failed; stop before using it. |
2. Configure the address | The client describes the destination; the server describes its local listening address. Here ip is a dotted IPv4 string and port is an integer. htons converts the port to network byte order. Wrong addresses or missing conversion prevent the intended connection. The server may use INADDR_ANY to accept traffic on its local interfaces. |
3. Establish a connection | The server first calls bind and listen, then obtains a connected descriptor from accept. The client calls connect. The cast supplies the generic address-pointer type; the final argument is the structure’s size in bytes. Start the server first: connecting to an endpoint without a listener commonly gives “Connection refused.” |
4. Exchange bytes | Both sides use the connected socket. Lab 7’s client receives, prints, reads keyboard input, and sends it; this repeats. The server receives commands and sends responses. Check byte counts and errors. Receiving does not append a null terminator; reserve a byte and terminate only after a positive result. |
5. Close | Lab 7 asks the server to shut down and close the accepted client socket when that session ends. shutdown disables communication; close releases the descriptor. Keep the listener for subsequent clients; close it when the server exits. The client closes its own connected descriptor. Check failures and avoid using closed descriptors. |
On ARM64 Linux, descriptors are int, addresses are structures, and send/receive counts use ssize_t. Do not store a pointer in an integer descriptor. Use socklen_t for an address-length variable passed to accept.
Communication Timeline
| Client | Server |
|---|---|
| Create socket; configure destination. | Create socket; configure local address; bind; listen. |
| Connect → server. | Accept waits for a client, then returns a connected socket. |
| Receive ← server; display prompt. | Send prompt → client. |
| Read keyboard input; send command → server. | Receive command; process it; send response → client. |
| Receive response; repeat interaction. | Continue handling this client until the session ends. |
| Close connected socket when finished. | Shut down and close session socket; accept another client. Close listener when exiting. |
Waiting is normal: with the lab’s blocking sockets, accept waits for a connection, connect can wait for connection setup, and recv waits for bytes or connection closure. send can wait for buffer space. Keyboard input also waits. If both sides receive before either sends, neither can make progress: check whose turn it is.
When a Response Needs Multiple Sends
Lab 7’s client performs one receive before asking for the next input. This simple loop can make database responses appear “behind”: more response bytes may remain unread when the client asks you to type again.
For example, sending "red\n" and then "blue\n" does not guarantee two matching receives. A receive might return "red\nblue\n", only "re", or another available portion that fits the buffer. Remaining bytes stay available for later receives.
A complete application needs an agreed way to identify the end of each message, such as a delimiter or a length, and receives until that boundary. Simply adding a second receive can block if no more data arrives. Even one send can require several receives, and a send can report fewer bytes than requested.
For Lab 7: follow the provided interaction loop. You do not need to solve complete-message handling or redesign the protocol here; the lab leaves that for later work.
Socket Function Reference
Use <sys/socket.h> for socket operations, <arpa/inet.h> for IPv4 conversion, and <unistd.h> for close. Consult man 2 connect or the corresponding function’s manual in your VM.
| Function | Purpose / important parameters | Return / common problem |
|---|---|---|
socket | Create endpoint: family, type, protocol. | Descriptor ≥ 0; −1 on failure. Wrong type or resource limits. |
htons, inet_addr | Convert port / dotted IPv4 string. | Converted value; invalid IPv4 text gives INADDR_NONE with inet_addr. Use valid lab addresses. |
bind | Associate listener with local address: descriptor, address pointer, size. | 0 / −1. Port in use or address not local. |
listen | Enable connections: listener, backlog (queue limit). | 0 / −1. Invalid socket or setup. |
accept | Obtain session: listener, peer-address pointer, pointer to its length. Initialize length to storage size. | New descriptor ≥ 0 / −1. Invalid listener or interrupted wait. |
connect | Contact server: socket, destination pointer, size. | 0 / −1. Refused connection, timeout, unreachable address. |
send | Send bytes: connected socket, buffer, byte count, flags 0. | Bytes sent / −1. Short count or disconnected peer; sending after closure may also terminate the process via SIGPIPE. |
recv | Read bytes: connected socket, writable buffer, maximum count, flags 0. | Positive byte count; 0 means orderly peer closure for the lab’s nonzero requests; −1 means error. No automatic string terminator. |
shutdown | Disable communication: connected descriptor, SHUT_RDWR for both directions. | 0 / −1. Invalid or unconnected socket. |
close | Release descriptor. | 0 / −1. Invalid descriptor. Shutdown alone does not release it. |
setsockopt (provided) | Lab’s existing SO_REUSEADDR setup helps restart the listener. | 0 / −1. Invalid descriptor or option. Preserve the supplied setup. |
Common Problems and Debugging
- Connection refused: start the server and confirm it reached listen. Match the client’s destination port to 20000.
- Wrong machine: verify the VM’s reachable IP. Your partner’s loopback address refers to their own VM when used there, but to yours when used here.
- Bind fails: check whether another server already uses the port. Preserve the provided restart option; do not keep executing after failed setup.
- Program seems stuck: identify the waiting call. Check that the other side has reached the corresponding connection or sending operation.
- Socket operation fails: check immediately for −1, use
perror("function-name")to show the system error, and release sockets you successfully opened. - Garbled text: reserve space for
'\0'. For positive countn, terminate atbuffer[n]; never index with −1 or interpret zero as a new message.
Key Takeaways
Understand: the five steps, client versus listener versus accepted socket, whose turn it is to send, byte counts, and cleanup. Look up: function signatures, address casts, constants, and parameter order. You are not expected to memorize networking syntax.
Check Yourself
- Why must the server be listening before the client connects?
- Which server descriptor exchanges bytes with an accepted client?
- Does receiving five bytes automatically create a C string?
- Can two sends be read by one receive? Could one send need several receives?
Answers
- The destination needs a listening service to establish the connection.
- The descriptor returned by accept; the original listener remains available for new connections.
- No. Check the count and append a terminator within the buffer’s bounds.
- Yes to both. TCP preserves byte order, not send-call boundaries.
For byte-count details: Linux manual pages for send and recv.