List of usage examples for java.net DatagramPacket DatagramPacket
public DatagramPacket(byte buf[], int length, SocketAddress address)
From source file:sx.blah.discord.api.internal.UDPVoiceSocket.java
/** * Obtains the machine's external IP address and port to send to Discord. * * @param ssrc The self user's ssrc.//from w w w . j av a 2 s.c o m * @return A pair of the machine's external IP address and port. * @throws IOException Thrown by underlying UDP socket. * * @see <a href=https://discordapp.com/developers/docs/topics/voice-connections#ip-discovery>IP Discovery</a> */ private Pair<String, Integer> doIPDiscovery(int ssrc) throws IOException { byte[] data = ByteBuffer.allocate(70).putInt(ssrc).array(); DatagramPacket discoveryPacket = new DatagramPacket(data, data.length, address); udpSocket.send(discoveryPacket); DatagramPacket responsePacket = new DatagramPacket(new byte[70], 70); udpSocket.receive(responsePacket); byte[] receivedData = responsePacket.getData(); String ip = new String(Arrays.copyOfRange(receivedData, 4, 68)).trim(); int port = ((((int) receivedData[69]) & 0x000000FF) << 8) | (((int) receivedData[68]) & 0x000000FF); return Pair.of(ip, port); }
From source file:org.openhab.binding.wemo.internal.WemoBinding.java
public void wemoDiscovery() { logger.debug("wemoDiscovery() is called!"); try {/*from w w w .j a va 2s. c o m*/ final int SSDP_PORT = 1900; final int SSDP_SEARCH_PORT = 1901; // Broadcast address final String SSDP_IP = "239.255.255.250"; // Connection timeout int TIMEOUT = 1000; // Send from localhost:1901 InetAddress localhost = InetAddress.getLocalHost(); InetSocketAddress srcAddress = new InetSocketAddress(localhost, SSDP_SEARCH_PORT); // Send to 239.255.255.250:1900 InetSocketAddress dstAddress = new InetSocketAddress(InetAddress.getByName(SSDP_IP), SSDP_PORT); // Request-Packet-Constructor StringBuffer discoveryMessage = new StringBuffer(); discoveryMessage.append("M-SEARCH * HTTP/1.1\r\n"); discoveryMessage.append("HOST: " + SSDP_IP + ":" + SSDP_PORT + "\r\n"); discoveryMessage.append("MAN: \"ssdp:discover\"\r\n"); discoveryMessage.append("MX: 5\r\n"); discoveryMessage.append("ST: urn:Belkin:service:basicevent:1\r\n"); discoveryMessage.append("\r\n"); logger.trace("Request: {}", discoveryMessage.toString()); byte[] discoveryMessageBytes = discoveryMessage.toString().getBytes(); DatagramPacket discoveryPacket = new DatagramPacket(discoveryMessageBytes, discoveryMessageBytes.length, dstAddress); // Send multi-cast packet MulticastSocket multicast = null; try { multicast = new MulticastSocket(null); multicast.bind(srcAddress); logger.trace("Source-Address = '{}'", srcAddress); multicast.setTimeToLive(5); logger.trace("Send multicast request."); multicast.send(discoveryPacket); } finally { logger.trace("Multicast ends. Close connection."); multicast.disconnect(); multicast.close(); } // Response-Listener MulticastSocket wemoReceiveSocket = null; DatagramPacket receivePacket = null; try { wemoReceiveSocket = new MulticastSocket(SSDP_SEARCH_PORT); wemoReceiveSocket.setTimeToLive(10); wemoReceiveSocket.setSoTimeout(TIMEOUT); logger.debug("Send datagram packet."); wemoReceiveSocket.send(discoveryPacket); while (true) { try { logger.debug("Receive SSDP Message."); receivePacket = new DatagramPacket(new byte[2048], 2048); wemoReceiveSocket.receive(receivePacket); final String message = new String(receivePacket.getData()); if (message.contains("Belkin")) { logger.trace("Received message: {}", message); } new Thread(new Runnable() { @Override public void run() { if (message != null) { String location = StringUtils.substringBetween(message, "LOCATION: ", "/setup.xml"); String udn = StringUtils.substringBetween(message, "USN: uuid:", "::urn:Belkin"); if (udn != null) { logger.trace("Save location '{}' for WeMo device with UDN '{}'", location, udn); wemoConfigMap.put(udn, location); logger.info("Wemo Device with UDN '{}' discovered", udn); } } } }).start(); } catch (SocketTimeoutException e) { logger.debug("Message receive timed out."); for (String name : wemoConfigMap.keySet()) { logger.trace(name + ":" + wemoConfigMap.get(name)); } break; } } } finally { if (wemoReceiveSocket != null) { wemoReceiveSocket.disconnect(); wemoReceiveSocket.close(); } } } catch (Exception e) { logger.error("Could not start wemo device discovery", e); } }
From source file:org.springframework.integration.syslog.inbound.SyslogReceivingChannelAdapterTests.java
@Test public void testUdpRFC5424() throws Exception { SyslogReceivingChannelAdapterFactoryBean factory = new SyslogReceivingChannelAdapterFactoryBean( SyslogReceivingChannelAdapterFactoryBean.Protocol.udp); int port = SocketUtils.findAvailableUdpSocket(1514); factory.setPort(port);/* w ww . jav a 2 s .c o m*/ PollableChannel outputChannel = new QueueChannel(); factory.setOutputChannel(outputChannel); factory.setBeanFactory(mock(BeanFactory.class)); factory.setConverter(new RFC5424MessageConverter()); factory.afterPropertiesSet(); factory.start(); UdpSyslogReceivingChannelAdapter adapter = (UdpSyslogReceivingChannelAdapter) factory.getObject(); Thread.sleep(1000); byte[] buf = ("<14>1 2014-06-20T09:14:07+00:00 loggregator d0602076-b14a-4c55-852a-981e7afeed38 DEA - " + "[exampleSDID@32473 iut=\\\"3\\\" eventSource=\\\"Application\\\" eventID=\\\"1011\\\"]" + "[exampleSDID@32473 iut=\\\"3\\\" eventSource=\\\"Application\\\" eventID=\\\"1011\\\"] Removing instance") .getBytes("UTF-8"); DatagramPacket packet = new DatagramPacket(buf, buf.length, new InetSocketAddress("localhost", port)); DatagramSocket socket = new DatagramSocket(); socket.send(packet); socket.close(); @SuppressWarnings("unchecked") Message<Map<String, ?>> message = (Message<Map<String, ?>>) outputChannel.receive(10000); assertNotNull(message); assertEquals("loggregator", message.getPayload().get("syslog_HOST")); adapter.stop(); }
From source file:net.sbbi.upnp.Discovery.java
/** * Sends an SSDP search message on the network * @param src the sender ip/*from ww w . j a v a2 s.c o m*/ * @param ttl the time to live * @param mx the mx field * @param searchTarget the search target * @throws IOException if some IO errors occurs during search */ public static void sendSearchMessage(InetAddress src, int ttl, int mx, String searchTarget) throws IOException { int bindPort = DEFAULT_SSDP_SEARCH_PORT; String port = System.getProperty("net.sbbi.upnp.Discovery.bindPort"); if (port != null) { bindPort = Integer.parseInt(port); } InetSocketAddress adr = new InetSocketAddress(InetAddress.getByName(Discovery.SSDP_IP), Discovery.SSDP_PORT); java.net.MulticastSocket skt = new java.net.MulticastSocket(null); skt.bind(new InetSocketAddress(src, bindPort)); skt.setTimeToLive(ttl); StringBuffer packet = new StringBuffer(); packet.append("M-SEARCH * HTTP/1.1\r\n"); packet.append("HOST: 239.255.255.250:1900\r\n"); packet.append("MAN: \"ssdp:discover\"\r\n"); packet.append("MX: ").append(mx).append("\r\n"); packet.append("ST: ").append(searchTarget).append("\r\n").append("\r\n"); if (log.isDebugEnabled()) log.debug("Sending discovery message on 239.255.255.250:1900 multicast address form ip " + src.getHostAddress() + ":\n" + packet.toString()); String toSend = packet.toString(); byte[] pk = toSend.getBytes(); skt.send(new DatagramPacket(pk, pk.length, adr)); skt.disconnect(); skt.close(); }
From source file:org.apache.nifi.processors.standard.TestListenUDP.java
protected void run(final DatagramSocket socket, final List<String> messages, final int expectedQueueSize, final int expectedTransferred) throws IOException, InterruptedException { try {//from w w w .ja va2 s . c o m // schedule to start listening on a random port final ProcessSessionFactory processSessionFactory = runner.getProcessSessionFactory(); final ProcessContext context = runner.getProcessContext(); proc.onScheduled(context); Thread.sleep(100); // get the real port the dispatcher is listening on final int destPort = proc.getDispatcherPort(); final InetSocketAddress destination = new InetSocketAddress("localhost", destPort); // send the messages to the port the processors is listening on for (final String message : messages) { final byte[] buffer = message.getBytes(StandardCharsets.UTF_8); final DatagramPacket packet = new DatagramPacket(buffer, buffer.length, destination); socket.send(packet); Thread.sleep(10); } long responseTimeout = 10000; // this first loop waits until the internal queue of the processor has the expected // number of messages ready before proceeding, we want to guarantee they are all there // before onTrigger gets a chance to run long startTimeQueueSizeCheck = System.currentTimeMillis(); while (proc.getQueueSize() < expectedQueueSize && (System.currentTimeMillis() - startTimeQueueSizeCheck < responseTimeout)) { Thread.sleep(100); } // want to fail here if the queue size isn't what we expect Assert.assertEquals(expectedQueueSize, proc.getQueueSize()); // call onTrigger until we processed all the messages, or a certain amount of time passes int numTransferred = 0; long startTime = System.currentTimeMillis(); while (numTransferred < expectedTransferred && (System.currentTimeMillis() - startTime < responseTimeout)) { proc.onTrigger(context, processSessionFactory); numTransferred = runner.getFlowFilesForRelationship(ListenUDP.REL_SUCCESS).size(); Thread.sleep(100); } // should have transferred the expected events runner.assertTransferCount(ListenUDP.REL_SUCCESS, expectedTransferred); } finally { // unschedule to close connections proc.onUnscheduled(); IOUtils.closeQuietly(socket); } }
From source file:sx.blah.discord.api.internal.UDPVoiceSocket.java
/** * Sends {@link #SILENCE_FRAMES} on the voice socket. * * @throws IOException Thrown by the underlying UDP socket. */// ww w . j av a 2s . c om private void sendSilence() throws IOException { OpusPacket packet = new OpusPacket(sequence, timestamp, ssrc, SILENCE_FRAMES); packet.encrypt(secret); byte[] toSend = packet.asByteArray(); udpSocket.send(new DatagramPacket(toSend, toSend.length, address)); }
From source file:net.dv8tion.jda.audio.AudioWebSocket.java
private InetSocketAddress handleUdpDiscovery(InetSocketAddress address, int ssrc) { //We will now send a packet to discord to punch a port hole in the NAT wall. //This is called UDP hole punching. try {//from w ww .j av a2s. co m udpSocket = new DatagramSocket(); //Use UDP, not TCP. //Create a byte array of length 70 containing our ssrc. ByteBuffer buffer = ByteBuffer.allocate(70); //70 taken from https://github.com/Rapptz/discord.py/blob/async/discord/voice_client.py#L208 buffer.putInt(ssrc); //Put the ssrc that we were given into the packet to send back to discord. //Construct our packet to be sent loaded with the byte buffer we store the ssrc in. DatagramPacket discoveryPacket = new DatagramPacket(buffer.array(), buffer.array().length, address); udpSocket.send(discoveryPacket); //Discord responds to our packet, returning a packet containing our external ip and the port we connected through. DatagramPacket receivedPacket = new DatagramPacket(new byte[70], 70); //Give a buffer the same size as the one we sent. udpSocket.setSoTimeout(1000); udpSocket.receive(receivedPacket); //The byte array returned by discord containing our external ip and the port that we used //to connect to discord with. byte[] received = receivedPacket.getData(); //Example string:" 121.83.253.66 " //You'll notice that there are 4 leading nulls and a large amount of nulls between the the ip and // the last 2 bytes. Not sure why these exist. The last 2 bytes are the port. More info below. String ourIP = new String(receivedPacket.getData());//Puts the entire byte array in. nulls are converted to spaces. ourIP = ourIP.substring(0, ourIP.length() - 2); //Removes the port that is stuck on the end of this string. (last 2 bytes are the port) ourIP = ourIP.trim(); //Removes the extra whitespace(nulls) attached to both sides of the IP //The port exists as the last 2 bytes in the packet data, and is encoded as an UNSIGNED short. //Furthermore, it is stored in Little Endian instead of normal Big Endian. //We will first need to convert the byte order from Little Endian to Big Endian (reverse the order) //Then we will need to deal with the fact that the bytes represent an unsigned short. //Java cannot deal with unsigned types, so we will have to promote the short to a higher type. //Options: char or int. I will be doing int because it is just easier to work with. byte[] portBytes = new byte[2]; //The port is exactly 2 bytes in size. portBytes[0] = received[received.length - 1]; //Get the second byte and store as the first portBytes[1] = received[received.length - 2]; //Get the first byte and store as the second. //We have now effectively converted from Little Endian -> Big Endian by reversing the order. //For more information on how this is converting from an unsigned short to an int refer to: //http://www.darksleep.com/player/JavaAndUnsignedTypes.html int firstByte = (0x000000FF & ((int) portBytes[0])); //Promotes to int and handles the fact that it was unsigned. int secondByte = (0x000000FF & ((int) portBytes[1])); // //Combines the 2 bytes back together. int ourPort = (firstByte << 8) | secondByte; this.address = address; return new InetSocketAddress(ourIP, ourPort); } catch (SocketException e) { return null; } catch (IOException e) { LOG.log(e); return null; } }
From source file:com.byteatebit.nbserver.simple.TestSimpleNbServer.java
@Test public void testUdpEchoServer() throws IOException { SimpleNbServer simpleNbServer = SimpleNbServer.Builder.builder() .withConfig(//from w w w . j a v a2 s .c o m SimpleNbServerConfig.builder().withListenAddress("localhost").withListenPort(1111).build()) .withConnectorFactory(UdpConnectorFactory.Builder.builder() .withDatagramMessageHandlerFactory(new UdpServiceFactory()).build()) .build(); simpleNbServer.start(); String message1 = "this is message1"; String message2 = "this is message2"; String message3 = "quit"; try { DatagramSocket socket = new DatagramSocket(); SocketAddress address = new InetSocketAddress("localhost", 1111); // message 1 byte[] payload1 = message1.getBytes(StandardCharsets.UTF_8); DatagramPacket packet = new DatagramPacket(payload1, payload1.length, address); socket.send(packet); byte[] response = new byte[50]; DatagramPacket responsePacket = new DatagramPacket(response, response.length); socket.receive(responsePacket); String messageRead = new String(responsePacket.getData(), 0, responsePacket.getLength()); Assert.assertEquals(message1, messageRead); // message2 byte[] payload2 = message2.getBytes(StandardCharsets.UTF_8); DatagramPacket packet2 = new DatagramPacket(payload2, payload2.length, address); socket.send(packet2); responsePacket = new DatagramPacket(response, response.length); socket.receive(responsePacket); messageRead = new String(responsePacket.getData(), 0, responsePacket.getLength()); Assert.assertEquals(message2, messageRead); // message3 byte[] payload3 = message3.getBytes(StandardCharsets.UTF_8); DatagramPacket packet3 = new DatagramPacket(payload3, payload3.length, address); socket.send(packet3); responsePacket = new DatagramPacket(response, response.length); socket.receive(responsePacket); messageRead = new String(responsePacket.getData(), 0, responsePacket.getLength()); Assert.assertEquals("goodbye", messageRead); } finally { simpleNbServer.shutdown(); } }
From source file:net.dv8tion.jda.core.audio.AudioWebSocket.java
private InetSocketAddress handleUdpDiscovery(InetSocketAddress address, int ssrc) { //We will now send a packet to discord to punch a port hole in the NAT wall. //This is called UDP hole punching. try {//from w ww . ja va 2s . co m udpSocket = new DatagramSocket(); //Use UDP, not TCP. //Create a byte array of length 70 containing our ssrc. ByteBuffer buffer = ByteBuffer.allocate(70); //70 taken from https://github.com/Rapptz/discord.py/blob/async/discord/voice_client.py#L208 buffer.putInt(ssrc); //Put the ssrc that we were given into the packet to send back to discord. //Construct our packet to be sent loaded with the byte buffer we store the ssrc in. DatagramPacket discoveryPacket = new DatagramPacket(buffer.array(), buffer.array().length, address); udpSocket.send(discoveryPacket); //Discord responds to our packet, returning a packet containing our external ip and the port we connected through. DatagramPacket receivedPacket = new DatagramPacket(new byte[70], 70); //Give a buffer the same size as the one we sent. udpSocket.setSoTimeout(1000); udpSocket.receive(receivedPacket); //The byte array returned by discord containing our external ip and the port that we used //to connect to discord with. byte[] received = receivedPacket.getData(); //Example string:" 121.83.253.66 " //You'll notice that there are 4 leading nulls and a large amount of nulls between the the ip and // the last 2 bytes. Not sure why these exist. The last 2 bytes are the port. More info below. String ourIP = new String(receivedPacket.getData());//Puts the entire byte array in. nulls are converted to spaces. ourIP = ourIP.substring(4, ourIP.length() - 2); //Removes the SSRC of the answer package and the port that is stuck on the end of this string. (last 2 bytes are the port) ourIP = ourIP.trim(); //Removes the extra whitespace(nulls) attached to both sides of the IP //The port exists as the last 2 bytes in the packet data, and is encoded as an UNSIGNED short. //Furthermore, it is stored in Little Endian instead of normal Big Endian. //We will first need to convert the byte order from Little Endian to Big Endian (reverse the order) //Then we will need to deal with the fact that the bytes represent an unsigned short. //Java cannot deal with unsigned types, so we will have to promote the short to a higher type. //Options: char or int. I will be doing int because it is just easier to work with. byte[] portBytes = new byte[2]; //The port is exactly 2 bytes in size. portBytes[0] = received[received.length - 1]; //Get the second byte and store as the first portBytes[1] = received[received.length - 2]; //Get the first byte and store as the second. //We have now effectively converted from Little Endian -> Big Endian by reversing the order. //For more information on how this is converting from an unsigned short to an int refer to: //http://www.darksleep.com/player/JavaAndUnsignedTypes.html int firstByte = (0x000000FF & ((int) portBytes[0])); //Promotes to int and handles the fact that it was unsigned. int secondByte = (0x000000FF & ((int) portBytes[1])); // //Combines the 2 bytes back together. int ourPort = (firstByte << 8) | secondByte; this.address = address; return new InetSocketAddress(ourIP, ourPort); } catch (SocketException e) { return null; } catch (IOException e) { return null; } }