List of usage examples for java.net DatagramPacket getAddress
public synchronized InetAddress getAddress()
From source file:cai.flow.collector.Collector.java
/** * * @param p// w ww . j a v a 2s. c om */ private synchronized void processPacket(final DatagramPacket p) { final byte[] buf = p.getData(); int len = p.getLength(); String addr = p.getAddress().getHostAddress().trim(); synchronized (data_queue) { processed++; } logger.debug(addr + "(" + p.getAddress().getHostName() + ") " + len + " bytes"); try { if (len < 2) throw new DoneException(" * too short packet *"); short version = (short) Util.to_number(buf, 0, 2); if (version > MAX_VERION || version <= 0) throw new DoneException(" * unsupported version *"); if (!isVersionEnabled[version - 1]) throw new DoneException(" * version " + version + " disabled *"); logger.debug(" version: " + version); FlowPacket packet; switch (version) { case 1: packet = (FlowPacket) new V1_Packet(addr, buf, len); break; case 5: packet = (FlowPacket) new V5_Packet(addr, buf, len); break; // Temporarily removing NetFlow Version 7 until Resources fully removed /* case 7: packet = (FlowPacket) new V7_Packet(addr, resources, buf, len); break; */ case 8: packet = (FlowPacket) new V8_Packet(addr, buf, len); break; case 9: packet = (FlowPacket) new V9_Packet(addr, buf, len); break; default: logger.error("Collector - Version problem. Version = " + version); return; } aggregator.process(packet); } catch (DoneException e) { e.printStackTrace(); logger.info(e); } }
From source file:MulticastClient.java
public void run() { while (moreQuotes) { try { byte[] buf = new byte[256]; // receive request DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet);//from w w w .j av a2 s . c o m // figure out response String dString = null; if (in == null) dString = new Date().toString(); else dString = getNextQuote(); buf = dString.getBytes(); // send the response to the client at "address" and "port" InetAddress address = packet.getAddress(); int port = packet.getPort(); packet = new DatagramPacket(buf, buf.length, address, port); socket.send(packet); } catch (IOException e) { e.printStackTrace(); moreQuotes = false; } } socket.close(); }
From source file:org.psit.transwatcher.TransWatcher.java
private String connectAndGetCardIP() { DatagramSocket clientSocket = null, serverSocket = null; try {//from w w w. j a va2s . c om String broadcastIP = getBroadcastIP(); setState(broadcastIP == null ? State.NO_WIFI : State.SEARCHING_CARD); notifyMessage("BroadcastIP: " + broadcastIP); // send out broadcast clientSocket = new DatagramSocket(58255); InetAddress IPAddress = InetAddress.getByName(broadcastIP); byte[] sendData = "".getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 55777); clientSocket.send(sendPacket); clientSocket.close(); serverSocket = new DatagramSocket(58255); byte[] receiveData = new byte[256]; DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.setSoTimeout(3000); serverSocket.receive(receivePacket); serverSocket.close(); notifyMessage("Packet received: " + new String(receiveData)); if (new String(receivePacket.getData()).indexOf("Transcend WiFiSD") >= 0) return receivePacket.getAddress().getHostAddress(); } catch (Exception ex) { notifyMessage("Card handshake unsuccessful. "); notifyException(ex); } finally { if (clientSocket != null) clientSocket.close(); if (serverSocket != null) serverSocket.close(); } return null; }
From source file:gravity.android.discovery.DiscoveryServer.java
public void run() { Log.v("DISCOVERY_SERVER", "SERVER STARTED"); DatagramSocket serverSocket = null; try {// w ww . j av a 2 s .c om serverSocket = new DatagramSocket(port); byte[] receiveData; byte[] sendData; while (this.isInterrupted() == false) { receiveData = new byte[128]; sendData = new byte[128]; try { Log.v("DISCOVERY_SERVER", "LISTENING"); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); String sentence = new String(receivePacket.getData()); if (sentence != null) Log.v("DISCOVERY_SERVER", "RECEIVED: " + sentence.substring(0, receivePacket.getLength()).trim()); if (sentence != null && sentence.substring(0, receivePacket.getLength()).trim().equals(token)) { Log.v("DISCOVERY_SERVER", "SEND '" + nome + "' to " + receivePacket.getAddress().getHostAddress() + ":" + receivePacket.getPort()); JSONObject sendDataJson = new JSONObject(); sendDataJson.accumulate("name", nome); sendDataJson.accumulate("port_to_share", port_to_share); //sendData = (nome + "," + port_to_share).getBytes(); sendData = sendDataJson.toString().getBytes(); //Prakash: converts the data to json objects to avoid troubles DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, receivePacket.getAddress(), receivePacket.getPort()); serverSocket.send(sendPacket); } } catch (Exception ex) { ex.printStackTrace(); Log.e("DISCOVERY_SERVER", ex.toString()); } } } catch (Exception e) { e.printStackTrace(); Log.e("DISCOVERY_SERVER", e.toString()); } finally { try { if (serverSocket != null) serverSocket.close(); } catch (Exception ex) { } } }
From source file:com.kecso.socket.ServerSocketControl.java
@Override public void run() { DatagramSocket sock = null;//from www .j av a 2s .c o m try { sock = new DatagramSocket(8888); sock.setSoTimeout(1000); byte[] buffer = new byte[65536]; DatagramPacket incoming = new DatagramPacket(buffer, buffer.length); while (!Thread.currentThread().isInterrupted()) { try { sock.receive(incoming); byte[] data = incoming.getData(); this.udpMessage = SerializationUtils.deserialize(data); byte[] response = SerializationUtils.serialize( this.output != null ? new UdpResponse((float) output.getSpeed(), (float) output.getVerticalSpeed(), (float) output.getAltitude(), (float) output.getRpm()) : null); DatagramPacket dp = new DatagramPacket(response, response.length, incoming.getAddress(), incoming.getPort()); sock.send(dp); } catch (SocketTimeoutException e) { } } } catch (Exception e) { System.err.println("IOException " + e); } finally { if (sock != null) { sock.close(); } } }
From source file:com.clustercontrol.agent.Agent.java
/** * ??awakeAgent?//ww w . j av a 2 s . c om * Agent.properties???UDP?24005??????????(releaseLatch) * ????ReceiveTopic????Topic???? */ public void waitAwakeAgent() { final int BUFSIZE = 1; byte[] buf = new byte[BUFSIZE]; InetAddress cAddr; // ??IP int cPort; // ??? DatagramSocket sock = null; boolean flag = true; int port = 24005; int awakeDelay = 1000; try { String awakeDelayStr = AgentProperties.getProperty("awake.delay", Integer.toString(1000)); awakeDelay = Integer.parseInt(awakeDelayStr); m_log.info("awake.delay = " + awakeDelay + " msec"); } catch (NumberFormatException e) { m_log.error("awake.delay", e); } while (true) { /* * UDP???flag?true?? * ?????flag?false?????getTopic(releaseLatch)? * * UDP???????getTopic???????? * ?????? */ try { if (sock != null && port != awakePort) { sock.close(); sock = null; } if (sock == null || !sock.isBound()) { port = awakePort; sock = new DatagramSocket(port); sock.setSoTimeout(awakeDelay); } DatagramPacket recvPacket = new DatagramPacket(buf, BUFSIZE); sock.receive(recvPacket); cAddr = recvPacket.getAddress(); cPort = recvPacket.getPort(); flag = true; m_log.info("waitAwakeAgent (" + cAddr.getHostAddress() + " onPort=" + cPort + ") buf.length=" + buf.length); } catch (SocketTimeoutException e) { if (flag) { m_log.info("waitAwakeAgent packet end"); m_receiveTopic.releaseLatch(); flag = false; } } catch (Exception e) { String msg = "waitAwakeAgent port=" + awakePort + ", " + e.getClass().getSimpleName() + ", " + e.getMessage(); if (e instanceof BindException) { m_log.warn(msg); } else { m_log.warn(msg, e); } try { Thread.sleep(60 * 1000); } catch (InterruptedException e1) { m_log.warn(e1, e1); } } } }
From source file:org.starnub.starnubserver.servers.starbound.UDPProxyServer.java
public void run() { InetAddress IPAddress;//from w w w . j a va 2 s . c o m DatagramSocket ds; try { ds = new DatagramSocket(starnubPort); IPAddress = InetAddress.getByName(starboundAddress); } catch (SocketException | UnknownHostException e1) { StarNub.getLogger().cFatPrint("StarNub", ExceptionUtils.getMessage(e1)); e1.printStackTrace(); return; } byte[] request = new byte[1024]; byte[] reply = new byte[4096]; while (!stopping) { try { DatagramPacket from_client = new DatagramPacket(request, request.length); ds.receive(from_client); byte[] real_request = new byte[from_client.getLength()]; System.arraycopy(request, 0, real_request, 0, from_client.getLength()); DatagramPacket sendPacket = new DatagramPacket(real_request, real_request.length, IPAddress, starboundPort); ds.send(sendPacket); DatagramPacket from_server = new DatagramPacket(reply, reply.length); ds.receive(from_server); byte[] real_reply = new byte[from_server.getLength()]; System.arraycopy(reply, 0, real_reply, 0, from_server.getLength()); InetAddress address = from_client.getAddress(); int port = from_client.getPort(); DatagramPacket to_client = new DatagramPacket(real_reply, real_reply.length, address, port); ds.send(to_client); } catch (Exception e) { StarNub.getLogger().cFatPrint("StarNub", ExceptionUtils.getMessage(e)); return; } } }
From source file:it.anyplace.sync.discovery.protocol.ld.LocalDiscorveryHandler.java
public void startListener() { listeningExecutorService.submit(new Runnable() { private final int incomingBufferSize = 1024; //TODO check this @Override//from w ww . ja v a 2 s . c om public void run() { try { if (datagramSocket == null || datagramSocket.isClosed()) { datagramSocket = new DatagramSocket(UDP_PORT, InetAddress.getByName("0.0.0.0")); logger.info("opening upd socket {}", datagramSocket.getLocalSocketAddress()); } final DatagramPacket datagramPacket = new DatagramPacket(new byte[incomingBufferSize], incomingBufferSize); logger.trace("waiting for message on socket addr = {}", datagramSocket.getLocalSocketAddress()); isListening = true; datagramSocket.receive(datagramPacket); processingExecutorService.submit(new Runnable() { @Override public void run() { try { final String sourceAddress = datagramPacket.getAddress().getHostAddress(); ByteBuffer byteBuffer = ByteBuffer.wrap(datagramPacket.getData(), datagramPacket.getOffset(), datagramPacket.getLength()); int magic = byteBuffer.getInt(); //4 bytes checkArgument(magic == MAGIC, "magic mismatch, expected %s, got %s", MAGIC, magic); final LocalDiscoveryProtos.Announce announce = LocalDiscoveryProtos.Announce .parseFrom(ByteString.copyFrom(byteBuffer)); final String deviceId = hashDataToDeviceIdString(announce.getId().toByteArray()); if (!equal(deviceId, configuration.getDeviceId())) { // logger.debug("received local announce from device id = {}", deviceId); final List<DeviceAddress> deviceAddresses = Lists .newArrayList(Iterables.transform( firstNonNull(announce.getAddressesList(), Collections.<String>emptyList()), new Function<String, DeviceAddress>() { @Override public DeviceAddress apply(String address) { // /* // When interpreting addresses with an unspecified address, e.g., tcp://0.0.0.0:22000 or tcp://:42424, the source address of the discovery announcement is to be used. // */ return DeviceAddress.newBuilder() .setAddress(address.replaceFirst( "tcp://(0.0.0.0|):", "tcp://" + sourceAddress + ":")) .setDeviceId(deviceId) .setInstanceId(announce.getInstanceId()) .setProducer( DeviceAddress.AddressProducer.LOCAL_DISCOVERY) .build(); } })); boolean isNew = false; synchronized (localDiscoveryRecords) { isNew = !localDiscoveryRecords.removeAll(deviceId).isEmpty(); localDiscoveryRecords.putAll(deviceId, deviceAddresses); } eventBus.post(new MessageReceivedEvent() { @Override public List<DeviceAddress> getDeviceAddresses() { return Collections.unmodifiableList(deviceAddresses); } @Override public String getDeviceId() { return deviceId; } }); if (isNew) { eventBus.post(new NewLocalPeerEvent() { @Override public String getDeviceId() { return deviceId; } }); } } } catch (Exception ex) { logger.warn("error processing datagram", ex); } } }); listeningExecutorService.submit(this); } catch (Exception ex) { isListening = false; if (listeningExecutorService.isShutdown()) { return; } if (datagramSocket != null) { logger.warn("error receiving datagram", ex); listeningExecutorService.submit(this); } else if (ex instanceof java.net.BindException) { logger.warn("error opening udp server socket : {}", ex.toString()); } else { logger.warn("error opening udp server socket", ex); } } } }); }
From source file:Reflector.java
public void packetReceived(DatagramPacket packet) { // An incoming packet has been received. Override // the old packet addressing to the new outgoing // addressing, send it and log it. try {/* w ww . j a v a 2 s .c om*/ packet.setAddress(sendAddr); packet.setPort(sendPort); ds.send(packet); logger.log("Packet forwarded to " + packet.getAddress().getHostAddress() + "/" + packet.getPort() + ", " + packet.getLength() + " bytes"); } catch (IOException e) { System.err.println("Error sending packet"); e.printStackTrace(); } }
From source file:org.lockss.test.LockssTestCase.java
/** * Asserts that the two DatagramPackets have equal contents * @param expected the expected value//from w ww . j ava 2 s. com * @param actual the actual value */ public static void assertEquals(DatagramPacket expected, DatagramPacket actual) { assertEquals(expected.getAddress(), actual.getAddress()); assertEquals(expected.getPort(), actual.getPort()); assertEquals(expected.getLength(), actual.getLength()); assertEquals(expected.getOffset(), actual.getOffset()); assertTrue(Arrays.equals(expected.getData(), actual.getData())); }