🎓 BookMCQ
← Back to 25. Introduction to Application Layer

📝 Iterative Programming Using UDP in Java (29 MCQs)

Sequential Datagram Processing with Java Networking Classes

A Java UDP server repeatedly receives datagrams through one DatagramSocket and sends a response for each request. DatagramPacket stores the payload, its length, and the sender's address and port. The server does not establish a TCP-style connection, and its loop can process packets from multiple clients sequentially. A single server loop can therefore alternate between unrelated client requests within its receive loop.

DatagramSocket Binding and Packet Construction

A server creates DatagramSocket bound to a known local port. It prepares a byte array and a DatagramPacket for reception, then calls receive. A client creates a DatagramPacket containing bytes, destination InetAddress, and destination port, and sends it through its DatagramSocket. The receiving packet must provide sufficient capacity for the expected message.

Receive, Interpret and Return a Datagram

The receive method fills the packet buffer and records sender metadata. The application uses the packet's actual length when decoding data, prepares a response byte array, and constructs a reply packet addressed to the sender. The send method transmits the datagram, after which the server repeats the receive operation. The application should reset packet length appropriately before reusing a receive packet.

A Java UDP Echo Exchange

A client sends the bytes for HELLO to a server at 192.0.2.60 port 6400 using DatagramPacket. The server receives the packet, copies only the received bytes, and creates a reply packet for the recorded sender address and port. The client receives the echoed datagram if the network delivers it.

Packet Length, Truncation and Response Reliability

A DatagramPacket's buffer capacity limits how much data a receive operation can store; a larger incoming datagram may be truncated. The application should decode only the received length and use a buffer appropriate to its protocol. DatagramSocket does not guarantee delivery, ordering, or duplicate suppression, so essential exchanges need application-level handling.

Java UDP Programming Misconceptions

'DatagramSocket preserves a reliable session' is false because UDP is connectionless. 'The whole byte array was received' ignores the packet's actual length and possible truncation. 'receive returns the sender as a separate object' is inaccurate because sender address and port are recorded in the DatagramPacket. A successful local send does not confirm delivery at the remote application.

Java Datagram API and Packet Tracing

Know how DatagramSocket binds, sends, and receives, and how DatagramPacket stores payload and endpoint data. Trace the sender address from an incoming packet into the reply packet, distinguish buffer capacity from received length, and state why UDP applications may need timeouts, acknowledgments, or request identifiers. Check the packet length before converting bytes into text or numeric values.

Java UDP Class and Packet Terms

  • DatagramSocket - Java class for UDP communication.
  • DatagramPacket - Object containing payload and datagram endpoint data.
  • receive - Waits for an incoming datagram.
  • send - Transmits a prepared datagram packet.
  • Packet length - Bytes actually carried in a datagram.
  • Packet buffer - Array used to store datagram payload bytes.
5
Easy
15
Medium
9
Hard

📝 All Iterative Programming Using UDP in Java MCQs

Q1. What is the size of a UDP port number?

A.8-bit
B.16-bit ✅
C.32-bit
D.64-bit
💡 Difficulty: easy | ✅ Correct: B

📖 Explanation: A UDP port number is defined as a 16‑bit unsigned integer. This size allows for 65,536 possible values, which the Internet Assigned Numbers Authority (IANA) partitions into well‑known, registered, and ephemeral ranges. Therefore the correct answer is the 16‑bit option.

Q2. Which of the following is the well‑known port number for HTTP?

A.21
B.80 ✅
C.443
D.25
💡 Difficulty: easy | ✅ Correct: B

📖 Explanation: The Hypertext Transfer Protocol (HTTP) historically uses port 80 as its well‑known service port. This number is reserved by IANA and cannot be used by other services on the same host, ensuring that web browsers connect to the correct server process. Hence option B is correct.

Q3. In UDP terminology, what does the term “ephemeral port” refer to?

