List of usage examples for java.net DatagramPacket getPort
public synchronized int getPort()
From source file:org.openhab.io.hueemulation.internal.HueEmulationUpnpServer.java
@Override public void run() { MulticastSocket recvSocket = null; // since jupnp shares port 1900, lets use a different port to send UDP packets on just to be safe. DatagramSocket sendSocket = null; byte[] buf = new byte[1000]; DatagramPacket recv = new DatagramPacket(buf, buf.length); while (running) { try {//from w w w . j a v a 2 s . c o m if (discoveryIp != null && discoveryIp.trim().length() > 0) { address = InetAddress.getByName(discoveryIp); } else { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface ni = interfaces.nextElement(); Enumeration<InetAddress> addresses = ni.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress addr = addresses.nextElement(); if (addr instanceof Inet4Address && !addr.isLoopbackAddress()) { address = addr; break; } } } } InetSocketAddress socketAddr = new InetSocketAddress(MULTI_ADDR, UPNP_PORT_RECV); recvSocket = new MulticastSocket(UPNP_PORT_RECV); recvSocket.joinGroup(socketAddr, NetworkInterface.getByInetAddress(address)); sendSocket = new DatagramSocket(); while (running) { recvSocket.receive(recv); if (recv.getLength() > 0) { String data = new String(recv.getData()); logger.trace("Got SSDP Discovery packet from {}:{}", recv.getAddress().getHostAddress(), recv.getPort()); if (data.startsWith("M-SEARCH")) { String msg = String.format(discoString, "http://" + address.getHostAddress().toString() + ":" + System.getProperty("org.osgi.service.http.port") + discoPath, usn); DatagramPacket response = new DatagramPacket(msg.getBytes(), msg.length(), recv.getAddress(), recv.getPort()); try { logger.trace("Sending to {} : {}", recv.getAddress().getHostAddress(), msg); sendSocket.send(response); } catch (IOException e) { logger.error("Could not send UPNP response", e); } } } } } catch (SocketException e) { logger.error("Socket error with UPNP server", e); } catch (IOException e) { logger.error("IO Error with UPNP server", e); } finally { IOUtils.closeQuietly(recvSocket); IOUtils.closeQuietly(sendSocket); if (running) { try { Thread.sleep(3000); } catch (InterruptedException e) { } } } } }
From source file:net.sbbi.upnp.jmx.UPNPMBeanDevicesDiscoveryHandler.java
public void run() { InetAddress group = null;//www.jav a 2 s . c om try { group = InetAddress.getByName("239.255.255.250"); skt = new java.net.MulticastSocket(1900); skt.setInterface(bindAddress.getAddress()); skt.joinGroup(group); } catch (IOException ex) { log.error("Error during multicast socket creation, thread cannot start", ex); return; } isRunning = true; while (isRunning) { try { byte[] buffer = new byte[4096]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length, group, bindAddress.getPort()); skt.receive(packet); String received = new String(packet.getData(), 0, packet.getLength()); if (log.isDebugEnabled()) log.debug("Received message:\n" + received); HttpRequest req = new HttpRequest(received); if (req.getHttpCommand().equals("M-SEARCH")) { String man = req.getHTTPHeaderField("MAN"); if (man.equals("\"ssdp:discover\"")) { String searchTarget = req.getHTTPHeaderField("ST"); // TODO check ALL devices search target //if ( searchTarget.equals( Discovery.ALL_DEVICES ) ) { if (searchTarget.equals(Discovery.ROOT_DEVICES)) { java.net.MulticastSocket multi = new java.net.MulticastSocket(); multi.setInterface(bindAddress.getAddress()); for (Iterator i = handledDevices.iterator(); i.hasNext();) { UPNPMBeanDevice dv = (UPNPMBeanDevice) i.next(); List packets = getReplyMessages(dv, false, dv.getSSDPAliveDelay()); for (int z = 0; z < packets.size(); z++) { String pack = (String) packets.get(z); if (log.isDebugEnabled()) log.debug("Sending http reply message on " + packet.getAddress() + ":" + packet.getPort() + " multicast address:\n" + pack.toString()); byte[] pk = pack.getBytes(); multi.setTimeToLive(dv.getSSDPTTL()); multi.send(new DatagramPacket(pk, pk.length, packet.getAddress(), packet.getPort())); } } multi.close(); } else { // TODO check a specific search target } } } } catch (IOException ex) { if (isRunning) { log.error("Error during multicast socket IO operations", ex); } } } }
From source file:org.dragonet.net.inf.mcpe.NetworkHandler.java
private void processPacket(DatagramPacket packet) { try {/* w w w.j a v a2 s. c o m*/ PEBinaryReader reader = new PEBinaryReader(new ByteArrayInputStream(packet.getData())); int raknetPID = reader.readByte() & 0xFF; switch (raknetPID) { case RaknetConstants.ID_PING_OPEN_CONNECTIONS: ServerInfoPacket pkReply = new ServerInfoPacket(); pkReply.time = reader.readLong(); pkReply.serverID = serverID; pkReply.serverName = this.getManager().getServer().getServer().getName(); pkReply.encode(); this.udp.send(pkReply.getData(), packet.getSocketAddress()); break; case RaknetConstants.ID_OPEN_CONNECTION_REQUEST_1: reader.read(16); //MAGIC reader.readByte(); //RakNet Protocol short mtu = (short) ((packet.getLength() - 18) & 0xFFFF); ByteArrayOutputStream bos = new ByteArrayOutputStream(); PEBinaryWriter writer = new PEBinaryWriter(bos); writer.writeByte(RaknetConstants.ID_OPEN_CONNECTION_REPLY_1); writer.write(RaknetConstants.magic); writer.writeLong(NetworkHandler.serverID); writer.writeByte((byte) 0x00); writer.writeShort(mtu); this.udp.send(bos.toByteArray(), packet.getSocketAddress()); break; case RaknetConstants.ID_OPEN_CONNECTION_REQUEST_2: reader.read(16); reader.readByte(); reader.readInt(); reader.readShort(); short clientMTU = reader.readShort(); long clientID = reader.readLong(); ByteArrayOutputStream bos8 = new ByteArrayOutputStream(); PEBinaryWriter writer8 = new PEBinaryWriter(bos8); writer8.writeByte(RaknetConstants.ID_OPEN_CONNECTION_REPLY_2); writer8.write(RaknetConstants.magic); writer8.writeLong(NetworkHandler.serverID); writer8.writeAddress(packet.getAddress(), (short) packet.getPort()); writer8.writeShort(clientMTU); writer8.writeByte((byte) 0x00); this.send(bos8.toByteArray(), packet.getSocketAddress()); PENetworkClient session = new PENetworkClient(this, packet.getSocketAddress(), clientID, clientMTU); clients.put(packet.getSocketAddress().toString(), session); //this.server.getServer().getSessionRegistry().add(session); break; case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8A: case 0x8B: case 0x8C: case 0x8D: case 0x8E: case 0x8F: if (this.manager.getSessions().containsKey(getClientKey(packet.getSocketAddress()))) { RaknetDataPacket dataPacket = new RaknetDataPacket( ArrayUtils.subarray(packet.getData(), 1, packet.getLength())); dataPacket.decode(); clients.get(getClientKey(packet.getSocketAddress())).processDataPacket(dataPacket); } break; case 0xC0: if (this.manager.getSessions().containsKey(getClientKey(packet.getSocketAddress()))) { clients.get(getClientKey(packet.getSocketAddress())) .processACKPacket(ArrayUtils.subarray(packet.getData(), 1, packet.getData().length)); } break; case 0xA0: if (this.manager.getSessions().containsKey(getClientKey(packet.getSocketAddress()))) { clients.get(getClientKey(packet.getSocketAddress())) .processNACKPacket(ArrayUtils.subarray(packet.getData(), 1, packet.getData().length)); } break; } } catch (IOException e) { } }
From source file:udpserver.UDPui.java
private void tempReceiveUDP() { 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 ww .j a v a 2 s . c om // while (true) { // byte[] receiveData = new byte[1024]; // DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); // if (!new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength()).equals("")) { // int count = 1; 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 message = new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength()); // String word = serverSocket.getInetAddress().toString(); // Integer count = counting.get(word); // if (count == null) { // counting.put(word, 1); // } // else { // counting.put(word, count + 1); // } boolean looprun = true; String word = receivePacket.getAddress().getHostAddress(); System.out.println(word); // System.out.println(message); while (looprun) { if (message.contains("&")) { message = message.substring(message.indexOf("&") + 1); Integer count = counting.get(word); if (count == null) { counting.put(word, 2); } else { counting.put(word, count + 1); } // System.out.println(count + ":" + message); } else { looprun = false; } } if (message.equals("end")) { valuePane.setCaretPosition(valuePane.getDocument().getLength()); //send back to mobile InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); String capitalizedSentence = counting.get(word) + ""; sendData = capitalizedSentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); serverSocket.send(sendPacket); //end send back to mobile // count = 1; // break; counting.remove(word); } else if (available) { // 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); } } // } // } } }; backgroundProcess = new Thread(background); }
From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java
/** * Server side implementation of Discovery Service. *///from w w w .j a va 2 s .c o m @Override public void run() { final DatagramPacket requestPacket = new DatagramPacket(new byte[64], 64); final Map<Integer, Long> packetIDMap = new HashMap<Integer, Long>(); while (this.isRunning) { try { this.serverSocket.receive(requestPacket); if (!isPacketForUs(requestPacket, this.magicNumber)) { LOG.debug("Received request packet which is not destined to this Nephele setup"); continue; } final Integer packetID = Integer.valueOf(extractPacketID(requestPacket)); if (packetIDMap.containsKey(packetID)) { LOG.debug("Request with ID " + packetID.intValue() + " already answered, discarding..."); continue; } else { final long currentTime = System.currentTimeMillis(); // Remove old entries final Iterator<Map.Entry<Integer, Long>> it = packetIDMap.entrySet().iterator(); while (it.hasNext()) { final Map.Entry<Integer, Long> entry = it.next(); if ((entry.getValue().longValue() + 5000L) < currentTime) { it.remove(); } } packetIDMap.put(packetID, Long.valueOf(currentTime)); } final int packetTypeID = getPacketTypeID(requestPacket); if (packetTypeID == JM_LOOKUP_REQUEST_ID) { LOG.debug("Received job manager lookup request from " + requestPacket.getSocketAddress()); final DatagramPacket responsePacket = createJobManagerLookupReplyPacket(this.ipcPort, this.magicNumber); responsePacket.setAddress(requestPacket.getAddress()); responsePacket.setPort(requestPacket.getPort()); this.serverSocket.send(responsePacket); } else if (packetTypeID == TM_ADDRESS_REQUEST_ID) { LOG.debug("Received task manager address request from " + requestPacket.getSocketAddress()); final DatagramPacket responsePacket = createTaskManagerAddressReplyPacket( requestPacket.getAddress(), this.magicNumber); responsePacket.setAddress(requestPacket.getAddress()); responsePacket.setPort(requestPacket.getPort()); this.serverSocket.send(responsePacket); } else { LOG.debug("Received packet of unknown type " + packetTypeID + ", discarding..."); } } catch (SocketTimeoutException ste) { LOG.debug("Discovery service: socket timeout"); } catch (IOException ioe) { if (this.isRunning) { // Ignore exception when service has been stopped LOG.error("Discovery service stopped working with IOException:\n" + ioe.toString()); } break; } } // Close the socket finally this.serverSocket.close(); }
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); }//w w w . j a va 2s .c o m // 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); }
From source file:ru.novoscan.trkpd.snmp.spring.TrackSpringSnmpAgent.java
public void run() { try {// w w w . j a v a 2s . c o m logger.debug("Binding to UDP port " + listeningPort); socket = new DatagramSocket(listeningPort); } catch (SocketException e) { // Fix: Flag to control lock socket within application isSocketException = true; throw new SnmpSystemException("Can not create SNMP agent UDP socket. Reason: " + e.getMessage()); } // Fix: Flag to control lock socket within application isSocketCreated = true; while (!workerThread.isInterrupted()) { byte requestPacketBuffer[] = new byte[PACKET_MAX_SIZE]; final DatagramPacket requestPacket = new DatagramPacket(requestPacketBuffer, requestPacketBuffer.length); try { socket.receive(requestPacket); } catch (IOException e) { logger.error("Error processing SNMP request. Reason: " + e.getMessage()); continue; } final byte data[] = requestPacket.getData(); Thread procThread = new Thread(new Runnable() { public void run() { try { Message requestMsg; Message responseMsg; PDU requestPDU; // Fix: Added missed ')' character logger.debug("Received packet (length=" + data.length + " bytes)"); BerTlv tlv = new BerTlv(); tlv.decode(new ByteArrayInputStream(data)); requestMsg = new Message(tlv); responseMsg = null; requestPDU = (PDU) requestMsg.getPDU(); String requestedOID = requestPDU.getVarBindList().getVarBind(0).getObjectName() .stringValue(); if (!hasHandledPrefix(requestedOID)) { logger.info("No entry found for oid " + requestedOID); GetResponsePDU responsePDU = new GetResponsePDU(requestPDU.getRequestId(), 2, 0L, requestPDU.getVarBindList()); responseMsg = new Message(0, requestMsg.getComunity(), responsePDU); return; } if (!validateCommunity(requestMsg)) { logger.warn( "Community [" + requestMsg.getComunity() + "] doesn't match for snmp request"); return; } GetResponsePDU responsePDU = null; if (requestPDU instanceof GetRequestPDU) responsePDU = handleGetRequest((GetRequestPDU) requestPDU); else if (requestPDU instanceof GetNextRequestPDU) responsePDU = handleGetNextRequest((GetNextRequestPDU) requestPDU); else if (requestPDU instanceof SetRequestPDU) responsePDU = handleSetRequest((SetRequestPDU) requestPDU); else responsePDU = createErrorResponse(requestPDU.getRequestId(), 5, 0, requestPDU.getVarBindList()); responseMsg = new Message(0, requestMsg.getComunity(), responsePDU); logger.info("Sending response to client\n" + responseMsg.toString()); byte responsePacketBuffer[] = responseMsg.toBerTlv().getBytes(); if (responsePacketBuffer.length > PACKET_MAX_SIZE) { responsePDU = new GetResponsePDU(requestPDU.getRequestId(), 1, 0L, requestPDU.getVarBindList()); responseMsg = new Message(SNMP_VERSION, requestMsg.getComunity(), responsePDU); responsePacketBuffer = responseMsg.toBerTlv().getBytes(); } DatagramPacket responsePacket = new DatagramPacket(responsePacketBuffer, responsePacketBuffer.length, requestPacket.getAddress(), requestPacket.getPort()); socket.send(responsePacket); } catch (Exception e) { logger.error("Error processing SNMP request. Reason: " + e.getMessage()); } } }); procThread.start(); } }