-
Notifications
You must be signed in to change notification settings - Fork 0
Bug: Socket leak if hostname resolution fails in DdpClient constructor #1
Copy link
Copy link
Open
Description
Hey! Was looking through the code and noticed a potential resource leak in the DdpClient constructor.
The Issue
If InetAddress.getByName(hostname) throws UnknownHostException, the DatagramSocket created on the previous line never gets closed:
this.socket = new DatagramSocket(); // socket created
this.targetAddress = InetAddress.getByName(hostname); // if this throws...
// socket is leakedSuggested Fix
Wrap the constructor in a try-catch that cleans up on failure:
DatagramSocket sock = null;
try {
sock = new DatagramSocket();
this.targetAddress = InetAddress.getByName(hostname);
this.socket = sock;
this.sendPacket = new DatagramPacket(new byte[0], 0, 0, targetAddress, port);
} catch (SocketException e) {
throw new DdpException("Failed to create UDP socket", e);
} catch (UnknownHostException e) {
if (sock != null) sock.close();
throw new DdpException("Invalid hostname: " + hostname, e);
}Also worth considering: implementing AutoCloseable so consumers can use try-with-resources:
public class DdpClient implements AutoCloseable {
// existing close() method already works
}Not urgent since this only triggers on bad hostnames, but good to tighten up before a wider release.
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels