Java Code Examples for java.net.DatagramSocket#setReuseAddress()

The following examples show how to use java.net.DatagramSocket#setReuseAddress() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Ssdp.java    From physical-web with Apache License 2.0 7 votes vote down vote up
public synchronized boolean start(Integer timeout) throws IOException {
  if (mThread == null) {
    // create a DatagramSocket without binding to any address
    mDatagramSocket = new DatagramSocket(null);
    mDatagramSocket.setReuseAddress(true);
    // bind to any free port
    mDatagramSocket.bind(null);
    if (timeout != null && timeout > 0) {
      mDatagramSocket.setSoTimeout(timeout);
    }
    mThread = new Thread(this);
    mThread.start();
    return true;
  }
  return false;
}
 
Example 2
Source File: NetworkSync.java    From ssj with GNU General Public License v3.0 6 votes vote down vote up
static void sendStartSignal(int port)
{
    try
    {
        DatagramSocket syncSocket = new DatagramSocket(null);
        syncSocket.setReuseAddress(true);
        syncSocket.setBroadcast(true);

        String msg = "SSI:STRT:RUN1"; //send in SSI format for compatibility
        byte[] data = msg.getBytes("ASCII");
        DatagramPacket packet = new DatagramPacket(data, data.length, Util.getBroadcastAddress(), port);
        syncSocket.send(packet);

        Log.i("start signal sent on port " + port);
    }
    catch(IOException e)
    {
        Log.e("network sync failed", e);
    }
}
 
Example 3
Source File: Network.java    From OberonEmulator with ISC License 6 votes vote down vote up
public Network(InetSocketAddress addr) throws IOException {
	this.addr = addr;
	ds = new DatagramSocket(null);
	ds.setReuseAddress(true);
	ds.bind(new InetSocketAddress((InetAddress) null, addr.getPort()));
	Thread t = new Thread(new Runnable() {
		@Override
		public void run() {
			try {
				while (true) {
					byte[] buf = new byte[576];
					DatagramPacket dp = new DatagramPacket(buf, buf.length);
					ds.receive(dp);
					if (dp.getLength() % 32 == 0)
						netQueue.put(dp);
				}
			} catch (Exception ex) {
				throw new RuntimeException(ex);
			}
		}
	});
	t.setDaemon(true);
	t.start();
}
 
Example 4
Source File: AvailablePortFinder.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Checks to see if a specific port is available.
 *
 * @param port the port to check for availability
 * @return <tt>true</tt> if the port is available, <tt>false</tt> otherwise
 */
private boolean available(int port) {
    try {
        ServerSocket ss = new ServerSocket(port);
        try {
            ss.setReuseAddress(true);
        } finally {
            ss.close();
        }
        DatagramSocket ds = new DatagramSocket(port);
        try {
            ds.setReuseAddress(true);
        } finally {
            ds.close();
        }
        return true;
    } catch (IOException e) {
        return false;
    }
}
 
Example 5
Source File: AvailablePortFinder.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Checks to see if a specific port is available.
 *
 * @param port the port to check for availability
 * @return <tt>true</tt> if the port is available, <tt>false</tt> otherwise
 */
private boolean available(int port) {
    try {
        ServerSocket ss = new ServerSocket(port);
        try {
            ss.setReuseAddress(true);
        } finally {
            ss.close();
        }
        DatagramSocket ds = new DatagramSocket(port);
        try {
            ds.setReuseAddress(true);
        } finally {
            ds.close();
        }
        return true;
    } catch (IOException e) {
        return false;
    }
}
 
Example 6
Source File: PrivilegedNfsGatewayStarter.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Override
public void init(DaemonContext context) throws Exception {
  System.err.println("Initializing privileged NFS client socket...");
  NfsConfiguration conf = new NfsConfiguration();
  int clientPort = conf.getInt(NfsConfigKeys.DFS_NFS_REGISTRATION_PORT_KEY,
      NfsConfigKeys.DFS_NFS_REGISTRATION_PORT_DEFAULT);
  if (clientPort < 1 || clientPort > 1023) {
    throw new RuntimeException("Must start privileged NFS server with '" +
        NfsConfigKeys.DFS_NFS_REGISTRATION_PORT_KEY + "' configured to a " +
        "privileged port.");
  }
  registrationSocket = new DatagramSocket(
      new InetSocketAddress("localhost", clientPort));
  registrationSocket.setReuseAddress(true);
  args = context.getArguments();
}
 
Example 7
Source File: NetworkSync.java    From ssj with GNU General Public License v3.0 6 votes vote down vote up
static void sendStopSignal(int port)
{
    try
    {
        DatagramSocket syncSocket = new DatagramSocket(null);
        syncSocket.setReuseAddress(true);
        syncSocket.setBroadcast(true);

        String msg = "SSI:STOP:QUIT"; //send in SSI format for compatibility
        byte[] data = msg.getBytes("ASCII");
        DatagramPacket packet = new DatagramPacket(data, data.length, Util.getBroadcastAddress(), port);
        syncSocket.send(packet);

        Log.i("stop signal sent on port " + port);
    }
    catch(IOException e)
    {
        Log.e("network sync failed", e);
    }
}
 
Example 8
Source File: AvailablePortFinder.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Checks to see if a specific port is available.
 *
 * @param port the port to check for availability
 * @return <tt>true</tt> if the port is available, <tt>false</tt> otherwise
 */
private boolean available(int port) {
    try {
        ServerSocket ss = new ServerSocket(port);
        try {
            ss.setReuseAddress(true);
        } finally {
            ss.close();
        }
        DatagramSocket ds = new DatagramSocket(port);
        try {
            ds.setReuseAddress(true);
        } finally {
            ds.close();
        }
        return true;
    } catch (IOException e) {
        return false;
    }
}
 
Example 9
Source File: PrivilegedNfsGatewayStarter.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Override
public void init(DaemonContext context) throws Exception {
  System.err.println("Initializing privileged NFS client socket...");
  NfsConfiguration conf = new NfsConfiguration();
  int clientPort = conf.getInt(NfsConfigKeys.DFS_NFS_REGISTRATION_PORT_KEY,
      NfsConfigKeys.DFS_NFS_REGISTRATION_PORT_DEFAULT);
  if (clientPort < 1 || clientPort > 1023) {
    throw new RuntimeException("Must start privileged NFS server with '" +
        NfsConfigKeys.DFS_NFS_REGISTRATION_PORT_KEY + "' configured to a " +
        "privileged port.");
  }
  registrationSocket = new DatagramSocket(
      new InetSocketAddress("localhost", clientPort));
  registrationSocket.setReuseAddress(true);
  args = context.getArguments();
}
 
Example 10
Source File: BLDevice.java    From broadlink-java-api with MIT License 6 votes vote down vote up
/**
 * Constructs a <code>BLDevice</code>, with a device type (constants),
 * hostname and MAC address
 * 
 * @param deviceType
 *            Device type constants (<code>BLDevice.DEV_*</code>)
 * @param deviceDesc
 *            Friendly device description
 * @param host
 *            Hostname of target Broadlink device
 * @param mac
 *            MAC address of target Broadlink device
 * @throws IOException
 *             Problems on constructing a datagram socket
 */
protected BLDevice(short deviceType, String deviceDesc, String host, Mac mac) throws IOException {
    key = INITIAL_KEY;
    iv = INITIAL_IV;
    id = new byte[] { 0, 0, 0, 0 };

    pktCount = new Random().nextInt(0xffff);

    this.deviceType = deviceType;
    this.deviceDesc = deviceDesc;
    
    this.host = host;
    this.mac = mac;

    sock = new DatagramSocket();
    sock.setReuseAddress(true);
    sock.setBroadcast(true);
    aes = new AES(iv, key);
    alreadyAuthorized = false;
}
 
Example 11
Source File: AvailablePortFinder.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Checks to see if a specific port is available.
 *
 * @param port the port to check for availability
 * @return <tt>true</tt> if the port is available, <tt>false</tt> otherwise
 */
private boolean available(int port) {
    try {
        ServerSocket ss = new ServerSocket(port);
        try {
            ss.setReuseAddress(true);
        } finally {
            ss.close();
        }
        DatagramSocket ds = new DatagramSocket(port);
        try {
            ds.setReuseAddress(true);
        } finally {
            ds.close();
        }
        return true;
    } catch (IOException e) {
        return false;
    }
}
 
Example 12
Source File: UDPBroadcastReceiver.java    From moleculer-java with MIT License 5 votes vote down vote up
@Override
protected void connect() throws Exception {

	// Start broadcast receiver
	broadcastReceiver = new DatagramSocket();
	broadcastReceiver.setReuseAddress(udpReuseAddr);
	broadcastReceiver.setBroadcast(true);
	broadcastReceiver.connect(InetAddress.getByName(udpAddress), udpPort);

	// Start thread
	super.connect();

	logger.info("Broadcast discovery service started on udp://" + udpAddress + ':' + udpPort + '.');
}
 
Example 13
Source File: NetworkSync.java    From ssj with GNU General Public License v3.0 5 votes vote down vote up
public NetworkSync(Pipeline.SyncType type, boolean isMaster, InetAddress masterAddr, int port, int interval)
{
    frame = Pipeline.getInstance();

    this.isMaster = isMaster;
    this.hostAddr = masterAddr;
    this.port = port;
    this.type = type;

    try {
        sendSocket = new DatagramSocket();
        recvSocket = new DatagramSocket(port);
        sendSocket.setReuseAddress(true);
        recvSocket.setReuseAddress(true);
    } catch (SocketException e) {
        Log.e("error setting up network sync", e);
    }

    listener = new SyncListener(port);
    new Thread(listener).start();

    if(type == Pipeline.SyncType.CONTINUOUS && interval > 0 && !isMaster)
    {
        sender = new SyncSender(interval);
        new Thread(sender).start();
    }
}
 
Example 14
Source File: UdpSocket.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
 * 同じアドレスを他のソケットでも使用可能にするかどうか
 * @param reuse
 * @throws SocketException
 */
public void setReuseAddress(final boolean reuse) throws SocketException {
	final DatagramSocket socket = channel != null ? channel.socket() : null;
	if (socket != null) {
		socket.setReuseAddress(reuse);
	}
}
 
Example 15
Source File: NetworkPackageQueueHandler.java    From PowerSwitch_Android with GNU General Public License v3.0 5 votes vote down vote up
private void send(NetworkPackage networkPackage) throws Exception {
    switch (networkPackage.getCommunicationType()) {
        case UDP:
            InetAddress host = InetAddress.getByName(networkPackage.getHost());
            int port = networkPackage.getPort();

            socket = new DatagramSocket(null);
            socket.setReuseAddress(true);
            socket.connect(host, port);

            byte[] messageBuffer = networkPackage.getMessage().getBytes();
            DatagramPacket messagePacket = new DatagramPacket(messageBuffer, messageBuffer.length, host, port);
            socket.send(messagePacket);

            Log.d("UDP Sender", "Host: " + host.getHostAddress() + ":" + port
                    + " Message: \"" + new String(messageBuffer) + "\" sent.");

            socket.disconnect();
            socket.close();
            break;
        case HTTP:
            URL url = new URL("http://" + networkPackage.getHost() + ":" + networkPackage.getPort() + "/" +
                    networkPackage.getMessage());
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            try {
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                readStream(in);
            } finally {
                urlConnection.disconnect();
            }
            break;
    }
}
 
Example 16
Source File: BroadcastSearch.java    From onpc with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected Void doInBackground(Void... params)
{
    Logging.info(this, "started, network=" + connectionState.isNetwork()
            + ", wifi=" + connectionState.isWifi());

    final Character[] models = new Character[]{ 'x', 'p' };
    int modelId = 0;

    try
    {
        final InetAddress target = InetAddress.getByName("255.255.255.255");

        final DatagramSocket socket = new DatagramSocket(null);
        socket.setReuseAddress(true);
        socket.setBroadcast(true);
        socket.setSoTimeout(500);
        socket.bind(new InetSocketAddress(ISCP_PORT));

        while (!isStopped())
        {
            request(socket, target, models[modelId]);
            modelId++;
            if (modelId > 1)
            {
                modelId = 0;
            }
        }
        socket.close();
    }
    catch (Exception e)
    {
        Logging.info(this, "Can not open socket: " + e.toString());
    }

    Logging.info(this, "stopped");
    return null;
}
 
Example 17
Source File: DiscoveryTest.java    From freeacs with MIT License 4 votes vote down vote up
private boolean test1()
    throws UtilityException, SocketException, UnknownHostException, IOException,
        MessageAttributeParsingException, MessageHeaderParsingException {
  int timeSinceFirstTransmission = 0;
  int timeout = timeoutInitValue;
  do {
    try {
      // Test 1 including response
      socketTest1 = new DatagramSocket(new InetSocketAddress(iaddress, 0));
      socketTest1.setReuseAddress(true);
      socketTest1.connect(InetAddress.getByName(stunServer), port);
      socketTest1.setSoTimeout(timeout);

      MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest);
      sendMH.generateTransactionID();

      ChangeRequest changeRequest = new ChangeRequest();
      sendMH.addMessageAttribute(changeRequest);

      byte[] data = sendMH.getBytes();
      DatagramPacket send = new DatagramPacket(data, data.length);
      socketTest1.send(send);
      LOGGER.debug("Test 1: Binding Request sent.");

      MessageHeader receiveMH = new MessageHeader();
      while (!receiveMH.equalTransactionID(sendMH)) {
        DatagramPacket receive = new DatagramPacket(new byte[200], 200);
        socketTest1.receive(receive);
        receiveMH = MessageHeader.parseHeader(receive.getData());
        receiveMH.parseAttributes(receive.getData());
      }

      ma =
          (MappedAddress)
              receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.MappedAddress);
      ca =
          (ChangedAddress)
              receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ChangedAddress);
      ErrorCode ec =
          (ErrorCode)
              receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode);
      if (ec != null) {
        di.setError(ec.getResponseCode(), ec.getReason());
        LOGGER.debug("Message header contains an Errorcode message attribute.");
        return false;
      }
      if (ma == null || ca == null) {
        di.setError(
            700,
            "The server is sending an incomplete response (Mapped Address and Changed Address message attributes are missing). The client should not retry.");
        LOGGER.debug(
            "Response does not contain a Mapped Address or Changed Address message attribute.");
        return false;
      } else {
        di.setPublicIP(ma.getAddress().getInetAddress());
        if (ma.getPort() == socketTest1.getLocalPort()
            && ma.getAddress().getInetAddress().equals(socketTest1.getLocalAddress())) {
          LOGGER.debug("Node is not natted.");
          nodeNatted = false;
        } else {
          LOGGER.debug("Node is natted.");
        }
        return true;
      }
    } catch (SocketTimeoutException ste) {
      if (timeSinceFirstTransmission < 7900) {
        LOGGER.debug("Test 1: Socket timeout while receiving the response.");
        timeSinceFirstTransmission += timeout;
        int timeoutAddValue = timeSinceFirstTransmission * 2;
        if (timeoutAddValue > 1600) {
          timeoutAddValue = 1600;
        }
        timeout = timeoutAddValue;
      } else {
        // node is not capable of udp communication
        LOGGER.debug(
            "Test 1: Socket timeout while receiving the response. Maximum retry limit exceed. Give up.");
        di.setBlockedUDP();
        LOGGER.debug("Node is not capable of UDP communication.");
        return false;
      }
    }
  } while (true);
}
 
Example 18
Source File: BasicNetworkInterface.java    From mochadoom with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void InitNetwork() {
    //struct hostent* hostentry;  // host information entry

    doomcom = new doomcom_t();
    //netbuffer = new doomdata_t();
    DOOM.setDoomCom(doomcom);
    //DM.netbuffer = netbuffer;

    // set up for network
    if (!DOOM.cVarManager.with(CommandVariable.DUP, 0, (Character c) -> {
        doomcom.ticdup = (short) (c - '0');
        if (doomcom.ticdup < 1) {
            doomcom.ticdup = 1;
        }
        if (doomcom.ticdup > 9) {
            doomcom.ticdup = 9;
        }
    })) {
        doomcom.ticdup = 1;
    }

    if (DOOM.cVarManager.bool(CommandVariable.EXTRATIC)) {
        doomcom.extratics = 1;
    } else {
        doomcom.extratics = 0;
    }

    DOOM.cVarManager.with(CommandVariable.PORT, 0, (Integer port) -> {
        DOOMPORT = port;
        System.out.println("using alternate port " + DOOMPORT);
    });

    // parse network game options,
    //  -net <consoleplayer> <host> <host> ...
    if (!DOOM.cVarManager.present(CommandVariable.NET)) {
        // single player game
        DOOM.netgame = false;
        doomcom.id = DOOMCOM_ID;
        doomcom.numplayers = doomcom.numnodes = 1;
        doomcom.deathmatch = 0; // false
        doomcom.consoleplayer = 0;
        return;
    }

    DOOM.netgame = true;

    // parse player number and host list
    doomcom.consoleplayer = (short) (DOOM.cVarManager.get(CommandVariable.NET, Character.class, 0).get() - '1');

    RECVPORT = SENDPORT = DOOMPORT;
    if (doomcom.consoleplayer == 0) {
        SENDPORT++;
    } else {
        RECVPORT++;
    }

    doomcom.numnodes = 1;  // this node for sure

    String[] hosts = DOOM.cVarManager.get(CommandVariable.NET, String[].class, 1).get();
    for (String host: hosts) {
        try {
            InetAddress addr = InetAddress.getByName(host);
            DatagramSocket ds = new DatagramSocket(null);
            ds.setReuseAddress(true);
            ds.connect(addr, SENDPORT);

            sendaddress[doomcom.numnodes] = ds;
        } catch (SocketException | UnknownHostException e) {
            e.printStackTrace();
        }

        doomcom.numnodes++;
    }

    doomcom.id = DOOMCOM_ID;
    doomcom.numplayers = doomcom.numnodes;

    // build message to receive
    try {
        insocket = new DatagramSocket(null);
        insocket.setReuseAddress(true);
        insocket.setSoTimeout(1);
        insocket.bind(new InetSocketAddress(RECVPORT));
    } catch (SocketException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}
 
Example 19
Source File: BroadcastingEchoServer.java    From tutorials with MIT License 4 votes vote down vote up
public BroadcastingEchoServer() throws IOException {
    socket = new DatagramSocket(null);
    socket.setReuseAddress(true);
    socket.bind(new InetSocketAddress(4445));
}
 
Example 20
Source File: BLDevice.java    From broadlink-java-api with MIT License 3 votes vote down vote up
/**
 * Sends a compiled packet to a destination host and port, and receives a
 * datagram from the source port specified.
 * 
 * @param pkt
 *            The compiled packet to be sent
 * @param sourceIpAddr
 *            Source IP address to be binded for receiving datagrams
 * @param sourcePort
 *            Source Port to be bineded for receiving datagrams
 * @param destIpAddr
 *            Destination IP address
 * @param destPort
 *            Destination Port
 * @param timeout
 *            Socket timeout. 0 will disable the timeout
 * @param bufSize
 *            Receiving datagram's buffer size
 * @return The received datagram
 * @throws IOException
 *             Thrown if socket timed out, cannot bind source IP and source
 *             port, no permission, etc.
 */
public static DatagramPacket sendPkt(Packet pkt, InetAddress sourceIpAddr, int sourcePort, InetAddress destIpAddr,
        int destPort, int timeout, int bufSize) throws IOException {
	log.debug("sendPkt - call with create socket for: " + sourceIpAddr.getHostAddress() + " and port " + sourcePort);
    DatagramSocket sock = new DatagramSocket(sourcePort, sourceIpAddr);

    sock.setBroadcast(true);
    sock.setReuseAddress(true);

    DatagramPacket recePkt = sendPkt(sock, pkt, destIpAddr, destPort, timeout, bufSize);
    sock.close();

    return recePkt;
}