List of usage examples for java.net DatagramPacket getAddress
public synchronized InetAddress getAddress()
From source file:QuoteServerThread.java
public void run() { if (socket == null) return;/*w ww . j ava2 s.com*/ while (moreQuotes) { try { byte[] buf = new byte[256]; DatagramPacket packet; InetAddress address; int port; String dString = null; // receive request packet = new DatagramPacket(buf, 256); socket.receive(packet); address = packet.getAddress(); port = packet.getPort(); // send response if (qfs == null) dString = new Date().toString(); else dString = getNextQuote(); buf = dString.getBytes(); packet = new DatagramPacket(buf, buf.length, address, port); socket.send(packet); } catch (IOException e) { System.err.println("IOException: " + e); moreQuotes = false; e.printStackTrace(); } } socket.close(); }
From source file:org.opennms.netmgt.syslogd.ConvertToEvent.java
/** * Constructs a new event encapsulation instance based upon the * information passed to the method. The passed datagram data is decoded * into a string using the <tt>US-ASCII</tt> character encoding. * * @param packet The datagram received from the remote agent. * @throws java.io.UnsupportedEncodingException * Thrown if the data buffer cannot be decoded using the * US-ASCII encoding./*from ww w . ja va 2 s .co m*/ * @throws MessageDiscardedException */ public ConvertToEvent(final DatagramPacket packet, final SyslogdConfig config) throws UnsupportedEncodingException, MessageDiscardedException { this(packet.getAddress(), packet.getPort(), new String(packet.getData(), 0, packet.getLength(), "US-ASCII"), config); }
From source file:cai.flow.collector.Collector.java
/** * UDP//from ww w . j a va2 s. co m * * @param p */ void put_to_queue(final DatagramPacket p) { InetAddress router = p.getAddress(); InetAddress group = (InetAddress) routers.get(router); if (group == null) { logger.warn("A packet from an unauthorized device is ignored. Device: " + router); return; } logger.debug("Packet from device " + router + " is moved to group " + group); p.setAddress(group);// routergroup if (data_queue.size() > max_queue_length) { logger.warn("Reader - the queue is bigger than max_queue_length: " + data_queue.size() + "/" + max_queue_length); } synchronized (data_queue) { data_queue.addLast(p); queued++; if (p == null) data_queue.notifyAll();// else data_queue.notify();// } }
From source file:org.avineas.fins.gw.Gateway.java
/** * The after properties set method of this gateway. The method initializes * a new thread that continuously reads from the UDP port for getting data * for local (or remote) nodes. This method <b>must</b> be called before * actual receiving of data can take place. *//*from w ww .j a v a2s . c o m*/ @PostConstruct public void init() throws SocketException { if (thread != null) return; if (channel == null) setPort(9600); // Initialize the nodes and handling of the packets. thread = new Thread() { @SuppressWarnings("synthetic-access") @Override public void run() { byte[] data = new byte[Frame.MAXFRAMESIZE]; logger.info(Gateway.this + " started"); for (;;) { try { // Read a datagram from the network DatagramPacket dpacket = new DatagramPacket(data, 0, data.length); channel.receive(dpacket); // Update the FINS node/gateway information Destination dest = new Destination(dpacket.getAddress(), dpacket.getPort()); traceDatagram(dest + " -> " + channel.getLocalPort(), dpacket); Frame packet = new Frame(data, dpacket.getLength()); Address from = packet.getSource(); setDestination(from.getNodeAsString(), dest); // Handle the packet. It is either forwarded to // a remote machine or locally handled. // Note that there is a possibility that gateways keep // each other busy with sending data to each other. This // cannot be prevented here. Address to = packet.getDestination(); NodeUnit unit = units.get(to.toString()); if (unit != null) { logger.info("received " + (packet.isReply() ? "reply" : "packet") + " frame from: " + dest + ", for local unit: " + to + " from: " + packet.getSource()); Frame reply = unit.handleFrame(packet); if (reply != null) send(reply); } else { logger.info("frame for node " + to + " cannot be handled locally, trying forward"); send(packet); } } catch (Exception exc) { if (!runDown) { synchronized (this) { // Will normally only occur when the port is changed on the fly logger.error("exception handling frame", exc); } } } // In case we were shut down, stop if (runDown) break; } logger.info("FINS gateway shutdown complete"); } }; thread.start(); }
From source file:com.all.landownloader.discovery.LanDiscoverySocket.java
public LanDiscoveredPeer listen() throws IOException, IllegalArgumentException { MulticastSocket socket = new MulticastSocket(PORT); socket.joinGroup(addressGroup);//from w w w . ja v a2s. com byte[] buf = new byte[BUF_LENGTH]; DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); socket.leaveGroup(addressGroup); socket.close(); InetAddress address = packet.getAddress(); byte[] remotePortBuffer = new byte[4]; System.arraycopy(buf, HEADER_LENGTH, remotePortBuffer, 0, remotePortBuffer.length); LanDiscoveredPeer discoveredPeer = new LanDiscoveredPeer(address, LanUtils.decodeInt(remotePortBuffer)); if (eq(BYE_MSG, buf, HEADER_LENGTH)) { addresses.remove(address); RegisteredAddress remove = quickLeases.remove(address); if (remove != null) { leases.remove(remove); } return null; } RegisteredAddress reg = quickLeases.get(discoveredPeer); long nextLeaseTime = System.currentTimeMillis() + this.leaseTime; if (reg == null) { reg = new RegisteredAddress(nextLeaseTime, discoveredPeer); quickLeases.put(discoveredPeer, reg); } else { reg.setLease(nextLeaseTime); } if (eq(ANNOUNCE_MSG, buf, HEADER_LENGTH)) { reply(address); } leases.add(reg); addresses.add(discoveredPeer); return discoveredPeer; }
From source file:org.openhab.binding.edimax.internal.UDPDiscoverer.java
private EdimaxDevice[] discover() throws SocketException, UnknownHostException, IOException { List<EdimaxDevice> discoveredDevices = new ArrayList<EdimaxDevice>(); DatagramSocket serverSocket = null; try {//from ww w . j av a2s. c om serverSocket = new DatagramSocket(12346); // choose random port, // because with empty // port sometimes error // occures. // send UDP broadcast InetAddress ipAddress = InetAddress.getByName("255.255.255.255"); byte[] sendData = DISCOVERY_BYTES; DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ipAddress, 20560); serverSocket.send(sendPacket); // receive serverSocket.setSoTimeout(1000 * 5); byte[] receiveData = new byte[1024]; try { while (true) { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); String sentence = new String(receivePacket.getData()); if (!StringUtils.isEmpty(sentence) && sentence.contains("EDIMAX")) { byte[] mac = new byte[6]; System.arraycopy(receivePacket.getData(), 0, mac, 0, 6); String encodedMAC = Hex.encodeHexString(mac).toUpperCase(); InetAddress discoveredIp = receivePacket.getAddress(); EdimaxDevice dev = new EdimaxDevice(); dev.setIp(discoveredIp.getHostAddress()); dev.setMac(encodedMAC); discoveredDevices.add(dev); } } } catch (SocketTimeoutException e) { // intended to happen } } finally { if (serverSocket != null) { serverSocket.close(); } } return discoveredDevices.toArray(new EdimaxDevice[discoveredDevices.size()]); }
From source file:com.esri.geoevent.test.performance.ClockSync.java
@Override public void run() { DatagramSocket socket = null; try {/*from www . j a va2 s . co m*/ byte[] incomingBuffer = new byte[1024]; DatagramPacket packet = new DatagramPacket(incomingBuffer, incomingBuffer.length); ByteBuffer bb = ByteBuffer.allocate(8); DatagramPacket outgoingPacket = new DatagramPacket(bb.array(), 0, 8, null, port); socket = new DatagramSocket(port); socket.setSoTimeout(100); while (isRunning.get()) { try { socket.receive(packet); long now = System.currentTimeMillis(); bb.putLong(now); outgoingPacket.setAddress(packet.getAddress()); outgoingPacket.setPort(packet.getPort()); socket.send(outgoingPacket); bb.clear(); //System.out.println("Sent the time " + now); } catch (SocketTimeoutException ex) { // Do nothing if nothing was sent. } } } catch (BindException e) { // port is in use - increment and try again port++; this.run(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(socket); } }
From source file:de.jaetzold.networking.SimpleServiceDiscovery.java
private HueBridge parseResponsePacket(DatagramPacket receivePacket) { Log.d("HUE", "parse resonse"); HueBridge bridge = null;// www . java2s . co m String message = new String(receivePacket.getData()); if (message.contains("/description.xml")) { //System.out.println("there is a description.xml, lets get it"); InetAddress address = receivePacket.getAddress(); bridge = new HueBridge(address, "xx26xxb3xx10xx0fxx5bxxabxx7bxx57"); } return bridge; }
From source file:nl.mindef.c2sc.nbs.olsr.pud.uplink.server.handlers.impl.PacketHandlerImpl.java
@Override @Transactional// w w w .j av a 2 s .c o m public boolean processPacket(RelayServer relayServer, DatagramPacket packet) { try { this.txChecker.checkInTx("PacketHandler::processPacket"); } catch (Throwable e) { e.printStackTrace(); } long utcTimestamp = System.currentTimeMillis(); boolean updated = false; if (this.logger.isDebugEnabled()) { this.logger.debug("[" + utcTimestamp + "] Received " + packet.getLength() + " bytes from " + packet.getAddress().getHostAddress() + ":" + packet.getPort()); } try { InetAddress srcIp = packet.getAddress(); int srcPort = packet.getPort(); /* get sender or create */ Sender sender = this.senders.getSender(srcIp, srcPort); if (sender == null) { sender = new Sender(srcIp, Integer.valueOf(srcPort), relayServer); } /* make sure the sender is linked to this relayServer */ sender.setRelayServer(relayServer); /* get packet data */ byte[] packetData = packet.getData(); int packetLength = packet.getLength(); /* parse the uplink packet for messages */ int messageOffset = 0; while (messageOffset < packetLength) { int messageType = UplinkMessage.getUplinkMessageType(packetData, messageOffset); int messageLength = UplinkMessage.getUplinkMessageHeaderLength() + UplinkMessage.getUplinkMessageLength(packetData, messageOffset); if ((messageType != UplinkMessage.getUplinkMessageTypePosition()) && (messageType != UplinkMessage.getUplinkMessageTypeClusterLeader())) { this.logger.warn("Uplink message type " + messageType + " not supported: ignored"); } else { byte[] messageData = Arrays.copyOfRange(packetData, messageOffset, messageOffset + messageLength); DumpUtil.dumpUplinkMessage(this.logger, Level.DEBUG, messageData, srcIp, srcPort, messageType, utcTimestamp, " "); Object msg = null; boolean msgCausedUpdate = false; if (messageType == UplinkMessage.getUplinkMessageTypePosition()) { msg = new PositionUpdate(messageData, messageLength); msgCausedUpdate = this.positionUpdateHandler.handlePositionMessage(sender, utcTimestamp, (PositionUpdate) msg); } else /* if (messageType == UplinkMessage.getUplinkMessageTypeClusterLeader()) */ { msg = new ClusterLeader(messageData, messageLength); msgCausedUpdate = this.clusterLeaderHandler.handleClusterLeaderMessage(sender, utcTimestamp, (ClusterLeader) msg); } if (msgCausedUpdate && this.useFaker) { this.faker.fakeit(sender, utcTimestamp, msg); } updated = msgCausedUpdate || updated; } messageOffset += messageLength; } return updated; } catch (Throwable e) { this.logger.error("error during packet handling", e); return updated; } finally { if (this.useFaker) { this.faker.setFirstFake(false); } } }
From source file:udpserver.UDPui.java
private void receiveUDP() { countSeparate = new ArrayList<>(); background = new Runnable() { public void run() { try { serverSocket = new DatagramSocket(9876); } catch (SocketException ex) { Logger.getLogger(UDPui.class.getName()).log(Level.SEVERE, null, ex); }/*from w w w . j av a2 s. c om*/ // while (true) { // byte[] receiveData = new byte[1024]; // DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); //<editor-fold defaultstate="collapsed" desc="Start timer after receive a packet"> // try { // serverSocket.receive(receivePacket); // series.clear(); // valuePane.setText(""); available = true; // System.out.println(available); // } catch (IOException ex) { // Logger.getLogger(UDPui.class.getName()).log(Level.SEVERE, null, ex); // } // Timer timer = new Timer(); // timer.schedule(new TimerTask() { // @Override // public void run() { // available = false; // System.out.println("Finish Timer"); // } // }, 1 * 1000); //</editor-fold> // if (!new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength()).equals("")) { // int count = 1; // while (available) { while (true) { try { byte[] receiveData = new byte[total_byte]; byte[] sendData = new byte[32]; DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); String word = receivePacket.getAddress().getHostAddress(); System.out.println(word); String message = new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength()); boolean looprun = true; // System.out.println(message); while (looprun) { Integer countt = counting.get(word); if (message.contains("&")) { message = message.substring(message.indexOf("&") + 1); // count++; // Integer countt = counting.get(word); if (countt == null) { counting.put(word, 1); } else { counting.put(word, countt + 1); } // System.out.println(count + ":" + message); } else { if (countt == null) { counting.put(word, 1); } else { counting.put(word, countt + 1); } System.out.println(counting.get(word)); looprun = false; } } if (message.contains("start")) { if (counting.get(word) != null) { counting.remove(word); } } else if (message.contains("end")) { message = message.substring(message.indexOf("end") + 3); // valuePane.setCaretPosition(valuePane.getDocument().getLength()); //send back to mobile InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); // String capitalizedSentence = count + ""; String capitalizedSentence = counting.get(word) + ""; sendData = capitalizedSentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); serverSocket.send(sendPacket); String timeStamp = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss") .format(Calendar.getInstance().getTime()); String content = IPAddress.getCanonicalHostName() + "," + timeStamp + "," + (counting.get(word) - 1) + "," + message; saveFile(content); //end send back to mobile // System.out.println(counting.get(word)); // count = 1; counting.remove(word); // break; } else if (available) { //<editor-fold defaultstate="collapsed" desc="check hasmap key"> // if (hm.size() > 0 && hm.containsKey(serverSocket.getInetAddress().getHostAddress())) { // hm.put(foundKey, new Integer(((int) hm.get(foundKey)) + 1)); // hm.put(serverSocket.getInetAddress().getHostAddress(), new Integer(((int) hm.get(serverSocket.getInetAddress().getHostAddress())) + 1)); // } else { // hm.put(serverSocket.getInetAddress().getHostAddress(), 1); // hm.entrySet().add(new Map<String, Integer>.Entry<String, Integer>()); // } //</editor-fold> // series.add(count, Double.parseDouble(message)); // valuePane.setText(valuePane.getText().toString() + count + ":" + message + "\n"); // valuePane.setCaretPosition(valuePane.getDocument().getLength()); // count++; } } catch (IOException ex) { Logger.getLogger(UDPui.class.getName()).log(Level.SEVERE, null, ex); valuePane.setText(valuePane.getText().toString() + "IOException" + "\n"); } } // valuePane.setText(valuePane.getText().toString() + "Out of while loop" + "\n"); // } // } } private void saveFile(String content) { try { File desktop = new File(System.getProperty("user.home"), "Desktop"); File file = new File(desktop.getAbsoluteFile() + "/udp.csv"); if (!file.exists()) { file.createNewFile(); } FileOutputStream fop = new FileOutputStream(file, true); fop.write((content + "\n").getBytes()); fop.flush(); fop.close(); // String timeStamp = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").format(Calendar.getInstance().getTime()); // valuePane.setText(valuePane.getText().toString() + timeStamp + "\n"); } catch (IOException ex) { Logger.getLogger(UDPui.class.getName()).log(Level.SEVERE, null, ex); String timeStamp = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss") .format(Calendar.getInstance().getTime()); valuePane.setText(valuePane.getText().toString() + timeStamp + "\n"); } } }; backgroundProcess = new Thread(background); }