A.A permanent server port
B.A temporary client port ✅
C.A reserved well‑known port
D.A broadcast port
💡 Difficulty: easy | ✅ Correct: B

📖 Explanation: Ephemeral ports are short‑lived ports assigned by the operating system to client processes when they initiate communication. They are drawn from a high‑number range (typically > 49152) and are released after the socket is closed, allowing reuse. This matches option B.

Q4. If a server binds to port 8080 and receives a packet from a client whose source port is 54321, what constitutes the server’s remote socket address for that interaction?

A.(Server IP,8080)
B.(Client IP,54321) ✅
C.(Server IP,0)
D.(Any IP,Any port)
💡 Difficulty: easy | ✅ Correct: B

📖 Explanation: The remote socket address is the client’s address as seen in the incoming packet: the client’s IP together with its source (ephemeral) port, here 54321. The server’s own address is the local socket address. Therefore the correct remote address is (Client IP,54321).

Q5. A client sends a UDP datagram to server 192.168.1.10 on port 5000 and the OS assigns it source port 40000. When the server replies, which port number must it use as the destination?

A.5000
B.40000 ✅
C.80
D.0
💡 Difficulty: easy | ✅ Correct: B

📖 Explanation: The server must address the reply to the client’s source (ephemeral) port, which is 40000. The destination port of the reply is taken from the client’s socket address contained in the received packet. Hence the correct destination is port 40000.

Q6. In an iterative UDP server, after serving client A the next packet arrives from client B. What must the server do to correctly address its response?

A.Reuse client A’s address
B.Use the address extracted from client B’s packet ✅
C.Broadcast to all clients
D.Ignore the packet
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: An iterative UDP server does not maintain persistent connections; each incoming datagram carries the sender’s address. To reply, the server simply uses the address information returned by recvfrom for that specific packet, which belongs to client B. Thus option B is the correct action.

Q7. Which statement best contrasts the state management of a TCP iterative server with that of a UDP iterative server?

A.TCP keeps a connection state per client; UDP does not maintain any state ✅
B.Both TCP and UDP maintain per‑client state in the same way
C.TCP is stateless; UDP maintains a connection state
D.Neither protocol uses socket addresses
💡 Difficulty: medium | ✅ Correct: A

📖 Explanation: TCP establishes a reliable connection, requiring the server to keep a socket (state) for each client, while UDP is connectionless and the server only processes each datagram independently, using the address supplied in the packet. This key contrast is captured in option A.

Q8. Which of the following statements about socket address uniqueness is true?

A.Two sockets on the same host can share the same IP and port if one uses TCP and the other UDP ✅
B.A socket address must be unique across all protocols on a host
C.Only the IP part needs to be unique; ports may be reused freely
D.Port numbers are irrelevant for socket uniqueness
💡 Difficulty: medium | ✅ Correct: A

📖 Explanation: Socket addresses are defined by the tuple (IP, port, protocol). Therefore, the same IP‑port combination can be used simultaneously by TCP and UDP because the protocol distinguishes them. Options B, C, and D ignore this rule, making A the correct statement.

Q9. How do well‑known ports differ from ephemeral ports regarding assignment and typical usage?

A.Well‑known ports are assigned by IANA for standard services; ephemeral ports are assigned dynamically by the OS for client use ✅
B.Both are assigned statically by the application developer
C.Ephemeral ports are lower numbers than well‑known ports
D.Well‑known ports change each time a program runs
💡 Difficulty: medium | ✅ Correct: A

📖 Explanation: Well‑known ports (0‑1023) are reserved by IANA for common services such as HTTP (80) or DNS (53). Ephemeral ports are high‑range numbers allocated by the operating system at runtime for temporary client endpoints. This distinction is precisely described in option A.

Q10. If a UDP server handles 1,000 clients sequentially, how does its average response latency compare to a multithreaded server that handles them concurrently?

