List of usage examples for java.net DatagramPacket getLength
public synchronized int getLength()
From source file:net.jradius.packet.PacketFactory.java
/** * Parse a UDP RADIUS message/*from w w w. j a v a 2s . com*/ * @param dp The Datagram to be parsed * @return Returns the RadiusPacket * @throws RadiusException */ public static RadiusPacket parse(DatagramPacket dp, boolean pool) throws RadiusException { ByteBuffer buffer = ByteBuffer.wrap(dp.getData(), dp.getOffset(), dp.getLength()); RadiusPacket rp = null; try { rp = parseUDP(buffer, pool); } catch (IOException e) { RadiusLog.error(e.getMessage(), e); } return rp; }
From source file:net.anidb.udp.UdpResponse.java
/** * Returns a instance of the class.//from w w w . j a v a 2 s . c om * @param packet The datagram packet. * @param charset The charset. * @return The instance. * @throws IllegalArgumentException If the datagram packet is * <code>null</code>. * @throws UdpConnectionException If the structure of datagram packet isn't * valid. * @throws UnsupportedEncodingException If the given charset isn't * supported. */ protected static UdpResponse getInstance(final DatagramPacket packet, final Charset charset) throws UdpConnectionException, UnsupportedEncodingException { ByteBuffer byteBuffer; String data, returnCodeStr, returnString; int returnCode; UdpResponse response; int index; String[] entries, dataFields; UdpResponseEntry entry; if (packet == null) { throw new IllegalArgumentException("Argument packet is null."); } if (packet.getLength() < 5) { throw new UdpConnectionException( "The packet length is less than " + "the minimum of 5 bytes: " + packet.getLength()); } byteBuffer = ByteBuffer.allocate(packet.getLength()); byteBuffer = (ByteBuffer) byteBuffer.put(packet.getData(), 0, packet.getLength()).flip(); data = charset.decode(byteBuffer).toString(); LOG.debug("received = [" + data + ']'); if (data.length() < 5) { throw new UdpConnectionException( "The string length is less than " + "the minimum of 5 characters: " + data); } // First 3 chars = return code returnCodeStr = data.substring(0, 3); data = data.substring(4); try { returnCode = Integer.parseInt(returnCodeStr); } catch (NumberFormatException nfe) { throw new UdpConnectionException("Couldn't parse return code: " + returnCodeStr, nfe); } // Return string. index = data.indexOf('\n'); if (index < 0) { returnString = data; data = ""; } else { returnString = data.substring(0, index); data = data.substring(index + 1); } response = new UdpResponse(returnCode, returnString); // Entries? if (data.length() > 0) { entries = data.split("\\n", -1); for (int eIndex = 0; eIndex < entries.length; eIndex++) { if ((entries[eIndex].length() == 0) && (eIndex == entries.length - 1)) { break; } entry = new UdpResponseEntry(); dataFields = entries[eIndex].split("\\|", -1); for (int dfIndex = 0; dfIndex < dataFields.length; dfIndex++) { entry.addDataField(new DataField(dataFields[dfIndex], charset)); } response.entries.addElement(entry); } // MTU size problem. // TODO Implement a better solution for the MTU problem. if ((response.entries.size() > 0) && (packet.getLength() == 1400)) { /* * I assume if the packet length is equal to the MTU size, the * last entry is cut and must be removed. */ index = response.entries.size() - 1; // entry = response.entries.elementAt(index); // data = entry.getMessageString(); // LOG.debug("last line = [" + data + ']'); response.entries.removeElementAt(index); } } return response; }
From source file:gravity.android.discovery.DiscoveryClient.java
public static ArrayList<DiscoveryServerInfo> findServer(WifiManager mWifi, int port, String token) { ArrayList<DiscoveryServerInfo> ret = new ArrayList<DiscoveryServerInfo>(); try {/*from w ww . j a v a2 s . c om*/ DatagramSocket clientSocket = new DatagramSocket(); clientSocket.setBroadcast(true); InetAddress IPAddress = Utils.getBroadcastAddress(mWifi); Log.v("DISCOVERY_CLIENT", "broadcast addr " + IPAddress.getHostAddress()); byte[] receiveData = new byte[2048]; byte[] sendData = new byte[128]; sendData = token.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); Log.v("DISCOVERY_CLIENT", "sent " + token); clientSocket.send(sendPacket); long t1 = System.currentTimeMillis(); while (System.currentTimeMillis() - t1 <= 4000) // 4 secondi { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); try { clientSocket.setSoTimeout(500); clientSocket.receive(receivePacket); if (receivePacket.getAddress() != null && receivePacket.getAddress().getHostAddress() != null) { String discovered_name, discovered_ip; int discovered_port; String received = new String(receivePacket.getData()); if (received != null) { received = received.trim().substring(0, receivePacket.getLength()).trim(); Log.d("Recieved Msg Packet:", received); //StringTokenizer st = new StringTokenizer(received, ","); //Gravity Code JSONObject recievedJson = new JSONObject(received); try { //discovered_name = st.nextToken(); discovered_name = recievedJson.getString("name"); //Gravity code discovered_ip = receivePacket.getAddress().getHostAddress(); //discovered_port = Integer.parseInt(st.nextToken()); discovered_port = recievedJson.getInt("port_to_share"); //Gravity code Log.v("DISCOVERY_CLIENT", "discovered " + discovered_name + ", " + discovered_ip + ":" + discovered_port); boolean add = true; if (ret.size() > 0) { for (DiscoveryServerInfo dsi : ret) { if (dsi != null && dsi.ip.equals(discovered_ip)) { add = false; break; } } } if (add) { ret.add(new DiscoveryServerInfo(discovered_name, discovered_ip, discovered_port)); } } catch (NoSuchElementException nsee) { Log.v("DISCOVERY_CLIENT", nsee.getLocalizedMessage()); } } } } catch (SocketTimeoutException tex) { /* ignored */ } } clientSocket.close(); } catch (Exception ex) { ex.printStackTrace(); Log.e("DISCOVERY_CLIENT", ex.toString()); } return ret; }
From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java
/** * Extracts an IPC port from the given datagram packet. The datagram packet must be of the type * <code>JM_LOOKUP_REPLY_PACKET_ID</code>. * // w w w .ja v a 2 s . c o m * @param packet * the packet to extract the IPC port from. * @return the extracted IPC port or <code>-1</code> if the port could not be extracted */ private static int extractIpcPort(DatagramPacket packet) { final byte[] data = packet.getData(); if (data == null) { return -1; } if (packet.getLength() < (PAYLOAD_OFFSET + 4)) { return -1; } return byteArrayToInteger(data, PAYLOAD_OFFSET); }
From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java
/** * Extracts the packet type ID from the given datagram packet. * /*from w w w.java 2s . c o m*/ * @param packet * the packet to extract the type ID from * @return the extracted packet type ID or <code>-1</code> if the ID could not be extracted */ private static int getPacketTypeID(final DatagramPacket packet) { final byte[] data = packet.getData(); if (data == null) { return -1; } if (packet.getLength() < (PACKET_TYPE_ID_OFFSET + 4)) { return -1; } return byteArrayToInteger(data, PACKET_TYPE_ID_OFFSET); }
From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java
/** * Extracts an {@link InetAddress} object from the given datagram packet. The datagram packet must be of the type * <code>TM_ADDRESS_REPLY_PACKET_ID</code>. * //w w w . ja v a2s. c om * @param packet * the packet to extract the address from * @return the extracted address or <code>null</code> if it could not be extracted */ private static InetAddress extractInetAddress(DatagramPacket packet) { final byte[] data = packet.getData(); if (data == null) { return null; } if (packet.getLength() < PAYLOAD_OFFSET + 8) { return null; } final int len = byteArrayToInteger(data, PAYLOAD_OFFSET); final byte[] addr = new byte[len]; System.arraycopy(data, PAYLOAD_OFFSET + 4, addr, 0, len); InetAddress inetAddress = null; try { inetAddress = InetAddress.getByAddress(addr); } catch (UnknownHostException e) { return null; } return inetAddress; }
From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java
/** * Extracts the datagram packet's magic number and checks it matches with the local magic number. * //from www . j a v a 2s .c o m * @param packet * the packet to check * @param magicNumber * the magic number identifying the discovery service * @return <code>true</code> if the packet carries the magic number expected by the local service, otherwise * <code>false</code> */ private static boolean isPacketForUs(final DatagramPacket packet, final int magicNumber) { final byte[] data = packet.getData(); if (data == null) { return false; } if (packet.getLength() < (MAGIC_NUMBER_OFFSET + 4)) { return false; } if (byteArrayToInteger(data, MAGIC_NUMBER_OFFSET) != magicNumber) { return false; } return true; }
From source file:com.navercorp.pinpoint.collector.receiver.thrift.udp.UDPReceiverTest.java
void interceptValidatePacket(DatagramPacket packet) { if (packet.getLength() == 0) { zeroPacketCounter.incrementAndGet(); } }
From source file:MainClass.java
public void run() { byte[] buffer = new byte[65507]; while (true) { if (stopped) return; DatagramPacket dp = new DatagramPacket(buffer, buffer.length); try {// w w w. j a v a2 s . co m socket.receive(dp); String s = new String(dp.getData(), 0, dp.getLength()); System.out.println(s); Thread.yield(); } catch (IOException ex) { System.err.println(ex); } } }
From source file:werewolf_client.Werewolf_Client.java
public void recvFromClient(String adr, int p) throws SocketException, IOException { DatagramSocket recv = new DatagramSocket(p); byte[] recvData = new byte[1024]; while (true) { DatagramPacket recvPacket = new DatagramPacket(recvData, recvData.length); recv.receive(recvPacket);//from w w w . j av a 2 s.c o m String s = new String(recvPacket.getData(), 0, recvPacket.getLength()); System.out.println("ReceivedD\n" + s); } }