Example usage for java.net DatagramSocket setReuseAddress

List of usage examples for java.net DatagramSocket setReuseAddress

Introduction

In this page you can find the example usage for java.net DatagramSocket setReuseAddress.

Prototype

public synchronized void setReuseAddress(boolean on) throws SocketException 

Source Link

Document

Enable/disable the SO_REUSEADDR socket option.

Usage

From source file:poisondog.net.udp.DatagramMission.java

public DatagramResponse execute(DatagramParameter parameter) throws IOException {
    DatagramSocket socket = new DatagramSocket(null);
    socket.setReuseAddress(true);

    socket.setBroadcast(parameter.getBroadcast());
    if (parameter.getTimeout() > 0)
        socket.setSoTimeout(parameter.getTimeout());
    String data = IOUtils.toString(parameter.getInputStream());
    DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length());
    packet.setAddress(InetAddress.getByName(parameter.getHost()));
    packet.setPort(parameter.getPort());
    socket.send(packet);/*from w w  w.ja  v a2s . c  o  m*/

    DatagramResponse response = new DatagramResponse(parameter.getResponseLength());
    DatagramPacket responsePacket = new DatagramPacket(response.getContent(), response.getContent().length);
    socket.receive(responsePacket);
    response.setAddress(responsePacket.getAddress().getHostAddress());
    response.setPacketLength(responsePacket.getLength());
    socket.close();
    return response;
}

From source file:com.chiralBehaviors.slp.hive.configuration.BroadcastConfiguration.java

@Override
public Engine construct() throws IOException {
    Tuple<NetworkInterface, InetSocketAddress> tuple = getNetworkInterface();
    DatagramSocket socket = new MulticastSocket(new InetSocketAddress(port));
    socket.setReuseAddress(true);
    socket.setBroadcast(true);/* ww w.j  ava  2 s  .  c o  m*/
    return new MulticastEngine(getFdFactory(), Generators.timeBasedGenerator(), heartbeatPeriod, heartbeatUnit,
            socket, tuple.b, receiveBufferMultiplier, sendBufferMultiplier, getMac(), tuple.a);
}

From source file:org.openacs.HostsBean.java

public void RequestConnectionUDP(String url, String user, String pass) throws Exception {
    DatagramSocket s = new DatagramSocket(null);
    s.setReuseAddress(true);
    s.bind(new InetSocketAddress(Application.getSTUNport()));
    String ts = Long.toString(Calendar.getInstance().getTimeInMillis());
    String id = ts;/*from  w  ww. j a va2 s .c om*/
    Random rnd = new Random();
    byte[] nonceArray = new byte[16];
    rnd.nextBytes(nonceArray);

    String cn = cvtHex.cvtHex(nonceArray);
    url = url.substring(6);
    String[] u = url.split(":");

    SecretKeySpec signingKey = new SecretKeySpec(pass.getBytes(), HMAC_SHA1_ALGORITHM);
    Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
    mac.init(signingKey);
    String data = ts + id + user + cn;
    byte[] rawHmac = mac.doFinal(data.getBytes());
    String signature = cvtHex.cvtHex(rawHmac);
    String req = "GET http://" + url + "?ts=" + ts + "&id=" + id + "&un=" + user + "&cn=" + cn + "&sig="
            + signature + " HTTP/1.1\r\n\r\n";

    byte[] breq = req.getBytes();
    DatagramPacket packet = new DatagramPacket(breq, breq.length);
    packet.setAddress(InetAddress.getByName(u[0]));
    packet.setPort(Integer.parseInt(u[1]));
    s.send(packet);
}

From source file:org.kde.kdeconnect.Backends.LanBackend.LanLinkProvider.java

