🎓 BookMCQ
← Back to 25. Introduction to Application Layer

📝 Iterative Programming Using TCP in C (21 MCQs)

Sequential TCP Service with POSIX Socket Calls

An iterative TCP server in C handles one accepted client at a time. It creates a stream socket, binds a local endpoint, calls listen, and repeatedly accepts connections. For each client, the program exchanges application data through the connected descriptor, closes that descriptor, and returns to accept while retaining the listening socket. The server's main loop therefore controls when the next client is served.

Listening Endpoint and Per-Client Descriptor

The listening descriptor represents the server service address and pending connection queue. Each successful accept returns a different descriptor associated with one client connection. The server uses the connected descriptor for recv or send, while the listening descriptor remains open for future clients until service shutdown. It is common to keep the two descriptors in separate variables.

Accept, Read, Respond and Close Sequence

After the TCP handshake completes, accept returns a connected socket. The server reads request bytes, checks their length and format, sends a response, and closes the client descriptor. It then repeats accept. Because TCP is a byte stream, the application must define delimiters or length fields for complete messages. The accepted descriptor remains valid only for that particular connection.

An Iterative Uppercase Server

A client connects to a C server on TCP port 6200 and sends a line terminated by a newline. The server reads bytes from the accepted socket until the delimiter appears, converts the characters, and writes the result back. It closes the connection and accepts the next client. The newline defines the application record, not a TCP segment boundary.

Stream Handling and Connection Lifecycle

A single send or recv call is not guaranteed to transfer an entire application message. Programs should loop over partial transfers, handle orderly closure, and distinguish transient errors from fatal ones. The server must close each accepted descriptor before reusing the sequential handler, but must not close its listening descriptor after every client.

C TCP Server Misconceptions

'accept returns the listening socket' is incorrect because it returns a new connected descriptor. 'recv always fills the buffer' is false because it may return fewer bytes. 'Closing the connected descriptor stops the server' is wrong when the listening descriptor is still open and the accept loop continues. The listener is closed separately when the service itself is stopped.

Tracing TCP Setup and Descriptor Use

For examinations, order socket, bind, listen, accept, receive, send, close, and repeat. Mark which descriptor is used for new connection requests and which carries client data. Explain stream framing, partial transfers, peer shutdown, and why a slow connected client can delay every later client in an iterative design. A complete-transfer routine must also detect closure before the expected length arrives.

C TCP Socket Function Terms

  • SOCK_STREAM - Socket type commonly used for TCP.
  • listen - Prepares a bound TCP socket for connections.
  • accept - Returns a descriptor for one client connection.
  • Connected socket - Endpoint used for an established TCP exchange.
  • Partial read - Receive operation returning fewer available bytes.
  • Delimiter - Marker used to identify a message ending.
6
Easy
7
Medium
8
Hard

📝 All Iterative Programming Using TCP in C MCQs

Q1. Which function converts a short integer from host byte order to network byte order?

A.htons ✅
B.htonl
C.ntohs
D.ntohl
💡 Difficulty: easy | ✅ Correct: A

📖 Explanation: The htons function translates a 16‑bit value from the host’s native byte ordering to the standardized network byte ordering, ensuring that port numbers are correctly interpreted by remote hosts regardless of endianness.

Q2. In the code snippet, what is the purpose of the memset function applied to the server address structure?

A.Initialize all fields to zero ✅
B.Allocate memory for the structure
C.Close the socket descriptor
D.Set the port number
💡 Difficulty: easy | ✅ Correct: A

📖 Explanation: memset fills the entire sockaddr_in structure with zeros, clearing any residual data and providing a clean slate for subsequent field assignments such as sin_family, sin_port, and sin_addr.

Q3. If the socket() call returns -1, what will the program do next?

A.Continue execution
B.Print an error message and exit ✅
C.Retry the socket call
D.Ignore the error and proceed
💡 Difficulty: easy | ✅ Correct: B

📖 Explanation: A return value of -1 signals failure; the surrounding if‑statement detects this condition, prints an informative error, and terminates the program to avoid undefined behavior from an invalid descriptor.

Q4. Suppose htons(8080) is used to set the port. What would happen if the programmer mistakenly used htonl instead?

A.The port would be set correctly
B.The port field would become corrupted, causing bind() to fail ✅
C.The program would crash immediately
D.There would be no effect on the program
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: htonl converts a 32‑bit value, not a 16‑bit port; placing the result in sin_port corrupts the field, so bind() receives an invalid port and typically returns an error such as EINVAL.

Q5. Which approach provides earlier detection of failures in a TCP server initialization?

A.Checking the return value of socket() immediately after the call
B.Checking the return value of bind() after socket() succeeds
C.Both checks detect failures at the same stage
D.Neither check is necessary for error detection ✅
💡 Difficulty: easy | ✅ Correct: D

