🎓 BookMCQ
← Back to 25. Introduction to Application Layer

📝 Iterative Programming Using UDP in C (18 MCQs)

Datagram-Based Iteration with POSIX Socket Functions

A UDP server written in C repeatedly receives independent datagrams and responds to each sender. It creates a socket with the IPv4 address family and datagram type, binds a local address and port, and enters a receive loop. No TCP connection is established, and the server can process requests from different hosts through the same socket. The program can reuse the same bound descriptor for every incoming request.

IPv4 Datagram Socket and Endpoint Setup

The call socket(AF_INET, SOCK_DGRAM, 0) creates an IPv4 UDP socket. A sockaddr_in structure specifies the local family, port, and interface address for bind. Port values are converted with htons, and IPv4 address text can be converted with inet_pton before the server begins receiving packets. The address length passed to bind must match the structure supplied.

Receiving and Replying with Sender Metadata

Inside the loop, recvfrom fills a data buffer and updates a sockaddr structure with the sender's endpoint. The program validates the returned length and processes only those bytes. It then calls sendto using the captured address and length, so the response returns to the originating IP address and UDP port.

A Number-Conversion Datagram Service

A client sends the four-byte network representation of an unsigned integer to UDP port 6100. The C server receives the datagram, verifies that its length is four, converts the value with ntohl, and sends back a four-byte result using htonl and sendto. This example demonstrates explicit payload interpretation. The fixed payload size makes the request format straightforward to validate.

Datagram Boundaries and Application-Level Recovery

Each UDP receive operation returns one datagram, subject to the supplied buffer capacity; an oversized datagram can be truncated. UDP does not retransmit lost requests, preserve order, or suppress duplicates. If the service needs reliability, the application can add identifiers, acknowledgments, retry limits, and duplicate-request handling. Applications should also reject malformed payloads before interpreting numeric fields.

UDP Socket Programming Misconceptions in C

'A UDP server must call listen' is wrong because UDP has no TCP listening state. 'recvfrom returns a null-terminated string' is false because it returns a byte count. 'A reply is guaranteed after sendto succeeds' ignores possible loss after the local stack accepts the datagram. It is the application, not UDP, that decides whether to retry.

Tracing UDP Calls and Data Conversion

Know the sequence socket, bind, recvfrom, validate, process, sendto, and repeat. Identify sockaddr_in fields, htons and htonl conversions, and the sender address returned by recvfrom. Calculate buffer sizes from payload formats, distinguish one datagram from a TCP stream, and explain how an application could detect missing replies. Verify that payload lengths and integer conversions match the agreed message format.

C UDP Socket Function Terms

  • SOCK_DGRAM - Socket type used for UDP datagrams.
  • sockaddr_in - IPv4 address structure used by socket calls.
  • htons - Converts a 16-bit value to network order.
  • ntohl - Converts a 32-bit value to host order.
  • recvfrom - Receives a datagram with sender address information.
  • Datagram boundary - Preserved limit of one UDP message.
5
Easy
8
Medium
5
Hard

📝 All Iterative Programming Using UDP in C MCQs

Q1. Which field in the socket structure specifies the protocol family such as PF_INET?

A.Family ✅
B.Type
C.Protocol
D.Length
💡 Difficulty: easy | ✅ Correct: A

📖 Explanation: The Family field identifies the protocol family (e.g., PF_INET for IPv4). It tells the kernel how to interpret the address and port fields. The other fields serve different purposes, so the correct answer is the Family field, which is option A.

Q2. In a socket address structure, which field holds the port number that identifies the process?

A.IP address
B.Port number ✅
C.Length
D.Unused
💡 Difficulty: easy | ✅ Correct: B

📖 Explanation: The port number field uniquely identifies the local process for a given IP address. It is distinct from the IP address itself, which identifies the host. Therefore, the correct choice is the Port number field, listed as option B.

Q3. If a programmer mistakenly sets the socket Type field to SOCK_STREAM while intending to use UDP, what is the most likely immediate effect when sending data?

A.Data will be sent via UDP as intended
B.Data will be sent via TCP causing connection errors ✅
C.No data will be transmitted at all
D.Data will be sent but with increased latency
💡 Difficulty: easy | ✅ Correct: B

📖 Explanation: SOCK_STREAM creates a TCP socket, which expects a connection-oriented handshake. Sending data without establishing a TCP connection will cause errors such as ECONNRESET or ECONNREFUSED. Hence the immediate effect is a TCP-related error, making option B correct.

Q4. Which statement correctly compares PF_INET and PF_INET6?

A.PF_INET supports IPv6
B.PF_INET6 supports only IPv4
C.PF_INET is for IPv4 while PF_INET6 is for IPv6 ✅
D.Both are identical
💡 Difficulty: easy | ✅ Correct: C

📖 Explanation: PF_INET designates the IPv4 family, whereas PF_INET6 designates the IPv6 family. They are distinct families used to interpret addresses appropriately. The other options are inaccurate, so the correct comparison is option C.

Q5. When the Protocol field is set to 0 for a socket in the PF_INET family, which statement is true?

A.The operating system selects the default protocol for the family ✅
B.The socket cannot be used until a non‑zero protocol is specified
C.The programmer must manually specify TCP or UDP
D.The default protocol is UDP
💡 Difficulty: easy | ✅ Correct: A

📖 Explanation: A zero value tells the OS to choose the appropriate default protocol for the specified family. For PF_INET, the default is typically TCP for SOCK_STREAM sockets and UDP for SOCK_DGRAM sockets. Thus, option A correctly describes the behavior.

Q6. A UDP client binds its socket to port 0 (letting the OS choose). Later it sends a packet to a server. What can be inferred about the source port in the transmitted packet?

A.It will be 0
B.It will be an OS‑assigned ephemeral port ✅
C.It will be the same as the server’s port
D.It is unpredictable and may change per packet
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: When a socket is bound to port 0, the operating system allocates an unused ephemeral port for that socket. All outgoing packets from that socket will carry that assigned port as the source. Therefore, option B is the correct inference.

Q7. If a socket's local address field has IP address 0.0.0.0, what does this imply about the socket's binding behavior?

A.It is bound to all local interfaces ✅
B.It is bound to no interface and will reject traffic
C.It is bound only to the loopback interface
D.It causes a bind error
💡 Difficulty: medium | ✅ Correct: A

📖 Explanation: An IP address of 0.0.0.0 is a wildcard that instructs the kernel to bind the socket to every available network interface on the host. This enables the socket to receive traffic addressed to any of the host’s IPs. Hence, option A is correct.

Q8. Compare the effect of setting the socket Type to SOCK_DGRAM versus SOCK_RAW on the ability to receive ICMP error messages.

A.Both can receive ICMP errors
B.Only SOCK_RAW can receive ICMP errors ✅
C.Only SOCK_DGRAM can receive ICMP errors
D.Neither can receive ICMP errors
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: SOCK_RAW sockets expose the IP layer to the application, allowing receipt of low‑level messages such as ICMP errors. SOCK_DGRAM sockets operate at the UDP layer and do not deliver ICMP messages to the user space. Thus, option B is accurate.

Q9. Evaluate the impact on resource usage when creating 1000 iterative UDP sockets versus reusing a single socket for all iterations.

A.Multiple sockets consume more memory than a single socket ✅
B.Both approaches use roughly the same resources
C.Fewer sockets increase CPU usage because of context switches
D.Multiple sockets improve overall throughput
💡 Difficulty: medium | ✅ Correct: A

📖 Explanation: Each socket instance requires kernel structures (file descriptor, buffers, control blocks). Creating 1000 sockets therefore allocates significantly more memory than maintaining one socket and reusing it. The other statements misrepresent the resource trade‑offs, making option A correct.

Q10. How would you modify the socket address structure to support IPv6 communication while preserving existing code that uses PF_INET?

A.Change Family to PF_INET6 and add a flowinfo field
B.Replace the structure with sockaddr_in6 everywhere
C.Use conditional compilation to select the appropriate structure at build time ✅
D.It is impossible to support both families in one program
💡 Difficulty: medium | ✅ Correct: C