A.Latency is lower because sequential processing avoids context switches
B.Latency is higher because each client must wait for the previous one to finish ✅
C.Latency is unchanged; UDP guarantees instant delivery
D.Latency becomes unpredictable and may exceed TCP latency
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: Sequential handling forces each client to wait for the server to finish processing the preceding request, increasing overall wait time. A multithreaded design can overlap processing, reducing per‑client latency. Therefore the sequential server exhibits higher average latency, as stated in option B.

Q11. How does a UDP server discover the remote socket address of a client that initiates communication?

A.It reads the address from the IP header of the received packet ✅
B.It queries a DNS server for the client’s address
C.It uses a pre‑configured configuration file
D.It guesses based on the client’s process ID
💡 Difficulty: medium | ✅ Correct: A

📖 Explanation: When a UDP datagram arrives, the recvfrom call returns both the payload and the sender’s socket address (IP and port). This address is extracted directly from the packet’s header, enabling the server to reply. Hence option A correctly describes the mechanism.

Q12. Which sequence correctly describes the steps a client follows to initiate communication with a UDP server?

A.Create socket → bind to a specific port → sendto → close
B.Create socket → sendto (OS assigns ephemeral port) → receive response → close ✅
C.Create socket → bind to well‑known port → listen → accept
D.Create socket → connect → send → receive
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: In UDP, the client typically creates a socket, calls sendto (providing the server’s address), and the OS automatically assigns an ephemeral source port. The client can then use recvfrom or similar to receive a reply before closing the socket. Option B captures this standard flow.

Q13. A developer wants to choose a custom server port that avoids conflict with well‑known services. Which range should they select?

A.0‑1023
B.1024‑49151
C.49152‑65535 ✅
D.Any range is acceptable
💡 Difficulty: medium | ✅ Correct: C

📖 Explanation: Ports 49152‑65535 are designated as dynamic or private (ephemeral) ports, generally not used by well‑known services. Selecting a port in this range reduces the risk of colliding with standard protocols. Therefore option C is the appropriate choice.

Q14. Two separate client processes on the same machine send UDP packets to the same server. How does the operating system ensure each packet is distinguishable?

A.It assigns each process a unique IP address
B.It gives each process a distinct ephemeral port number ✅
C.It adds a process identifier inside the UDP payload
D.It uses different MAC addresses for each process
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: The OS maintains a separate socket for each client process, allocating a unique 16‑bit ephemeral port for each. The combination of the host’s IP and the distinct port makes each client’s socket address unique, allowing the server to differentiate the sources. Hence option B is correct.

Q15. Why might using a fixed port number for a UDP client cause packet collisions when multiple instances run on the same host?

A.Because the OS will reject the second bind operation
B.Because the kernel will merge the packets into one stream
C.Because both instances will attempt to bind to the same (IP,port) tuple, causing address‑in‑use errors or packet overwriting ✅
D.Because fixed ports are reserved for servers only
💡 Difficulty: hard | ✅ Correct: C

📖 Explanation: When two client processes try to bind to the identical (IP, port) pair, the second bind fails unless SO_REUSEADDR is set, and even then incoming packets may be delivered nondeterministically, leading to collisions. This issue arises from the uniqueness requirement of socket addresses, making option C correct.

Q16. A server receives a malformed UDP packet whose source port field is zero. According to the UDP specification, how should the server treat this packet?

A.Process it normally, ignoring the zero port
B.Discard it because a zero source port is illegal in IPv4
C.Reply using port zero as the destination
D.Forward it to the TCP layer ✅
💡 Difficulty: hard | ✅ Correct: D

📖 Explanation: The UDP RFC specifies that a source port of zero is reserved and must not be used for normal communication. Packets with a zero source port are considered invalid and should be dropped without processing. Therefore the correct handling is described in option B.

Q17. After processing a client’s request, does an iterative UDP server need to close its socket before handling the next client?

