CSSE 132 Mini-reading · Socket Programming
Socket Clients: Connect, Exchange Bytes, Close
Connect the network ideas to C I/O. Allow about 7–9 minutes.
Why This Matters
You already know how a C program reads and writes files. A socket lets it exchange bytes with another program, using an interface similar to file I/O. This reading prepares you to follow the client demo and reason about received data in Worksheet 21.
Core Idea
A socket is a software interface for communication between programs, which can run on the same computer or different computers. The client initiates a connection to a server that is ready to accept it. These roles describe how the connection begins: after connecting, both programs can send and receive.
On Linux, a socket is represented in your program by an integer descriptor. This number is a handle managed by the operating system; it is neither the server's IP address nor its port. One computer can run both client and server programs, even for different applications at the same time.
- Create the client socket with
socket. - Set up the server address, including its IP address and port.
- Connect the socket to that destination with
connect. - Exchange bytes with
sendandrecv, following the application's rules. - Close the descriptor with
closewhen finished.
Creating a socket does not establish the connection. Preparing an address does not contact the server either: it fills in a C structure that the later connection call uses. Normally, the server must already be listening when the client attempts to connect.
Worked Examples
1. Describe the destination
These fragments illustrate the first steps; they are not a complete client program. Assume the declarations from <arpa/inet.h>, <string.h>, and <sys/socket.h> are available.
| C code | What this does |
|---|---|
| AF_INET selects IPv4; SOCK_STREAM with protocol 0 selects the default TCP stream protocol here. Success produces a descriptor; failure produces −1. |
| Declare the IPv4 address structure and clear its bytes before setting its fields. |
| Use IPv4, the loopback address (this computer), and an illustrative service port. inet_addr converts dotted IPv4 text; htons converts the 16-bit port to network byte order. |
The address is meaningful only if your intended server listens there. The legacy slides use an old campus address and port 80; neither is a promise of a running service today. This example uses a numeric address, so it does not perform DNS lookup.
int result = connect(sock, (const struct sockaddr *)&server,
sizeof server);
&server passes the address of the structure. The cast provides the general socket-address pointer type expected by connect; the size tells it how many bytes describe this address. Success returns 0; failure returns −1. Check the result before exchanging data, and close an already-created socket on a failure path. Include <unistd.h> for close.
2. Receive text without losing a byte
Assume sock is connected and the peer sends the four text bytes PING, without a null terminator. The following fragment handles one receive operation, not an entire application message. It also needs <stdio.h>.
| C code | What this does |
|---|---|
| Request at most 11 bytes, reserving the last array element for a terminator. Flags 0 selects ordinary receive behavior. The signed return type can represent −1. |
| Only a positive count identifies newly received bytes. If this call returns 4, indices 0–3 contain P, I, N, G; index 4 receives the terminator. The output is PING. |
| A zero result for this positive-length request means orderly end of the incoming stream. A negative result means an error. Neither case permits indexing the buffer with a negative count. |
recv copies bytes; it does not add '\0'. Printing an unterminated array with %s can read beyond its bounds: the behavior is undefined, so extra characters are only one possible symptom. Writing at buf[n - 1] instead erases the last received byte. Writing at buf[n] is safe here because the receive request reserved one element.
This example treats incoming bytes as text. Binary data can contain zero bytes, and %s would stop at the first one. Keep the returned byte count when processing arbitrary data.
3. Count bytes, not calls
TCP provides an ordered byte stream, not application message boundaries. Even if the peer sends PING in one call, your first receive might return only PI. A later receive can supply NG. Another receive can contain bytes from several sends together. The worksheet's output exercise assumes its described bytes arrive in the call; real code must use the actual return count.
send(sock, text, length, 0) likewise returns how many bytes it accepted, or −1 on error. A positive result can be smaller than the requested length. Continue with the remaining bytes when the application requires sending all of them. For text, strlen(text) counts characters before the terminator; sizeof on a pointer counts the pointer's bytes, not the text. Neither a send nor a receive call by itself defines a complete request or response.
Common Mistakes
Confusing descriptor and port
The descriptor selects your local socket; the destination structure identifies the server address and service.
Assuming clients only receive
Both endpoints can send and receive after connection. The application decides who speaks next.
Printing before checking the count
Check for error, end of stream, and available buffer space before adding a terminator.
Equating one call with one message
Use byte counts and the application's completion rule; TCP does not preserve send boundaries.
Quick Reference
| Operation | Remember |
|---|---|
socket | Create a descriptor; −1 indicates failure. |
sockaddr_in | IPv4 family, address, and port; use htons for the port. |
connect | Attempt connection; 0 succeeds, −1 fails. |
send / recv | Return signed byte counts; check errors and short transfers. |
| Text receive | Reserve one byte; if n > 0, terminate at buf[n]. |
close | Release the local descriptor when finished. |
Check Yourself
- A client successfully calls socket. Has it connected yet? What information does it need next?
- Can two programs on one computer communicate as client and server? Can both send bytes?
- The example receives four bytes into buf. Which index gets the terminator, and why is there space?
- Why must you check n before executing buf[n] = '\0'?
- The peer sends eight bytes once; recv returns three. Does this mean TCP lost the other five?
Answers
Show the answers
- No. Prepare the server's IP address and port, then call connect and check its result.
- Yes to both. The roles describe connection initiation, not one-way data flow.
- Index 4, immediately after indices 0–3. The request allows at most 11 bytes in a 12-byte array.
- An error returns −1, which would index outside the array. Zero means no new bytes from this positive-length stream receive.
- No. A short receive is allowed; subsequent calls can read remaining bytes. The application must determine when its data is complete.
Next Step
Use Worksheet 21 alongside the client demo. Label each step of the workflow, then track the valid buffer indices after each receive.