📖 Explanation: Conditional compilation (e.g., #ifdef) lets the same source code compile with either sockaddr_in (IPv4) or sockaddr_in6 (IPv6) based on a macro. This approach retains existing PF_INET code while enabling IPv6 support without rewriting the entire codebase, so option C is correct.

Q11. When implementing an iterative UDP server, why is it unnecessary to call listen() on the socket?

A.Because UDP is connectionless and does not establish a listening queue ✅
B.Because listen() would block indefinitely on a UDP socket
C.Because listen() sets a timeout that is irrelevant for UDP
D.Because listen() automatically converts the socket to TCP
💡 Difficulty: medium | ✅ Correct: A

📖 Explanation: listen() is only meaningful for connection‑oriented protocols like TCP, where it prepares a backlog queue for incoming connections. UDP is connectionless; packets are received directly via recvfrom() without a listening state. Therefore, option A correctly explains why listen() is not required.

Q12. Suppose you need to send a large message that exceeds the typical UDP datagram size limit. Which strategy best synthesizes UDP usage with application‑level fragmentation?

A.Split the message into multiple UDP packets, each with sequence numbers ✅
B.Increase the socket’s send buffer to accommodate the whole message
C.Switch to TCP for reliable delivery
D.Rely on IP‑level fragmentation performed by the kernel
💡 Difficulty: medium | ✅ Correct: A

📖 Explanation: Because UDP does not guarantee delivery or ordering, the application must handle fragmentation. Dividing the data into smaller packets, tagging each with a sequence number, and reassembling on the receiver side provides a reliable approach while staying within UDP’s size constraints. Option A reflects this strategy.

Q13. If a programmer forgets to set the Length field of the local socket address before calling bind(), what is the most probable outcome?

A.bind() succeeds using a default length value
B.bind() fails with an EINVAL error ✅
C.bind() succeeds but the address information is ignored
D.The behavior is undefined and may cause a crash
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: The Length field tells the kernel how many bytes of the address structure are valid. If it is left unset (often zero), bind() cannot determine the address size and typically returns EINVAL, indicating an invalid argument. Hence, option B describes the likely result.

Q14. During an iterative UDP client loop, the client receives a packet from an unexpected source IP. Assuming the socket was bound to a specific local address, which inference about the network is most plausible?

A.Network address translation altered the source address
B.The packet is a spoofed injection attempting to masquerade as a legitimate sender ✅
C.The operating system ignored the binding and accepted any source
D.The network is using multicast and the packet is part of it
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: UDP provides no built‑in authentication, so a receiver can get packets from any IP address. If the client expected a specific server, an unexpected source most likely indicates a spoofed packet crafted by an attacker, making option B the best inference.

Q15. Contrast the error handling mechanisms available for SOCK_DGRAM versus SOCK_STREAM sockets when a remote host becomes unreachable. Which statement accurately reflects the difference?

A.SOCK_DGRAM provides an immediate error via recvfrom()
B.SOCK_STREAM reports the error on the next send() call ✅
C.Both provide the same error notification semantics
D.SOCK_DGRAM cannot detect an unreachable host at all
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: TCP (SOCK_STREAM) maintains a connection state, so when the remote host disappears, the next send() operation fails with an error such as ECONNRESET. UDP (SOCK_DGRAM) is connectionless and does not generate a direct error when the peer is unreachable; the application may only infer loss through timeouts. Therefore, option B is correct.

Q16. Assess the security implications of using SOCK_RAW sockets for UDP communication compared to SOCK_DGRAM. Which of the following best captures the risk?

A.SOCK_RAW bypasses kernel checks, allowing packet spoofing ✅
B.SOCK_DGRAM allows full packet spoofing as well
C.Both socket types are equally risky in this regard
D.SOCK_RAW is actually safer because it gives more control
💡 Difficulty: hard | ✅ Correct: A

📖 Explanation: RAW sockets expose the entire IP packet to user space, letting applications set arbitrary source addresses and headers. This capability can be abused to forge packets, facilitating attacks such as IP spoofing. SOCK_DGRAM sockets are limited to proper UDP handling, making option A the accurate risk description.

Q17. Design an iterative UDP server that must handle both IPv4 and IPv6 clients without code duplication. Which architectural approach best achieves this goal?

A.Create separate sockets for each family and poll them
B.Use a single IPv4‑mapped IPv6 socket to receive both types
C.Use a dual‑stack socket with AF_INET6 and IPV6_V6ONLY disabled ✅
D.Convert IPv6 addresses to IPv4 before processing
💡 Difficulty: hard | ✅ Correct: C

📖 Explanation: A dual‑stack socket created with AF_INET6 and configured with IPV6_V6ONLY set to 0 can accept both IPv6 and IPv4‑mapped IPv6 addresses on the same file descriptor. This eliminates the need for separate code paths, fulfilling the requirement for minimal duplication. Option C captures this design.

Q18. Synthesize a method to reliably measure round‑trip time (RTT) for UDP packets in an iterative client, considering UDP's lack of built‑in acknowledgments. Which technique is most appropriate?

A.Embed a timestamp in the payload and compute the difference upon receipt ✅
B.Rely on operating‑system provided timestamps for send and receive events
C.Use ICMP echo requests instead of UDP packets
D.Assume a constant RTT based on network specifications
💡 Difficulty: hard | ✅ Correct: A

📖 Explanation: Because UDP does not guarantee delivery, the client must embed a send‑time value within each packet. When the server echoes the payload back, the client subtracts the embedded timestamp from the current time to obtain the RTT. This method directly measures the round‑trip delay, making option A the correct approach.

🔗 Related Topics (MCQs)