📖 Explanation: Detecting an error right after socket() gives the earliest possible feedback; if socket() fails, there is no point in proceeding to bind(), making the early check the most proactive strategy.

Q6. Why must the IP address be converted with htonl before being placed in the sockaddr_in structure?

A.To ensure the address is in network byte order ✅
B.To compress the address into fewer bytes
C.To encrypt the address for security
D.To increase the speed of transmission
💡 Difficulty: easy | ✅ Correct: A

📖 Explanation: Network protocols expect addresses in big‑endian order; htonl transforms the host‑order 32‑bit address into this format, guaranteeing that the receiving side interprets the address correctly across differing architectures.

Q7. Given that len holds the length of the incoming string, what is the effect of calling recv(s, buffer, len, 0) when len is larger than the actual data received?

A.It causes a buffer overflow
B.Only the actual number of bytes received are written to the buffer ✅
C.The excess bytes are filled with zeros
D.The socket is automatically closed
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: recv() writes at most the number of bytes actually transmitted; if len exceeds that amount, the function simply returns the smaller count, leaving the remainder of the buffer unchanged.

Q8. Which of the following best describes the difference between iterative and concurrent server designs in the context of TCP socket programming?

A.Iterative servers handle one client at a time, while concurrent servers use fork or threads to handle multiple clients simultaneously
B.Iterative servers use select() to multiplex connections, while concurrent servers use poll()
C.Iterative servers rely on UDP, whereas concurrent servers rely on TCP
D.Both designs are identical in their handling of client connections ✅
💡 Difficulty: medium | ✅ Correct: D

📖 Explanation: Concurrent servers create a new execution context (process or thread) for each accepted connection, allowing multiple clients to be served in parallel, whereas iterative servers process one client completely before returning to accept the next.

Q9. If a server repeatedly calls accept() inside a while loop, how does this pattern contribute to the iterative model’s ability to serve multiple clients?

A.It creates new processes for each client
B.It sequentially handles each client, returning to accept() only after the current client’s session ends ✅
C.It buffers incoming data for all clients simultaneously
D.It changes the underlying transport protocol from TCP to UDP
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: The loop blocks on accept() until a client connects; after the server finishes communicating with that client, the loop iterates and calls accept() again, thereby serving clients one after another in a deterministic sequence.

Q10. Assume the server socket is bound to port 0 (letting the OS choose). After bind(), which function can retrieve the assigned port, and why is this useful for iterative servers?

A.getsockname
B.getpeername
C.inet_ntoa
D.getsockname ✅
💡 Difficulty: medium | ✅ Correct: D

📖 Explanation: getsockname extracts the local address information of a bound socket, including the automatically assigned port number; knowing this port enables the server to advertise or log the actual listening endpoint, which is essential when the port is chosen dynamically.

Q11. Evaluate the impact of not calling close(s) after finishing communication with a client in an iterative TCP server.

A.It leads to a resource leak that can exhaust file descriptors ✅
B.It causes the server to terminate immediately
C.The operating system automatically reclaims the descriptor, so there is no impact
D.It improves performance by keeping the descriptor open
💡 Difficulty: easy | ✅ Correct: A

📖 Explanation: Each successful close releases the underlying file descriptor back to the OS; omitting it leaves descriptors allocated, and after enough iterations the process can run out of descriptors, preventing new connections from being accepted.

Q12. How does converting both the port and IP address to network byte order affect portability across big‑endian and little‑endian architectures?

A.It eliminates endianness issues, allowing the same binary to run on any architecture
B.It doubles the transmission time due to extra conversion steps
C.It requires additional code but offers no practical benefit
D.It ensures correct interpretation of the values on both big‑endian and little‑endian systems ✅
💡 Difficulty: medium | ✅ Correct: D

📖 Explanation: By presenting the port and address in the standardized big‑endian (network) format, the server guarantees that any peer—regardless of its native byte ordering—will decode the values correctly, which is the core of portable network programming.

Q13. If a programmer mistakenly swaps the arguments of htons and htonl when setting sin_port and sin_addr, respectively, which of the following sequences of events is most likely?

A.bind() succeeds and the server listens on the intended address
B.bind() fails with EINVAL due to an invalid address structure ✅
C.The server receives data but interprets it incorrectly
D.The server crashes during socket creation
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: Applying htons to a 32‑bit address and htonl to a 16‑bit port corrupts both fields; bind() validates the address family and port, detects the malformed values, and typically returns an error such as EINVAL.

Q14. Consider two implementations of an iterative server: one uses a fixed-size buffer of 256 bytes, the other dynamically allocates a buffer based on len. Which approach better adheres to the principle of resource efficiency, and why?