A.Yes, it must close and reopen the socket each time
B.No, it can keep the same socket open for all clients ✅
C.It should close only if the client requests termination
D.It must close only when a fatal error occurs
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: An iterative UDP server typically creates a single socket, binds it to a well‑known port, and repeatedly calls recvfrom. Because UDP is connectionless, there is no per‑client state to release, so the socket remains open for the server’s entire lifetime. Option B reflects this practice.

Q18. What happens if a server binds to port 0 (letting the OS choose) before receiving client packets?

A.The OS assigns a random high‑number port, which the server must advertise to clients ✅
B.The server cannot receive any packets because port 0 is reserved
C.The server will listen on all ports simultaneously
D.The binding fails with an error code
💡 Difficulty: hard | ✅ Correct: A

📖 Explanation: Binding to port 0 signals the OS to allocate an available ephemeral port. The server then learns the assigned port via getsockname and must convey it to clients (e.g., via configuration) to be reachable. Therefore option A accurately describes the effect.

Q19. If a UDP client does not explicitly bind, how does the OS select an ephemeral port and what are the implications for NAT traversal?

A.The OS uses a fixed port for all clients, simplifying NAT mapping
B.The OS randomly selects an available high‑range port, creating a unique NAT mapping per client instance ✅
C.The OS disables NAT for unbound sockets
D.The OS requires manual NAT configuration
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: When a client calls sendto without prior bind, the OS automatically picks an unused ephemeral port from the designated range, ensuring each client instance gets a distinct mapping. This behavior aids NAT traversal because the NAT device can create a predictable mapping based on the chosen port. Hence option B is correct.

Q20. Even though UDP is connectionless, why does an iterative server still need to keep track of remote socket addresses?

A.To enforce TCP‑style handshakes
B.To know where to send the response for each received datagram ✅
C.To maintain a persistent session state
D.To encrypt the traffic
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: Each incoming UDP datagram contains the sender’s IP and port, which the server extracts via recvfrom. To reply, the server must use that exact address as the destination. Without storing this information, the server cannot direct its response correctly. Thus tracking remote addresses is essential, as described in option B.

Q21. If a server’s local address is 10.0.0.5:6000 and it receives a packet from client 10.0.0.8:5500, what is the complete socket address pair for this exchange?

A.(10.0.0.5:6000,10.0.0.8:5500) ✅
B.(10.0.0.8:5500,10.0.0.5:6000)
C.(10.0.0.5:5500,10.0.0.8:6000)
D.(10.0.0.8:6000,10.0.0.5:5500)
💡 Difficulty: medium | ✅ Correct: A

📖 Explanation: A socket address pair consists of the server’s local address (IP = 10.0.0.5, port = 6000) and the client’s remote address (IP = 10.0.0.8, port = 5500). The ordering (local, remote) matches option A, which correctly represents the communication endpoints.

Q22. A client mistakenly sends a datagram to port 80 (the HTTP well‑known port) instead of the intended UDP service port 5000. What is the most likely result?

A.The UDP server receives the packet on port 80
B.The packet is discarded because port 80 is reserved for TCP only
C.The packet reaches the HTTP server, which will ignore the UDP payload ✅
D.The packet is delivered to the correct UDP service despite the wrong port
💡 Difficulty: medium | ✅ Correct: C

📖 Explanation: Port 80 is typically bound by a TCP‑based HTTP server. Most operating systems allow UDP packets to be sent to a port even if a TCP listener exists, but the UDP stack will deliver the datagram to any UDP socket bound to that port (usually none). Consequently, the TCP HTTP server will receive the packet at the network layer but will ignore the UDP payload, making option C the most plausible outcome.

Q23. If a UDP server uses the generic recv call instead of recvfrom, what problem is introduced?

