package org.graylog2;

import java.io.IOException;
import java.net.*;
import java.util.List;

public class GelfSender {

    private static final int DEFAULT_PORT = 12201;

    private static final int PORT_MIN = 8000;
    private static final int PORT_MAX = 8888;

    private InetAddress host;
    private int port;
    private DatagramSocket socket;

    public GelfSender(String host) throws UnknownHostException, SocketException {
        this(host, DEFAULT_PORT);
    }

    public GelfSender(String host, int port) throws UnknownHostException, SocketException {
        this.host = InetAddress.getByName(host);
        this.port = port;
        this.socket = initiateSocket();
    }

    private DatagramSocket initiateSocket() throws SocketException {
        int port = PORT_MIN;

        DatagramSocket resultingSocket = null;
        boolean binded = false;
        while (!binded) {
            try {
                resultingSocket = new DatagramSocket(port);
                binded = true;
            } catch (SocketException e) {
                port++;

                if (port > PORT_MAX)
                    throw e;
            }
        }
        return resultingSocket;
    }

    public boolean sendMessage(GelfMessage message) {
        return message.isValid() && sendDatagrams(message.toDatagrams());
    }

    public boolean sendDatagrams(List<byte[]> bytesList) {
        for (byte[] bytes : bytesList) {
            DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length, host, port);
            try {
                socket.send(datagramPacket);
            } catch (IOException e) {
                return false;
            }
        }
        return true;
    }

    public void close() {
        socket.close();
    }
}

@@ -64,9 +64,154 @@
 net.
-*
+DatagramPacket;%0Aimport java.net.DatagramSocket;%0Aimport java.net.InetAddress;%0Aimport java.net.SocketException;%0Aimport java.net.UnknownHostException
 ;%0Aim
@@ -315,101 +315,8 @@
 1;%0A%0A
-    private static final int PORT_MIN = 8000;%0A    private static final int PORT_MAX = 8888;%0A%0A
     
@@ -817,431 +817,36 @@
     
-int port = PORT_MIN;%0A%0A        DatagramSocket resultingSocket = null;%0A        boolean binded = false;%0A        while (!binded) %7B%0A            try %7B%0A                resultingSocket = new DatagramSocket(port);%0A                binded = true;%0A            %7D catch (SocketException e) %7B%0A                port++;%0A%0A                if (port %3E PORT_MAX)%0A                    throw e;%0A            %7D%0A        %7D%0A        return resultingSocket
+return new DatagramSocket(0)
 ;%0A  

Simplify initialiazing a datagram by use source port 0 and letting OS find an available port