List of usage examples for java.net DatagramPacket DatagramPacket
public DatagramPacket(byte buf[], int length, InetAddress address, int port)
From source file:ca.viaware.dlna.ssdp.SSDPService.java
public void reply(String st, String usn, String uid, SocketAddress source) { String http = "HTTP/1.1 200 OK\r\n"; http += "CACHE-CONTROL: max-age=1800\r\n"; http += "EXT: \r\n"; http += "ST: " + st + "\r\n"; http += "USN: " + usn + "\r\n"; http += "SERVER: " + Globals.SERVER + "\r\n"; http += "LOCATION: http://" + httpConfig.getString("host") + ":" + httpConfig.getInt("port") + "/" + uid + "/\r\n"; http += "DATE: " + DateUtils.getDate() + "\r\n"; http += "\r\n"; try {//from w ww .j a v a2s. c om byte[] bytes = http.getBytes("UTF-8"); DatagramPacket p = new DatagramPacket(bytes, 0, bytes.length, source); outSock.send(p); Log.info("SSDP: M-SEARCH Reply sent to '" + source + "' successfully : ST: " + st + " : USN: " + usn); } catch (SocketException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.eredlab.g4.ccl.net.tftp.TFTPDataPacket.java
/*** * Creates a UDP datagram containing all the TFTP * data packet data in the proper format. * This is a method exposed to the programmer in case he * wants to implement his own TFTP client instead of using * the {@link org.apache.commons.net.tftp.TFTPClient} * class./*from www.j a v a 2s. c o m*/ * Under normal circumstances, you should not have a need to call this * method. * <p> * @return A UDP datagram containing the TFTP data packet. ***/ public DatagramPacket newDatagram() { byte[] data; data = new byte[_length + 4]; data[0] = 0; data[1] = (byte) _type; data[2] = (byte) ((_blockNumber & 0xffff) >> 8); data[3] = (byte) (_blockNumber & 0xff); System.arraycopy(_data, _offset, data, 4, _length); return new DatagramPacket(data, _length + 4, _address, _port); }
From source file:vitro.vgw.wsiadapter.WSIAdapterCoap.java
/** * WSIAdapter interface//from w ww. j a v a2s.com */ public List<Node> getAvailableNodeList() throws WSIAdapterException { logger.info("Getting available nodes..."); nodesList = new ArrayList<Node>(); List<String> wsnProxyList = new LinkedList<String>(); wsnProxyList.add(Network.WLAB_OFFICE_PROXY_ADDRESS); wsnProxyList.add(Network.WLAB_LAB_PROXY_ADDRESS); DatagramSocket serverSocket = null; DatagramSocket clientSocket = null; String cmdString = "route"; for (int i = 0; i < wsnProxyList.size(); i++) { try { serverSocket = new DatagramSocket(Constants.UDPSHELL_VGW_PORT); String hostProxyString = wsnProxyList.get(i); InetAddress hostProxy = InetAddress.getByName(hostProxyString); clientSocket = new DatagramSocket(); byte[] bufCmd = new byte[10]; bufCmd = cmdString.getBytes(); DatagramPacket outcomingPacket = new DatagramPacket(bufCmd, bufCmd.length, hostProxy, Constants.PROXY_UDPFORWARDER_PORT); clientSocket.send(outcomingPacket); boolean otherPackets = false; serverSocket.setSoTimeout(Constants.PROXY_RESPONSE_TIMEOUT); logger.info("Quering " + hostProxyString); try { byte[] bufAck = new byte[10]; DatagramPacket ackPacket = new DatagramPacket(bufAck, bufAck.length); serverSocket.receive(ackPacket); String ackString = new String(ackPacket.getData()).trim(); if (ackString.equals("ack")) { otherPackets = true; } } catch (SocketTimeoutException e) { logger.warn(e.getMessage()); } serverSocket.setSoTimeout(0); while (otherPackets) { try { byte[] bufIncoming = new byte[1000]; DatagramPacket incomingPacket = new DatagramPacket(bufIncoming, bufIncoming.length); serverSocket.receive(incomingPacket); String currentNodeIP = new String(incomingPacket.getData()).trim(); if (!currentNodeIP.equals("end")) { logger.info("Node: " + currentNodeIP); nodesList.add(new Node(currentNodeIP)); } else { otherPackets = false; logger.info("No other nodes from " + hostProxyString); } } catch (IOException e) { logger.error(e.getMessage()); } } } catch (UnknownHostException e) { logger.warn(e.getMessage() + " is not reachable."); } catch (SocketException e) { logger.error(e.getMessage()); } catch (IOException e) { logger.error(e.getMessage()); } finally { if (serverSocket != null) { serverSocket.close(); } if (clientSocket != null) { clientSocket.close(); } } } return nodesList; }
From source file:Network.Network.java
private String discoverUDPServer() { DatagramSocket c;//from w w w .j av a 2 s .com String foundIP = null; // Find the server using UDP broadcast try { //Open a random port to send the package c = new DatagramSocket(); c.setBroadcast(true); byte[] sendData = "DISCOVER_BATTLESHIPSERVER_REQUEST".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); System.out.println(getClass().getName() + ">>> 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 = 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) { } System.out.println(getClass().getName() + ">>> Request packet sent to: " + broadcast.getHostAddress() + "; Interface: " + networkInterface.getDisplayName()); } }*/ System.out.println(getClass().getName() + ">>> 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 System.out.println(getClass().getName() + ">>> Broadcast response from server: " + receivePacket.getAddress().getHostAddress()); //Check if the message is correct String message = new String(receivePacket.getData()).trim(); if (message.equals("DISCOVER_BATTLESHIPSERVER_RESPONSE")) { //DO SOMETHING WITH THE SERVER'S IP (for example, store it in your controller) foundIP = receivePacket.getAddress().getHostAddress(); } //Close the port! c.close(); } catch (IOException ex) { Logger.getLogger(Network.class.getName()).log(Level.SEVERE, null, ex); } return foundIP; }
From source file:com.streamsets.pipeline.stage.origin.udp.BaseUDPSourceTest.java
private void doBasicTest(DatagramMode dataFormat, boolean enableEpoll, int numThreads) throws Exception { List<String> ports = NetworkUtils.getRandomPorts(2); final UDPSourceConfigBean conf = new UDPSourceConfigBean(); conf.ports = ports;// w ww. jav a2s .co m conf.enableEpoll = enableEpoll; conf.numThreads = 1; conf.dataFormat = dataFormat; conf.maxWaitTime = 1000; conf.batchSize = 1000; conf.collectdCharset = UTF8; conf.syslogCharset = UTF8; conf.rawDataCharset = UTF8; try { byte[] bytes = null; switch (dataFormat) { case NETFLOW: InputStream is = Thread.currentThread().getContextClassLoader() .getResourceAsStream(TEN_PACKETS_RESOURCE); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(is, baos); is.close(); baos.close(); bytes = baos.toByteArray(); break; case SYSLOG: bytes = RAW_SYSLOG_STR.getBytes(UTF8); conf.syslogCharset = UTF8; break; case RAW_DATA: bytes = StringUtils.join(RAW_DATA_VALUES, RAW_DATA_SEPARATOR).getBytes(UTF8); conf.rawDataSeparatorBytes = RAW_DATA_SEPARATOR; conf.rawDataOutputField = RAW_DATA_OUTPUT_FIELD; conf.rawDataCharset = UTF8; conf.rawDataMode = RawDataMode.CHARACTER; break; default: Assert.fail("Unknown data format: " + dataFormat); } initializeRunner(conf, numThreads); for (String port : ports) { DatagramSocket clientSocket = new DatagramSocket(); InetAddress address = InetAddress.getLoopbackAddress(); DatagramPacket sendPacket = new DatagramPacket(bytes, bytes.length, address, Integer.parseInt(port)); clientSocket.send(sendPacket); clientSocket.close(); } runProduce(dataFormat, ports); } finally { destroyRunner(); } }
From source file:org.eredlab.g4.ccl.net.tftp.TFTPErrorPacket.java
/*** * Creates a UDP datagram containing all the TFTP * error packet data in the proper format. * This is a method exposed to the programmer in case he * wants to implement his own TFTP client instead of using * the {@link org.apache.commons.net.tftp.TFTPClient} * class.//from ww w . j av a 2 s. com * Under normal circumstances, you should not have a need to call this * method. * <p> * @return A UDP datagram containing the TFTP error packet. ***/ public DatagramPacket newDatagram() { byte[] data; int length; length = _message.length(); data = new byte[length + 5]; data[0] = 0; data[1] = (byte) _type; data[2] = (byte) ((_error & 0xffff) >> 8); data[3] = (byte) (_error & 0xff); System.arraycopy(_message.getBytes(), 0, data, 4, length); data[length + 4] = 0; return new DatagramPacket(data, data.length, _address, _port); }
From source file:org.openhab.binding.harmonyhub.discovery.HarmonyHubDiscovery.java
/** * Send broadcast message over all active interfaces * * @param discoverString// w w w.j a va 2 s .co m * String to be used for the discovery */ private void sendDiscoveryMessage(String discoverString) { DatagramSocket bcSend = null; try { bcSend = new DatagramSocket(); bcSend.setBroadcast(true); byte[] sendData = discoverString.getBytes(); // 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; } for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) { InetAddress[] broadcast = null; if (StringUtils.isNotBlank(optionalHost)) { try { broadcast = new InetAddress[] { InetAddress.getByName(optionalHost) }; } catch (Exception e) { logger.error("Could not use host for hub discovery", e); return; } } else { broadcast = new InetAddress[] { InetAddress.getByName("224.0.0.1"), InetAddress.getByName("255.255.255.255"), interfaceAddress.getBroadcast() }; } for (InetAddress bc : broadcast) { // Send the broadcast package! if (bc != null) { try { DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, bc, DISCO_PORT); bcSend.send(sendPacket); } catch (IOException e) { logger.debug("IO error during HarmonyHub discovery: {}", e.getMessage()); } catch (Exception e) { logger.debug(e.getMessage(), e); } logger.trace("Request packet sent to: {} Interface: {}", bc.getHostAddress(), networkInterface.getDisplayName()); } } } } } catch (IOException e) { logger.debug("IO error during HarmonyHub discovery: {}", e.getMessage()); } finally { try { if (bcSend != null) { bcSend.close(); } } catch (Exception e) { // Ignore } } }
From source file:org.lwes.emitter.UnicastEventEmitter.java
/** * @param bytes the byte array to emit/*from w w w . jav a 2 s . c om*/ * @param address the address to use * @param port the port to use * @throws IOException throws an IOException if there is a network error */ protected void emit(byte[] bytes, InetAddress address, int port) throws IOException { /* don't send null bytes */ if (bytes == null) return; DatagramPacket dp = new DatagramPacket(bytes, bytes.length, address, port); socket.send(dp); if (log.isTraceEnabled()) { log.trace("Sent to network '" + NumberCodec.byteArrayToHexString(dp.getData(), 0, dp.getLength())); } }
From source file:it.anyplace.sync.discovery.protocol.ld.LocalDiscorveryHandler.java
public Future sendAnnounceMessage() { return processingExecutorService.submit(new Callable() { @Override// w w w . j ava 2s .com public Object call() throws Exception { for (int i = 0; i < 10 && !isListening; i++) { //wait for listening Thread.sleep(100); } if (!isListening) { logger.warn("skipping announce message, udp listening is not active"); return null; } ByteArrayOutputStream out = new ByteArrayOutputStream(); new DataOutputStream(out).writeInt(MAGIC); Announce.newBuilder() .setId(ByteString.copyFrom(deviceIdStringToHashData(configuration.getDeviceId()))) .setInstanceId(configuration.getInstanceId()).build().writeTo(out); byte[] data = out.toByteArray(); Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { NetworkInterface networkInterface = networkInterfaces.nextElement(); for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) { InetAddress broadcastAddress = interfaceAddress.getBroadcast(); logger.trace("interface = {} address = {} broadcast = {}", networkInterface, interfaceAddress, broadcastAddress); if (broadcastAddress != null) { logger.debug("sending broadcast announce on {}", broadcastAddress); try (DatagramSocket broadcastSocket = new DatagramSocket()) { broadcastSocket.setBroadcast(true); DatagramPacket datagramPacket = new DatagramPacket(data, data.length, broadcastAddress, UDP_PORT); broadcastSocket.send(datagramPacket); } catch (Exception ex) { logger.warn("error sending datagram", ex); } } } } return null; } }); }
From source file:net.sbbi.upnp.jmx.UPNPMBeanDevicesDiscoveryHandler.java
private void sendHello(UPNPMBeanDevice dv) throws IOException { InetAddress group = InetAddress.getByName("239.255.255.250"); java.net.MulticastSocket multi = new java.net.MulticastSocket(bindAddress.getPort()); multi.setInterface(bindAddress.getAddress()); multi.setTimeToLive(dv.getSSDPTTL()); List packets = getReplyMessages(dv, true, dv.getSSDPAliveDelay()); for (int i = 0; i < packets.size(); i++) { String packet = (String) packets.get(i); if (log.isDebugEnabled()) log.debug("Sending ssdp alive message on 239.255.255.250:1900 multicast address:\n" + packet.toString()); byte[] pk = packet.getBytes(); multi.send(new DatagramPacket(pk, pk.length, group, 1900)); }//from ww w. j a v a 2s . c om multi.close(); }