List of usage examples for java.net DatagramSocket setBroadcast
public synchronized void setBroadcast(boolean on) throws SocketException
From source file:Main.java
public static void main(String args[]) { try {/*from w w w .j a v a 2 s .c om*/ InetAddress ia = InetAddress.getByName("www.java2s.com"); DatagramSocket ds = new DatagramSocket(); byte buffer[] = "hello".getBytes(); DatagramPacket dp = new DatagramPacket(buffer, buffer.length, ia, 80); ds.setBroadcast(true); ds.send(dp); } catch (Exception e) { e.printStackTrace(); } }
From source file:gravity.android.discovery.DiscoveryClient.java
public static ArrayList<DiscoveryServerInfo> findServer(WifiManager mWifi, int port, String token) { ArrayList<DiscoveryServerInfo> ret = new ArrayList<DiscoveryServerInfo>(); try {//from www . j ava2 s .c om DatagramSocket clientSocket = new DatagramSocket(); clientSocket.setBroadcast(true); InetAddress IPAddress = Utils.getBroadcastAddress(mWifi); Log.v("DISCOVERY_CLIENT", "broadcast addr " + IPAddress.getHostAddress()); byte[] receiveData = new byte[2048]; byte[] sendData = new byte[128]; sendData = token.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); Log.v("DISCOVERY_CLIENT", "sent " + token); clientSocket.send(sendPacket); long t1 = System.currentTimeMillis(); while (System.currentTimeMillis() - t1 <= 4000) // 4 secondi { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); try { clientSocket.setSoTimeout(500); clientSocket.receive(receivePacket); if (receivePacket.getAddress() != null && receivePacket.getAddress().getHostAddress() != null) { String discovered_name, discovered_ip; int discovered_port; String received = new String(receivePacket.getData()); if (received != null) { received = received.trim().substring(0, receivePacket.getLength()).trim(); Log.d("Recieved Msg Packet:", received); //StringTokenizer st = new StringTokenizer(received, ","); //Gravity Code JSONObject recievedJson = new JSONObject(received); try { //discovered_name = st.nextToken(); discovered_name = recievedJson.getString("name"); //Gravity code discovered_ip = receivePacket.getAddress().getHostAddress(); //discovered_port = Integer.parseInt(st.nextToken()); discovered_port = recievedJson.getInt("port_to_share"); //Gravity code Log.v("DISCOVERY_CLIENT", "discovered " + discovered_name + ", " + discovered_ip + ":" + discovered_port); boolean add = true; if (ret.size() > 0) { for (DiscoveryServerInfo dsi : ret) { if (dsi != null && dsi.ip.equals(discovered_ip)) { add = false; break; } } } if (add) { ret.add(new DiscoveryServerInfo(discovered_name, discovered_ip, discovered_port)); } } catch (NoSuchElementException nsee) { Log.v("DISCOVERY_CLIENT", nsee.getLocalizedMessage()); } } } } catch (SocketTimeoutException tex) { /* ignored */ } } clientSocket.close(); } catch (Exception ex) { ex.printStackTrace(); Log.e("DISCOVERY_CLIENT", ex.toString()); } return ret; }
From source file:org.cc86.MMC.client.Main.java
public static String serverDiscovery() { String res = "0.0.0.0"; DatagramSocket c; // Find the server using UDP broadcast try {// w w w .j av a 2 s. c o m //Open a random port to send the package c = new DatagramSocket(); c.setBroadcast(true); byte[] sendData = "DISCOVER_MMC_REQUEST".getBytes(); //Try the 255.255.255.255 first try { DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, InetAddress.getByName("255.255.255.255"), 0xCC86); c.send(sendPacket); l.info("Request packet sent to: 255.255.255.255 (DEFAULT)"); } catch (Exception e) { } // Broadcast the message over all the network interfaces Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = (NetworkInterface) interfaces.nextElement(); if (networkInterface.isLoopback() || !networkInterface.isUp()) { continue; // Don't want to broadcast to the loopback interface } for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) { InetAddress broadcast = interfaceAddress.getBroadcast(); if (broadcast == null) { continue; } // Send the broadcast package! try { DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, broadcast, 8888); c.send(sendPacket); } catch (Exception e) { } l.info("Request packet sent to: " + broadcast.getHostAddress() + "; Interface: " + networkInterface.getDisplayName()); } } l.info("Done looping over all network interfaces. Now waiting for a reply!"); //Wait for a response byte[] recvBuf = new byte[15000]; DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length); c.receive(receivePacket); //We have a response l.info("Broadcast response from server: " + receivePacket.getAddress().getHostAddress()); //Check if the message is correct String message = new String(receivePacket.getData()).trim(); if (message.equals("DISCOVER_MMC_RESPONSE")) { //DO SOMETHING WITH THE SERVER'S IP (for example, store it in your controller) res = (receivePacket.getAddress() + "").substring(1); } //Close the port! c.close(); } catch (IOException ex) { } return res; }
From source file:com.t_oster.visicut.misc.Helper.java
public static List<String> findVisiCamInstances() { List<String> result = new LinkedList<String>(); // Find the server using UDP broadcast try {/* w w w . j ava 2 s . c o m*/ //Open a random port to send the package DatagramSocket c = new DatagramSocket(); c.setBroadcast(true); byte[] sendData = "VisiCamDiscover".getBytes(); //Try the 255.255.255.255 first try { DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, InetAddress.getByName("255.255.255.255"), 8888); c.send(sendPacket); } catch (Exception e) { } // Broadcast the message over all the network interfaces Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = interfaces.nextElement(); if (networkInterface.isLoopback() || !networkInterface.isUp()) { continue; // Don't want to broadcast to the loopback interface } for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) { InetAddress broadcast = interfaceAddress.getBroadcast(); if (broadcast == null) { continue; } // Send the broadcast package! try { DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, broadcast, 8888); c.send(sendPacket); } catch (Exception e) { } } } //Wait for a response byte[] recvBuf = new byte[15000]; c.setSoTimeout(3000); while (true) { DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length); try { c.receive(receivePacket); //Check if the message is correct String message = new String(receivePacket.getData()).trim(); //Close the port! c.close(); if (message.startsWith("http")) { result.add(message); } } catch (SocketTimeoutException e) { break; } } } catch (IOException ex) { } return result; }
From source file:poisondog.net.udp.SendMission.java
public Void execute(DatagramParameter parameter) throws IOException { DatagramSocket socket = new DatagramSocket(); socket.setReuseAddress(true);//w w w. ja v a 2 s. c om 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())); if (parameter.getPort() > 0) packet.setPort(parameter.getPort()); socket.send(packet); socket.close(); return null; }
From source file:poisondog.net.udp.DatagramMission.java
public DatagramResponse execute(DatagramParameter parameter) throws IOException { DatagramSocket socket = new DatagramSocket(null); socket.setReuseAddress(true);//from ww w .j a v a 2 s. c o m 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); 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:us.nineworlds.serenity.core.services.GDMService.java
@Override protected void onHandleIntent(Intent intent) { try {/*from ww w.ja v a2s . c o m*/ DatagramSocket socket = new DatagramSocket(32414); socket.setBroadcast(true); String data = "M-SEARCH * HTTP/1.1\r\n\r\n"; DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length(), useMultiCastAddress(), 32414); // DatagramPacket packet = new DatagramPacket(data.getBytes(), // data.length(), getBroadcastAddress(), 32414); socket.send(packet); Log.d("GDMService", "Search Packet Broadcasted"); byte[] buf = new byte[256]; packet = new DatagramPacket(buf, buf.length); socket.setSoTimeout(2000); boolean listening = true; while (listening) { try { socket.receive(packet); String packetData = new String(packet.getData()); if (packetData.contains("HTTP/1.0 200 OK")) { Log.d("GDMService", "PMS Packet Received"); // Broadcast Received Packet Intent packetBroadcast = new Intent(GDMService.MSG_RECEIVED); packetBroadcast.putExtra("data", packetData); packetBroadcast.putExtra("ipaddress", packet.getAddress().toString()); LocalBroadcastManager.getInstance(this).sendBroadcast(packetBroadcast); } } catch (SocketTimeoutException e) { Log.d("GDMService", "Socket Timeout"); socket.close(); listening = false; Intent socketBroadcast = new Intent(GDMService.SOCKET_CLOSED); LocalBroadcastManager.getInstance(this).sendBroadcast(socketBroadcast); } } } catch (IOException e) { Log.e("GDMService", e.toString()); } }
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);//w w w. jav a2s . co m socket.setBroadcast(true); return new MulticastEngine(getFdFactory(), Generators.timeBasedGenerator(), heartbeatPeriod, heartbeatUnit, socket, tuple.b, receiveBufferMultiplier, sendBufferMultiplier, getMac(), tuple.a); }
From source file:com.ionicsdk.discovery.Discovery.java
public void doIdentify(final JSONObject opts, final CallbackContext callbackContext) { new AsyncTask<Integer, Void, Void>() { @Override//ww w.j av a 2 s .c o m protected Void doInBackground(Integer... params) { try { DatagramSocket socket = new DatagramSocket(); socket.setBroadcast(true); String data = opts.toString(); DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length(), getBroadcastAddress(), opts.getInt("port")); socket.send(packet); Log.d(TAG, "Sent packet"); byte[] buf = new byte[1024]; packet = new DatagramPacket(buf, buf.length); socket.receive(packet); String result = new String(buf, 0, packet.getLength()); Log.d(TAG, "Got response packet of " + packet.getLength() + " bytes: " + result); callbackContext.success(result); } catch (Exception e) { callbackContext.error(e.getMessage()); Log.e(TAG, "Exception while listening for server broadcast"); e.printStackTrace(); } return null; } }.execute(); }
From source file:org.rifidi.emulator.reader.alien.heartbeat.HeartbeatController.java
/** * Send out a heartbeat/*from www. j av a2 s . c o m*/ */ private void broadcast() { String retString = "<Alien-RFID-Reader-Heartbeat>\n" + " <ReaderName>Alien RFID Reader</ReaderName>\n" + " <ReaderType>Alien RFID Tag Reader, Model: ALR-9800(Four Antenna / Multi-Protocol / 915 Mhz)" + "</ReaderType>\n" + " <IPAddress>" + asr.getCommandIP() + "</IPAddress>\n" + " <CommandPort>" + asr.getCommandPort() + "</CommandPort>\n" + " <HeartbeatTime>" + this.timeInMs / 1000 + "</HeartbeatTime>\n" + " <MACAddress>00:00:00:00:00:00</MACAddress>\n" + "</Alien-RFID-Reader-Heartbeat>\n"; try { logger.debug("Attempting to send heartbeat..."); DatagramSocket sock = new DatagramSocket(bindingPort); InetAddress ia = InetAddress.getByName(broadcastAddr); sock.setBroadcast(true); DatagramPacket p = new DatagramPacket(retString.getBytes(), retString.getBytes().length, ia, broadcastPort); sock.send(p); sock.disconnect(); sock.close(); } catch (SocketException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }