List of usage examples for java.net DatagramPacket getAddress
public synchronized InetAddress getAddress()
From source file:examples.ntp.SimpleNTPServer.java
/** * Handle incoming packet. If NTP packet is client-mode then respond * to that host with a NTP response packet otherwise ignore. * * @param request incoming DatagramPacket * @param rcvTime time packet received// ww w.j a va 2s . c o m * * @throws IOException if an I/O error occurs. */ protected void handlePacket(DatagramPacket request, long rcvTime) throws IOException { NtpV3Packet message = new NtpV3Impl(); message.setDatagramPacket(request); System.out.printf("NTP packet from %s mode=%s%n", request.getAddress().getHostAddress(), NtpUtils.getModeName(message.getMode())); if (message.getMode() == NtpV3Packet.MODE_CLIENT) { NtpV3Packet response = new NtpV3Impl(); response.setStratum(1); response.setMode(NtpV3Packet.MODE_SERVER); response.setVersion(NtpV3Packet.VERSION_3); response.setPrecision(-20); response.setPoll(0); response.setRootDelay(62); response.setRootDispersion((int) (16.51 * 65.536)); // originate time as defined in RFC-1305 (t1) response.setOriginateTimeStamp(message.getTransmitTimeStamp()); // Receive Time is time request received by server (t2) response.setReceiveTimeStamp(TimeStamp.getNtpTime(rcvTime)); response.setReferenceTime(response.getReceiveTimeStamp()); response.setReferenceId(0x4C434C00); // LCL (Undisciplined Local Clock) // Transmit time is time reply sent by server (t3) response.setTransmitTime(TimeStamp.getNtpTime(System.currentTimeMillis())); DatagramPacket dp = response.getDatagramPacket(); dp.setPort(request.getPort()); dp.setAddress(request.getAddress()); socket.send(dp); } // otherwise if received packet is other than CLIENT mode then ignore it }
From source file:org.vesalainen.nmea.processor.SNTPServer.java
@Override public void run() { try {// w w w. ja v a2s.co m socket = new DatagramSocket(NTP_PORT); ntpMessage = new NtpV4Impl(); DatagramPacket datagramPacket = ntpMessage.getDatagramPacket(); while (true) { socket.receive(datagramPacket); log.info("NTP: received %s from %s %d", ntpMessage, datagramPacket.getAddress(), datagramPacket.getPort()); TimeStamp transmitTimeStamp = ntpMessage.getTransmitTimeStamp(); ntpMessage.setLeapIndicator(LI_NO_WARNING); ntpMessage.setMode(MODE_SERVER); ntpMessage.setStratum(1); ntpMessage.setPrecision(-20); ntpMessage.setRootDelay(0); ntpMessage.setRootDispersion(0); ntpMessage.setReferenceId(ReferenceIdentifier.GPS); ntpMessage.setReferenceTime(TimeStamp.getNtpTime(clock.getZonedDateTime().toEpochSecond())); ntpMessage.setOriginateTimeStamp(transmitTimeStamp); long time = clock.millis(); TimeStamp timeStamp = TimeStamp.getNtpTime(time); ntpMessage.setReceiveTimeStamp(timeStamp); ntpMessage.setTransmitTime(timeStamp); socket.send(datagramPacket); log.info("NTP: sent %s to %s %d diff=%d", ntpMessage, datagramPacket.getAddress(), datagramPacket.getPort(), time - transmitTimeStamp.getTime()); } } catch (Exception ex) { log.log(Level.SEVERE, ex, ""); } }
From source file:org.proto.led.network.WiFiControllerService.java
private void listenAndWaitAndThrowIntent(InetAddress broadcastIP, Integer port) throws Exception { byte[] recvBuf = new byte[400]; if (socket == null || socket.isClosed()) { socket = new DatagramSocket(port); socket.setSoTimeout(5000);/* w w w . j a v a2 s. com*/ socket.setBroadcast(true); } DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length); Log.i(TAG, "Waiting for UDP broadcast"); socket.receive(packet); String senderIP = packet.getAddress().getHostAddress(); parseMessage(recvBuf, senderIP); String message = new String(packet.getData()).trim(); Log.i(TAG, "Got UDP broadcast from " + senderIP + ", message: " + message); socket.close(); }
From source file:nl.mindef.c2sc.nbs.olsr.pud.uplink.server.cluster.impl.RelayClusterReceiverImpl.java
@Override public void run() { byte[] receiveBuffer = new byte[UplinkReceiver.BUFFERSIZE]; DatagramPacket packet = new DatagramPacket(receiveBuffer, receiveBuffer.length); while (this.run.get()) { try {//from w w w.j a v a2 s .c o m this.sock.receive(packet); InetAddress ip = packet.getAddress(); int port = packet.getPort(); if (this.logger.isDebugEnabled()) { this.logger.debug("received packet from RelayServer " + ip.getHostAddress() + ":" + port); } RelayServer me = this.relayServers.getMe(); if (!(ip.equals(me.getIp()) && (port != this.relayClusterUdpPort))) { DatagramPacket msg = RelayClusterMessage.fromWireFormat(packet, this.reportOnce); if (msg != null) { RelayServer rs = this.relayServers.getOrAdd(ip, port); boolean packetCausedUpdate = this.packetHandler.processPacket(rs, msg); if (this.relayClusterForwarding && packetCausedUpdate) { if (this.logger.isDebugEnabled()) { this.logger.debug( "forwarding packet from RelayServer " + ip.getHostAddress() + ":" + port); } this.relayClusterSender.addPacket(rs, msg); } } else { this.logger.error("Could not convert RelayClusterMessage from wire format"); } } else { if (this.logger.isDebugEnabled()) { this.logger.debug("skipping packet from RelayServer " + ip.getHostAddress() + ":" + port + " since the packet came from me"); } } } catch (Exception e) { if (!SocketException.class.equals(e.getClass())) { e.printStackTrace(); } } } if (this.sock != null) { this.sock.close(); this.sock = null; } }
From source file:org.apache.jmeter.JMeter.java
private static void waitForSignals(final List<JMeterEngine> engines, DatagramSocket socket) { byte[] buf = new byte[80]; System.out.println(//from w w w. j a va2 s . c om "Waiting for possible Shutdown/StopTestNow/Heapdump message on port " + socket.getLocalPort()); DatagramPacket request = new DatagramPacket(buf, buf.length); try { while (true) { socket.receive(request); InetAddress address = request.getAddress(); // Only accept commands from the local host if (address.isLoopbackAddress()) { String command = new String(request.getData(), request.getOffset(), request.getLength(), "ASCII"); System.out.println("Command: " + command + " received from " + address); log.info("Command: " + command + " received from " + address); if (command.equals("StopTestNow")) { for (JMeterEngine engine : engines) { engine.stopTest(true); } } else if (command.equals("Shutdown")) { for (JMeterEngine engine : engines) { engine.stopTest(false); } } else if (command.equals("HeapDump")) { HeapDumper.dumpHeap(); } else { System.out.println("Command: " + command + " not recognised "); } } } } catch (Exception e) { System.out.println(e); } finally { socket.close(); } }
From source file:com.offbynull.portmapper.natpmp.NatPmpReceiver.java
/** * Start listening for NAT-PMP events. This method blocks until {@link #stop() } is called. * @param listener listener to notify of events * @throws IOException if socket error occurs * @throws NullPointerException if any argument is {@code null} *///from ww w . j ava 2s. c om public void start(NatPmpEventListener listener) throws IOException { Validate.notNull(listener); MulticastSocket socket = null; try { final InetAddress group = InetAddress.getByName("224.0.0.1"); // NOPMD final int port = 5350; final InetSocketAddress groupAddress = new InetSocketAddress(group, port); socket = new MulticastSocket(port); if (!currentSocket.compareAndSet(null, socket)) { IOUtils.closeQuietly(socket); return; } socket.setReuseAddress(true); Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = interfaces.nextElement(); Enumeration<InetAddress> addrs = networkInterface.getInetAddresses(); while (addrs.hasMoreElements()) { // make sure atleast 1 ipv4 addr bound to interface InetAddress addr = addrs.nextElement(); try { if (addr instanceof Inet4Address) { socket.joinGroup(groupAddress, networkInterface); } } catch (IOException ioe) { // NOPMD // occurs with certain interfaces // do nothing } } } ByteBuffer buffer = ByteBuffer.allocate(12); DatagramPacket data = new DatagramPacket(buffer.array(), buffer.capacity()); while (true) { buffer.clear(); socket.receive(data); buffer.position(data.getLength()); buffer.flip(); if (!data.getAddress().equals(gatewayAddress)) { // data isn't from our gateway, ignore continue; } if (buffer.remaining() != 12) { // data isn't the expected size, ignore continue; } int version = buffer.get(0); if (version != 0) { // data doesn't have the correct version, ignore continue; } int opcode = buffer.get(1) & 0xFF; if (opcode != 128) { // data doesn't have the correct op, ignore continue; } int resultCode = buffer.getShort(2) & 0xFFFF; switch (resultCode) { case 0: break; default: continue; // data doesn't have a successful result, ignore } listener.publicAddressUpdated(new ExternalAddressNatPmpResponse(buffer)); } } catch (IOException ioe) { if (currentSocket.get() == null) { return; // ioexception caused by interruption/stop, so just return without propogating error up } throw ioe; } finally { IOUtils.closeQuietly(socket); currentSocket.set(null); } }
From source file:org.eclipse.smarthome.binding.ntp.server.SimpleNTPServer.java
private void handleRequest(DatagramPacket requestPacket) throws IOException { final long receivedTime = System.currentTimeMillis(); NtpV3Packet responsePacket = new NtpV3Impl(); responsePacket.setMode(NtpV3Packet.MODE_SERVER); responsePacket.setTransmitTime(TimeStamp.getNtpTime(receivedTime)); DatagramPacket dataPacket = responsePacket.getDatagramPacket(); dataPacket.setPort(requestPacket.getPort()); dataPacket.setAddress(requestPacket.getAddress()); socket.send(dataPacket);/*from w w w.j a va 2 s . c om*/ }
From source file:com.clearspring.metriccatcher.MetricCatcher.java
/** * Grab metric messages off the listening socket, creating and updating * them as needed./* ww w . ja v a 2 s .c o m*/ */ @Override public void run() { // Arbitrary. One metric with a reasonable name is less than 200b // This (http://stackoverflow.com/q/3712151/17339) implies that 64 bit // leenuks will handle packets up to 24,258b, so let's assume we won't // get anything larger than that. Note that this is a hard limit-you // can't accumulate from the socket so anything larger is truncated. byte[] data = new byte[24258]; // Keep track of the last 1000 packets we've seen byte[] json = null; while (shutdown.get() == false) { DatagramPacket received = new DatagramPacket(data, data.length); try { // Pull in network data socket.receive(received); json = received.getData(); if (logger.isDebugEnabled()) { logger.debug("Got packet from " + received.getAddress() + ":" + received.getPort()); if (logger.isTraceEnabled()) { String jsonString = new String(json); logger.trace("JSON: " + jsonString); } } // Turn bytes of JSON into JSONMetric objects TypeReference<List<JSONMetric>> typeRef = new TypeReference<List<JSONMetric>>() { }; List<JSONMetric> jsonMetrics = mapper.readValue(json, typeRef); // Parse all of the metrics in the message for (JSONMetric jsonMetric : jsonMetrics) { if (!metricCache.containsKey(jsonMetric.getName())) { logger.info("Creating new " + jsonMetric.getType().name() + " metric for '" + jsonMetric.getName() + "'"); Metric newMetric = createMetric(jsonMetric); metricCache.put(jsonMetric.getName(), newMetric); } // Record the update logger.debug("Updating " + jsonMetric.getType() + " '" + jsonMetric.getName() + "' with <" + jsonMetric.getValue() + ">"); updateMetric(metricCache.get(jsonMetric.getName()), jsonMetric.getValue()); } } catch (IOException e) { logger.warn("IO error: " + e); String jsonString = new String(json); logger.warn("JSON: " + jsonString); } } socket.close(); }
From source file:org.necsave.NecsaveTransport.java
private Message readMessage() throws Exception { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); ProtoInputStream pis = new ProtoInputStream(new ByteArrayInputStream(receiveData), ProtoDefinition.getInstance()); Message msg = ProtoDefinition.getInstance().nextMessage(pis); if (msg instanceof PlatformInfo) process((PlatformInfo) msg, receivePacket.getAddress().getHostAddress(), receivePacket.getPort()); NeptusLog.pub().debug("Received message of type '" + msg.getAbbrev() + "' from " + receivePacket.getAddress() + " - Platform " + platformNames.get(msg.getSrc())); return msg;//from w w w .j a v a 2 s.c o m }
From source file:Network.Network.java
private String discoverUDPServer() { DatagramSocket c;/* ww w .j a v 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; }