Skip to content

Bug: Socket leak if hostname resolution fails in DdpClient constructor #1

@travisbreaks

Description

@travisbreaks

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 leaked

Suggested 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions