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

The following examples show how to use java.net.DatagramSocket#setBroadcast() . 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: 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 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: 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 4
Source File: DiscoveryThread.java    From LocalNetwork with MIT License 6 votes vote down vote up
@Override
public void run() {
    try {
        int port = NetworkUtil.BASE_PORT;
        do {
            socket = new DatagramSocket(port, InetAddress.getByName("0.0.0.0"));
            port--;
        } while (socket == null);

        socket.setBroadcast(true);

        while (true) {
            // Receive broadcast packet
            byte[] buffer = new byte[15000];
            DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
            socket.receive(receivePacket);
            Log.d("USER", "Received packet from: " + receivePacket.getAddress().getHostAddress());

            // Send reply
            byte[] replyPacket = SerializationUtil.serialize(reply);
            socket.send(new DatagramPacket(replyPacket, replyPacket.length, receivePacket.getAddress(), receivePacket.getPort()));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 5
Source File: DhcpProtocolParserServer.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    while (_running) {
        try {
            DatagramSocket dhcpSocket = new DatagramSocket(dhcpServerPort, InetAddress.getByAddress(new byte[] {0, 0, 0, 0}));
            dhcpSocket.setBroadcast(true);

            while (true) {
                byte[] buf = new byte[bufferSize];
                DatagramPacket dgp = new DatagramPacket(buf, buf.length);
                dhcpSocket.receive(dgp);
                // _executor.execute(new DhcpPacketParser(buf));
            }
        } catch (IOException e) {
            s_logger.debug(e.getMessage());
        }
    }
}
 
Example 6
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 7
Source File: UdpSend.java    From AndroidDemo with MIT License 5 votes vote down vote up
@Override
public void run() {
    do {
        try {
            DatagramSocket sendSocket = new DatagramSocket();
            String msg = "Message from udp:" + String.valueOf((char) ('A' + count));
            byte[] buf = msg.getBytes();
            DatagramPacket packet = new DatagramPacket(buf, 0, buf.length, InetAddress.getByName("192.168.0.255"), 2000);
            sendSocket.setBroadcast(true);
            sendSocket.send(packet);
            sendSocket.close();
            System.out.println(msg);
            count++;
            if (count > 30) {
                count = -1;
            }
            Thread.sleep(2000);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            System.out.println("Error exit");
            break;
        }
    } while (true);

    System.exit(0);

}
 
Example 8
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 9
Source File: UdpSocket.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
 * ブロードキャストするかどうかをセット
 * @param broadcast
 * @throws SocketException
 */
public void setBroadcast(final boolean broadcast) throws SocketException {
	final DatagramSocket socket = channel != null ? channel.socket() : null;
	if (socket != null) {
		socket.setBroadcast(broadcast);
	}
}
 
Example 10
Source File: DiscoverySocketThread.java    From LocalNetwork with MIT License 5 votes vote down vote up
@Override
public void run() {
    try {
        int port = NetworkUtil.BASE_PORT;
        boolean portAvailable = false;
        do {
            if (NetworkUtil.available(port))
                portAvailable = true;
            else
                port--;
        } while (!portAvailable);

        socket = new DatagramSocket(port, InetAddress.getByName("0.0.0.0"));
        socket.setBroadcast(true);

        while (true) {
            // Receive broadcast packet
            Log.d("USER", "Waiting for packet...");
            byte[] buffer = new byte[15000];
            DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
            socket.receive(receivePacket);
            Log.d("USER", "Received packet from: " + receivePacket.getAddress().getHostAddress());

            // Send reply
            byte[] replyPacket = SerializationUtil.serialize(reply);
            socket.send(new DatagramPacket(replyPacket, replyPacket.length, receivePacket.getAddress(), receivePacket.getPort()));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 11
Source File: BroadcastDiscovery.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 *  Starts a new thread to reply to broadcast discovery requests from nodes.
 *
 * @throws SocketException if cannot bind UDP socket
 * @throws UnknownHostException if cannot bind to 0.0.0.0
 */
public void start() throws SocketException, UnknownHostException {
    broadcastSocket = new DatagramSocket(port, InetAddress.getByName("0.0.0.0"));
    broadcastSocket.setBroadcast(true);

    discoveryThread = new Thread(new Runnable() {
        @Override
        public void run() {
            for (;;) {
                try {
                    DatagramPacket nodePacket = new DatagramPacket(new byte[0], 0);
                    broadcastSocket.receive(nodePacket);

                    byte[] urlAsBytes = url.getBytes(BroadcastDiscoveryClient.BROADCAST_ENCODING);
                    DatagramPacket replyPacket = new DatagramPacket(urlAsBytes,
                                                                    urlAsBytes.length,
                                                                    nodePacket.getAddress(),
                                                                    nodePacket.getPort());
                    broadcastSocket.send(replyPacket);
                } catch (SocketException e) {
                    if (needsToStop) {
                        return;
                    } else {
                        logger.warn("Could not broadcast URL to node", e);
                    }
                } catch (Exception e) {
                    logger.warn("Could not broadcast URL to node", e);
                }
            }
        }
    }, "BroadcastDiscovery");
    discoveryThread.start();
}
 
Example 12
Source File: Broadcaster.java    From Android with Apache License 2.0 5 votes vote down vote up
public boolean open(int localport,int destport) {
    mDestPort = destport;        
    try {
        mSocket = new DatagramSocket(localport);
        mSocket.setBroadcast(true);
        mSocket.setReuseAddress(true);
        return true;
    } 
    catch (SocketException e) {         
        e.printStackTrace();
    }        
    return false;
}
 
Example 13
Source File: NameServerProxy.java    From big-c with Apache License 2.0 4 votes vote down vote up
public static NameServerProxy locateNS(String host, int port, byte[] hmacKey) throws IOException {
	if(host!=null) {
		if(port==0)
			port=Config.NS_PORT;
		NameServerProxy proxy=new NameServerProxy(host, port);
		proxy.pyroHmacKey = hmacKey;
		proxy.ping();
		return proxy;
	}
	if(port==0)
		port=Config.NS_BCPORT;
	DatagramSocket udpsock=new DatagramSocket();
	udpsock.setSoTimeout(3000);
	udpsock.setBroadcast(true);
	byte[] buf="GET_NSURI".getBytes();
	if(host==null)
		host="255.255.255.255";
	InetAddress address=InetAddress.getByName(host);
	DatagramPacket packet=new DatagramPacket(buf, buf.length, address, port);
	udpsock.send(packet);
	
	DatagramPacket response=new DatagramPacket(new byte[100], 100);
	try
	{
		udpsock.receive(response);
	}
	catch(SocketTimeoutException x)
	{
		// try localhost explicitly (if host wasn't localhost already)
		if(!host.startsWith("127.0") && !host.equals("localhost"))
			return locateNS("localhost", Config.NS_PORT, hmacKey);
		else
			throw x;
	}
	finally {
		udpsock.close();
	}
	String location=new String(response.getData(), 0, response.getLength());
	NameServerProxy nsp = new NameServerProxy(new PyroURI(location));
	nsp.pyroHmacKey = hmacKey;
	return nsp;
}
 
Example 14
Source File: BroadcastingClient.java    From tutorials with MIT License 4 votes vote down vote up
private void initializeSocketForBroadcasting() throws SocketException {
    socket = new DatagramSocket();
    socket.setBroadcast(true);
}
 
Example 15
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;
}