A.The server cannot receive any data
B.The server loses the sender’s address information, making replies impossible ✅
C.The server will automatically reply to the wrong client
D.The server will block indefinitely
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: recv reads data from a connected socket and does not provide the source address. Since UDP sockets are typically unconnected, using recv discards the sender’s IP and port, preventing the server from addressing a response correctly. Therefore the loss of sender information described in option B is the key issue.

Q24. How does the choice of port number influence the security posture of a UDP server?

A.Lower port numbers are always more secure
B.Using a well‑known port makes the service more visible to attackers ✅
C.Random high‑range ports are immune to all attacks
D.Port numbers have no impact on security
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: Selecting a well‑known port (e.g., 53 for DNS) signals the presence of a particular service, potentially attracting targeted attacks. Conversely, using a non‑standard high port can obscure the service, reducing exposure. Thus option B correctly captures the relationship between port choice and security visibility.

Q25. What role does the operating system play in providing the local socket address for both client and server processes?

A.It generates a random IP address for each process
B.It supplies the host’s IP address and assigns an appropriate port (fixed or ephemeral) ✅
C.It requires the application to manually input the address
D.It blocks the creation of socket addresses for security
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: When a process creates a socket, the OS knows the machine’s network interfaces and thus supplies the appropriate IP address. For servers, the OS may assign a fixed port (if specified) or for clients an ephemeral port. This automatic provisioning is described in option B.

Q26. Compare the resource usage of an iterative UDP server with a thread‑per‑client UDP server. Which statement is accurate?

A.Iterative servers consume more memory due to multiple sockets
B.Thread‑per‑client servers use fewer file descriptors because they share one socket
C.Iterative servers use a single socket and minimal threads, reducing memory and descriptor overhead compared to spawning a thread per client ✅
D.Both designs use identical resources
💡 Difficulty: medium | ✅ Correct: C

📖 Explanation: An iterative UDP server typically opens one socket and processes each datagram sequentially, requiring only one thread and a single file descriptor. In contrast, a thread‑per‑client design creates a new thread (and potentially a new socket) for each client, increasing memory and descriptor consumption. Option C correctly reflects this comparison.

Q27. Evaluate the impact of packet loss on an iterative UDP server’s ability to maintain correct client‑server communication. Which outcome is most likely?

A.The server will automatically retransmit lost packets
B.Lost packets cause the server to skip the corresponding client request, possibly leading to out‑of‑order processing ✅
C.Packet loss has no effect because UDP guarantees delivery
D.The server will switch to TCP when loss is detected
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: UDP does not provide reliability; if a datagram is lost, the server simply never receives that request. In an iterative design, the server proceeds to the next incoming packet, which may cause the client’s request to be missed or processed out of order. Therefore option B accurately describes the consequence.

Q28. Design a sequence diagram for an iterative UDP client‑server interaction, highlighting the exchange of socket addresses. Which step is essential in the diagram?

A.The client sends a SYN packet to establish a connection
B.The server replies with an ACK before data transfer
C.The client’s sendto includes its automatically assigned source port, which the server records from the received datagram ✅
D.The server performs a three‑way handshake
💡 Difficulty: hard | ✅ Correct: C

📖 Explanation: Even though UDP is connectionless, the client’s sendto operation embeds its source IP and ephemeral port in the packet header. The server extracts this information via recvfrom, establishing the remote socket address needed for the reply. This capture of address information is the critical step depicted in option C.

Q29. If a UDP server receives packets from clients behind different NAT devices, how can it reliably send responses without maintaining explicit state for each client?

A.By broadcasting to the network segment
B.By using the source address from each received packet as the destination for the reply ✅
C.By establishing a TCP tunnel through the NATs
D.By ignoring NAT and sending to the client’s private IP directly
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: When a NAT translates a client’s private address to a public one, the server sees the NAT’s public IP and port in the packet header. By replying to that exact source address (as obtained via recvfrom), the NAT forwards the response back to the appropriate internal client, eliminating the need for persistent server‑side state. Hence option B is correct.

🔗 Related Topics (MCQs)