@Override
public void onStart() {

    //This handles the case when I'm the existing device in the network and receive a "hello" UDP package

    udpAcceptor.setHandler(udpHandler);//from  w ww  .  j  a va 2  s  .  c  o  m

    try {
        udpAcceptor.bind(new InetSocketAddress(port));
    } catch (Exception e) {
        Log.e("LanLinkProvider", "Error: Could not bind udp socket");
        e.printStackTrace();
    }

    boolean success = false;
    int tcpPort = port;
    while (!success) {
        try {
            tcpAcceptor.bind(new InetSocketAddress(tcpPort));
            success = true;
        } catch (Exception e) {
            tcpPort++;
        }
    }

    Log.i("LanLinkProvider", "Using tcpPort " + tcpPort);

    //I'm on a new network, let's be polite and introduce myself
    final int finalTcpPort = tcpPort;
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... voids) {
            String deviceListPrefs = PreferenceManager.getDefaultSharedPreferences(context)
                    .getString(KEY_CUSTOM_DEVLIST_PREFERENCE, "");
            ArrayList<String> iplist = new ArrayList<String>();
            if (!deviceListPrefs.isEmpty()) {
                iplist = CustomDevicesActivity.deserializeIpList(deviceListPrefs);
            }
            iplist.add("255.255.255.255");
            for (String ipstr : iplist) {
                try {
                    InetAddress client = InetAddress.getByName(ipstr);
                    NetworkPackage identity = NetworkPackage.createIdentityPackage(context);
                    identity.set("tcpPort", finalTcpPort);
                    byte[] b = identity.serialize().getBytes("UTF-8");
                    DatagramPacket packet = new DatagramPacket(b, b.length, client, port);
                    DatagramSocket socket = new DatagramSocket();
                    socket.setReuseAddress(true);
                    socket.setBroadcast(true);
                    socket.send(packet);
                    //Log.i("LanLinkProvider","Udp identity package sent to address "+packet.getAddress());
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("LanLinkProvider",
                            "Sending udp identity package failed. Invalid address? (" + ipstr + ")");
                }
            }

            return null;

        }

    }.execute();

}

From source file:IntergrationTest.OCSPIntegrationTest.java

/**
 * Method to test a port is available.//from ww w .j  a v  a  2s.  c  om
 *
 * @param port
 *
 * @return
 */
private boolean available(int port) {
    if (port < MIN_PORT_NUMBER || port > MAX_PORT_NUMBER) {
        throw new IllegalArgumentException("Invalid start port: " + port);
    }
    ServerSocket ss = null;
    DatagramSocket ds = null;
    try {
        ss = new ServerSocket(port);
        ss.setReuseAddress(true);
        ds = new DatagramSocket(port);
        ds.setReuseAddress(true);
        return true;
    } catch (IOException e) {
    } finally {
        if (ds != null) {
            ds.close();
        }
        if (ss != null) {
            try {
                ss.close();
            } catch (IOException e) {
                /* should not be thrown */
            }
        }
    }
    return false;
}

From source file:org.wso2.carbon.analytics.common.jmx.agent.JmxAgentWebInterface.java

/**
 * Test the availability of the DataPublisher by
 * trying to connect to it (credentials are not checked)
 *
 * @return : whether the test was successful or not
 */// www.j  ava  2 s  .  c o  m
public boolean testDataPublisherAvailability(String connectionType, String url, int port) {

    //check for tcp and ssl port availability
    if (connectionType.equalsIgnoreCase("tcp://") || connectionType.equalsIgnoreCase("ssl://")) {

        DatagramSocket ds = null;

        try {
            ds = new DatagramSocket(port);
            ds.setReuseAddress(true);

            return true;
        } catch (IOException e) {
            log.error(e);
        } finally {
            if (ds != null) {
                ds.close();
            }
        }
    }

    //check for http and https port availability
    if (connectionType.equalsIgnoreCase("http://") || connectionType.equalsIgnoreCase("https://")) {

        Socket socket = null;

        try {
            socket = new Socket();
            socket.setReuseAddress(true);

            SocketAddress sa = new InetSocketAddress(url, port);
            socket.connect(sa);
            return true;
        } catch (IOException e) {
            log.error(e);
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    //do nothing
                }
            }
        }
    }

    return false;
}

From source file:org.limewire.mojito.io.MessageDispatcherImpl.java

@Override
public void bind(SocketAddress address) throws IOException {
    synchronized (lock) {
        if (isBound()) {
            throw new IOException("DatagramChannel is already bound");
        }/*  ww w  .  j  a v  a2s  . c  o m*/

        channel = DatagramChannel.open();
        channel.configureBlocking(false);

        selector = Selector.open();
        channel.register(selector, SelectionKey.OP_READ);

        DatagramSocket socket = channel.socket();
        socket.setReuseAddress(false);
        socket.setReceiveBufferSize(RECEIVE_BUFFER_SIZE);
        socket.setSendBufferSize(SEND_BUFFER_SIZE);

        socket.bind(address);
    }
}