A.The fixed buffer is more efficient because allocation overhead is avoided
B.The dynamic approach avoids wasting memory when messages are small, aligning resource usage with actual demand ✅
C.Both approaches are equally efficient in modern operating systems
D.The fixed buffer is better because it simplifies code and reduces fragmentation
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: Allocating exactly the amount of memory required for each message prevents over‑provisioning; although dynamic allocation incurs a small overhead, it scales with the workload and prevents the server from holding unnecessary memory for short messages.

Q15. Synthesize a short algorithm that combines memset, htons, htonl, socket, bind, listen, and accept to create a minimal iterative TCP server. Which step must occur immediately after socket() and before bind()?

A.listen()
B.memset() ✅
C.htons()
D.htonl()
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: After obtaining a fresh socket descriptor, the server must prepare the sockaddr_in structure; memset() zeroes the structure so that fields like sin_family, sin_port, and sin_addr can be safely set before the bind() call.

Q16. When the server receives a SIGINT during a blocking accept() call, what is the typical behavior of the accept() function, and how should the program respond to ensure graceful shutdown?

A.accept() returns -1 with errno set to EINTR, and the program should close the listening socket and exit cleanly ✅
B.accept() continues waiting for a new connection, ignoring the signal
C.accept() raises a C++ exception that must be caught
D.accept() automatically closes the socket and terminates the process
💡 Difficulty: hard | ✅ Correct: A

📖 Explanation: POSIX specifies that a signal interrupting a blocking system call causes the call to fail with EINTR; detecting this return value lets the server break out of the accept loop, close resources, and shut down in an orderly manner.

Q17. Compare the effect of using SOCK_STREAM versus SOCK_DGRAM when creating the socket descriptor for an iterative TCP server. Which statement is accurate?

A.SOCK_STREAM provides a reliable, ordered byte stream suitable for TCP, while SOCK_DGRAM provides message‑oriented, unordered datagrams suitable for UDP ✅
B.SOCK_STREAM provides ordered datagrams, while SOCK_DGRAM provides a reliable stream
C.SOCK_STREAM is used only for IPv6, whereas SOCK_DGRAM is for IPv4
D.Both constants are interchangeable for TCP servers
💡 Difficulty: hard | ✅ Correct: A

📖 Explanation: TCP requires SOCK_STREAM because it guarantees delivery, ordering, and flow control; SOCK_DGRAM corresponds to UDP, which lacks these guarantees and therefore cannot be used for a traditional iterative TCP server.

Q18. Explain why an iterative TCP server cannot handle a client that remains idle for an extended period without affecting other clients, and propose a modification to mitigate this limitation.

A.Because the server uses UDP, which does not maintain connections
B.Because the server closes the socket after each request, preventing idle connections
C.Because the server blocks on recv() for the active client, preventing the loop from reaching accept() for new connections ✅
D.Because the server operates only on IPv6 addresses
💡 Difficulty: hard | ✅ Correct: C

📖 Explanation: An iterative server processes one client at a time; if that client blocks on recv(), the server never returns to accept() and therefore cannot serve additional clients. Using non‑blocking sockets or multiplexing with select()/poll() allows the server to detect idle periods and continue accepting new connections.

Q19. What does the variable 'len' typically represent in the context of an echo server's receive loop?

A.The socket descriptor used for communication
B.The length of the message to be sent back to the client
C.The length of the string to be echoed back to the client ✅
D.The port number on which the server listens
💡 Difficulty: medium | ✅ Correct: C

📖 Explanation: In a simple echo server, 'len' is commonly set to the number of bytes read from the client (often the return value of recv()) and then used to determine how many bytes to write back, effectively representing the length of the echoed string.

Q20. Given the code fragment: int s; char buffer[256]; int len = sizeof(buffer); ssize_t n = recv(s, buffer, len, 0); If n returns -1, which of the following is the most appropriate immediate action?

A.Retry the recv() call immediately
B.Print an error message, close the socket descriptor, and exit or continue as appropriate ✅
C.Ignore the error and continue processing
D.Reset len to zero and call recv() again
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: A negative return from recv() indicates an error (e.g., connection reset or EINTR); the prudent response is to report the condition, release the socket resource, and decide whether to terminate or restart based on the error type.

Q21. If an iterative server must support both IPv4 and IPv6 clients, which structure and associated functions should replace sockaddr_in and how does this affect the use of htons/htonl?

A.Use sockaddr_in6 and replace htons/htonl with htons6/htonl6
B.Use sockaddr_in6 and continue using htons for port and htonl for address
C.Use sockaddr_in6 and use htons for port while address is set with in6addr_any (no htonl needed) ✅
D.Use sockaddr_in6 and rely on getaddrinfo which provides network‑order fields automatically
💡 Difficulty: hard | ✅ Correct: C

📖 Explanation: IPv6 addresses are stored in network order by default; the port still requires htons conversion, but the address field does not need an additional htonl step, making option C the correct description of the required adjustments.

🔗 Related Topics (MCQs)