List of usage examples for java.net DatagramPacket DatagramPacket
public DatagramPacket(byte buf[], int length, InetAddress address, int port)
From source file:org.opennms.netmgt.syslogd.SyslogdEventdLoadTest.java
@Test @Transactional/*from w ww . ja va2 s . c om*/ public void testNGSyslog() throws Exception { loadSyslogConfiguration("/etc/syslogd-syslogng-configuration.xml"); startSyslogdGracefully(); m_eventCounter.anticipate(); InetAddress address = InetAddress.getLocalHost(); // handle an invalid packet byte[] bytes = "<34>main: 2010-08-19 localhost foo0: load test 0 on tty1\0".getBytes(); DatagramPacket pkt = new DatagramPacket(bytes, bytes.length, address, SyslogClient.PORT); WaterfallExecutor.waterfall(m_executorServices, new SyslogConnection(pkt, MATCH_PATTERN, HOST_GROUP, MESSAGE_GROUP, UEI_LIST, HIDE_MESSAGE, DISCARD_UEI)); // handle a valid packet bytes = "<34>monkeysatemybrain!\0".getBytes(); pkt = new DatagramPacket(bytes, bytes.length, address, SyslogClient.PORT); WaterfallExecutor.waterfall(m_executorServices, new SyslogConnection(pkt, MATCH_PATTERN, HOST_GROUP, MESSAGE_GROUP, UEI_LIST, HIDE_MESSAGE, DISCARD_UEI)); m_eventCounter.waitForFinish(120000); assertEquals(1, m_eventCounter.getCount()); }
From source file:org.avineas.fins.gw.Gateway.java
/** * Method called by the NodeUnit functionality to actually transmit a FINS frame * to the correct node.//from w w w . j a v a2 s .c o m * * @param packet The FINS packet to transmit * @throws IOException In case of sending failures */ void send(Frame packet) throws IOException { // Try to find the destination, either local or remote NodeUnit unit = units.get(packet.getDestination().toString()); // Is it a local node? if (unit != null) { // Handle the frame locally. This means that we call // handleFrame and if this one gives a reply, let that reply handle // by the initiator Frame response = unit.handleFrame(packet); if (response != null) { unit = units.get(packet.getSource().toString()); unit.handleFrame(response); } return; } // It must be a remote node. Check where it must be sent to String node = packet.getDestination().getNodeAsString(); Destination dest = getDestination(node); if (dest == null) { logger.warn("don't have an IP destination for node: " + node + ", dropping packet"); return; } // OK, got everything correct. Send it to a remote IP/FINS node byte[] data = packet.getBytes(); DatagramPacket dpacket = new DatagramPacket(data, data.length, dest.getAddress(), dest.getPort()); traceDatagram(channel.getLocalPort() + " -> " + dest, dpacket); channel.send(dpacket); logger.info("sent " + (packet.isReply() ? "reply" : "packet") + " frame to destination: " + dest + ", from unit: " + packet.getSource() + " to unit: " + packet.getDestination()); }
From source file:com.vivareal.logger.appender.UDPAppender.java
public void append(LoggingEvent event) { if (event == null) { return;/* w w w . j a va 2 s. c o m*/ } if (address == null) { errorHandler.error("No remote host is set for UDPAppender named \"" + this.name + "\"."); return; } if (outSocket != null) { // if the values already exist, don't set (useful when forwarding // from a simplesocketserver if ((overrideProperties != null) && overrideProperties.equalsIgnoreCase("true")) { event.setProperty("log4jmachinename", localMachine); if (application != null) { event.setProperty("log4japp", application); } } try { TimeZone tz = TimeZone.getTimeZone("UTC"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); df.setTimeZone(tz); String timestamp = df.format(new Date(event.getTimeStamp())); LogstashEvent logstashEvent = new LogstashEvent(); logstashEvent.setApplication(application); logstashEvent.setLoggerName(event.getLoggerName()); logstashEvent.setNdc(event.getNDC()); logstashEvent.setPath(event.getLoggerName()); logstashEvent.setPriority(event.getLevel().toString()); logstashEvent.setThread(event.getThreadName()); logstashEvent.setTimestamp(timestamp); logstashEvent.setEnvironment(environment); if (event.getLocationInformation() != null) { logstashEvent.setClassName(event.getLocationInformation().getClassName()); logstashEvent.setFile(event.getLocationInformation().getFileName()); logstashEvent.setMethod(event.getLocationInformation().getMethodName()); } String message = event.getRenderedMessage().trim(); logstashEvent.setMessage(message); if (message.length() > MAX_MESSAGE_SIZE) { StringBuilder sb = new StringBuilder(); String truncatedMessage = message.substring(0, MAX_MESSAGE_SIZE - 3); sb.append(truncatedMessage); sb.append("..."); logstashEvent.setMessage(sb.toString()); } if (event.getThrowableInformation() != null) { String stackTrace = StringUtils.join(event.getThrowableStrRep(), "\n"); logstashEvent.setStackTrace(stackTrace); if (stackTrace.length() > MAX_STACK_TRACE_SIZE) { StringBuilder sb = new StringBuilder(); String truncatedStackTrace = stackTrace.substring(0, MAX_STACK_TRACE_SIZE - 3); sb.append(truncatedStackTrace); sb.append("..."); logstashEvent.setStackTrace(sb.toString()); } } ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(logstashEvent); StringBuffer buf = new StringBuffer(json); DatagramPacket dp = new DatagramPacket(buf.toString().getBytes("ASCII"), buf.length(), address, port); outSocket.send(dp); } catch (IOException e) { outSocket = null; LogLog.warn("Detected problem with UDP connection: " + e); if (reconnectionDelay > 0) { fireConnector(); } } } }
From source file:UDPOutputStream.java
/*********** writing to and flushing the buffer ************/ /*// ww w .j a v a2 s .c o m ***************************************************************** *** *** *** Name : flush *** *** By : U. Bergstrom (Creare Inc., Hanover, NH) *** *** For : E-Scan *** *** Date : October, 2001 *** *** *** *** Copyright 2001 Creare Inc. *** *** All Rights Reserved *** *** *** *** Description : *** *** Flush current buffer contents to UDP socket. *** *** *** ***************************************************************** */ public void flush() throws IOException { if (idx == 0) { // no data in buffer return; } // copy what we have in the buffer so far into a new array; // if buffer is full, use it directly. if (idx == buffer.length) { outdata = buffer; } else { outdata = new byte[idx]; System.arraycopy(buffer, 0, outdata, 0, idx); } // send data dpack = new DatagramPacket(outdata, idx, iAdd, port); dsock.send(dpack); // reset buffer index idx = 0; }
From source file:org.apache.slide.webdav.event.NotificationTrigger.java
protected void notifySubscriber(String callback, String subscribers) { if (callback.startsWith(TCP_PROTOCOL)) { Domain.log("Notify subscribers with adress='" + callback + "' via TCP with id's " + subscribers, LOG_CHANNEL, Logger.INFO); NotifyMethod notifyMethod = new NotifyMethod(callback.toString()); notifyMethod.addRequestHeader(H_SUBSCRIPTION_ID_RESPONSE, subscribers); try {/*from w w w.j ava 2s. c o m*/ URL url = new URL(callback); notifyMethod.execute(new HttpState(), new HttpConnection(url.getHost(), url.getPort() != -1 ? url.getPort() : 80)); } catch (IOException e) { Domain.log("Notification of subscriber '" + callback.toString() + "' failed!"); } } else if (callback.startsWith(UDP_PROTOCOL) && socket != null) { Domain.log("Notify subscribers with adress='" + callback + "' via UDP with id's " + subscribers + "\n", LOG_CHANNEL, Logger.INFO); try { URL url = new URL(TCP_PROTOCOL + callback.substring(UDP_PROTOCOL.length())); String notification = "NOTIFY " + callback + " HTTP/1.1\nSubscription-id: " + subscribers; byte[] buf = notification.getBytes(); InetAddress address = InetAddress.getByName(url.getHost()); DatagramPacket packet = new DatagramPacket(buf, buf.length, address, url.getPort() != -1 ? url.getPort() : 80); socket.send(packet); } catch (IOException e) { Domain.log("Notification of subscriber '" + callback.toString() + "' failed!", LOG_CHANNEL, Logger.ERROR); } } }
From source file:org.jini.commands.multicast.MulticastSender.java
private void startMulticastSender() throws NoSuchAlgorithmException { byte[] outBuf; // Interval in MiliSeconds final int INTERVAL = this.getInterval(); // Port /*from w w w . j a v a2 s. c om*/ final int PORT = this.getPort(); // Multicast Group String mcastGroup = this.getMulticastGroup(); String fl = this.getFile(); String fileName = this.getFile(); // Read Data from File String msg = this.getFileContents(fileName); // MD5 CheckSum String mdfiveSum = this.checkFileMD5(fileName); // Jini Logging JiniCommandsLogger jcl = new JiniCommandsLogger(); System.out.println("Started Multicast Sender. Sending Datagram every : " + INTERVAL + " Miliseconds"); if (logDatagramMessages == true) { System.out.println("Logging to Directory : " + jcl.getJiniLogDir()); } else { System.out.println("Logging not turned on, add -l to start logging. "); } System.out.println("'c + ENTER' or 'x + ENTER' to stop Multicast Sender."); PrintChar printChar = new PrintChar(); printChar.setOutPutChar(">"); try { Scanner in = new Scanner(System.in); printChar.start(); DatagramSocket socket = new DatagramSocket(); long counter = 0; while (this.running) { // Every 10th broadcast the file is checked if it has changed (MD5). // If it has the new data is read and broadcasted counter++; if (counter == 10) { if (mdfiveSum.equals(this.checkFileMD5(fileName)) == false) { msg = this.getFileContents(fileName); } counter = 0; } outBuf = msg.getBytes(); //Send to multicast IP address and port InetAddress address = InetAddress.getByName(mcastGroup); DatagramPacket outPacket = new DatagramPacket(outBuf, outBuf.length, address, PORT); socket.send(outPacket); if (logDatagramMessages == true) { jcl.writeLog(msg); } if ((in.nextLine().equalsIgnoreCase("c")) || (in.nextLine().equalsIgnoreCase("x"))) { this.running = false; } try { Thread.sleep(INTERVAL); } catch (InterruptedException ie) { printChar.setStopPrinting(true); this.setJcError(true); this.addErrorMessages("Error : An error occured in the Sleep thread."); } } } catch (IOException ioe) { printChar.setStopPrinting(true); /* DatagramPacket is just a wrapper on a UDP based socket, so the usual UDP rules apply. 64 kilobytes is the theoretical maximum size of a complete IP datagram, but only 576 bytes are guaranteed to be routed. On any given network path, the link with the smallest Maximum Transmit Unit will determine the actual limit. (1500 bytes, less headers is the common maximum, but it is impossible to predict how many headers there will be so its safest to limit messages to around 1400 bytes.) If you go over the MTU limit, IPv4 will automatically break the datagram up into fragments and reassemble them at the end, but only up to 64 kilobytes and only if all fragments make it through. If any fragment is lost, or if any device decides it doesn't like fragments, then the entire packet is lost. As noted above, it is impossible to know in advance what the MTU of path will be. There are various algorithms for experimenting to find out, but many devices do not properly implement (or deliberately ignore) the necessary standards so it all comes down to trial and error. Or you can just guess 1400 bytes per message. As for errors, if you try to send more bytes than the OS is configured to allow, you should get an EMSGSIZE error or its equivalent. If you send less than that but more than the network allows, the packet will just disappear. */ this.setJcError(true); this.addErrorMessages("Info : 64 kilobytes is the theoretical maximum size of a complete IP Datagram"); this.addErrorMessages("Error : " + ioe); } printChar.setStopPrinting(true); this.done = true; }
From source file:org.kde.kdeconnect.Backends.LanBackend.LanLinkProvider.java
@Override public void onStart() { //This handles the case when I'm the existing device in the network and receive a "hello" UDP package udpAcceptor.setHandler(udpHandler);//from w w w .j a va 2 s . com try { udpAcceptor.bind(new InetSocketAddress(port)); } catch (Exception e) { Log.e("LanLinkProvider", "Error: Could not bind udp socket"); e.printStackTrace(); } boolean success = false; int tcpPort = port; while (!success) { try { tcpAcceptor.bind(new InetSocketAddress(tcpPort)); success = true; } catch (Exception e) { tcpPort++; } } Log.i("LanLinkProvider", "Using tcpPort " + tcpPort); //I'm on a new network, let's be polite and introduce myself final int finalTcpPort = tcpPort; new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { String deviceListPrefs = PreferenceManager.getDefaultSharedPreferences(context) .getString(KEY_CUSTOM_DEVLIST_PREFERENCE, ""); ArrayList<String> iplist = new ArrayList<String>(); if (!deviceListPrefs.isEmpty()) { iplist = CustomDevicesActivity.deserializeIpList(deviceListPrefs); } iplist.add("255.255.255.255"); for (String ipstr : iplist) { try { InetAddress client = InetAddress.getByName(ipstr); NetworkPackage identity = NetworkPackage.createIdentityPackage(context); identity.set("tcpPort", finalTcpPort); byte[] b = identity.serialize().getBytes("UTF-8"); DatagramPacket packet = new DatagramPacket(b, b.length, client, port); DatagramSocket socket = new DatagramSocket(); socket.setReuseAddress(true); socket.setBroadcast(true); socket.send(packet); //Log.i("LanLinkProvider","Udp identity package sent to address "+packet.getAddress()); } catch (Exception e) { e.printStackTrace(); Log.e("LanLinkProvider", "Sending udp identity package failed. Invalid address? (" + ipstr + ")"); } } return null; } }.execute(); }
From source file:org.openhab.binding.network.internal.utils.NetworkUtils.java
/** * iOS devices are in a deep sleep mode, where they only listen to UDP traffic on port 5353 (Bonjour service * discovery). A packet on port 5353 will wake up the network stack to respond to ARP pings at least. * * @throws IOException/*from w w w.java 2 s. c o m*/ */ public void wakeUpIOS(InetAddress address) throws IOException { try (DatagramSocket s = new DatagramSocket()) { byte[] buffer = new byte[0]; s.send(new DatagramPacket(buffer, buffer.length, address, 5353)); } catch (PortUnreachableException ignored) { // We ignore the port unreachable error } }
From source file:com.clustercontrol.hinemosagent.util.AgentConnectUtil.java
/** * [Topic] getTopic?????UDP???/* w w w. ja v a2 s . c o m*/ * @param facilityId */ private static void awakeAgent(String facilityId) { String ipAddress = ""; Integer port = 24005; m_log.debug("awakeAgent facilityId=" + facilityId); try { NodeInfo info = NodeProperty.getProperty(facilityId); ipAddress = info.getAvailableIpAddress(); port = info.getAgentAwakePort(); } catch (FacilityNotFound e) { m_log.debug(e.getMessage(), e); return; } catch (Exception e) { m_log.warn("awakeAgent facilityId=" + facilityId + " " + e.getClass().getSimpleName() + ", " + e.getMessage(), e); return; } if (port < 1 || 65535 < port) { m_log.info("awakeAgent : invalid port " + port + "(" + facilityId + ")"); } m_log.debug("awakeAgent ipaddress=" + ipAddress); final int BUFSIZE = 1; byte[] buf = new byte[BUFSIZE]; buf[0] = 1; InetAddress sAddr; try { sAddr = InetAddress.getByName(ipAddress); } catch (UnknownHostException e) { m_log.warn("awakeAgent facilityId=" + facilityId + " " + e.getClass().getSimpleName() + ", " + e.getMessage(), e); return; } DatagramPacket sendPacket = new DatagramPacket(buf, BUFSIZE, sAddr, port); DatagramSocket soc = null; try { soc = new DatagramSocket(); soc.send(sendPacket); } catch (SocketException e) { m_log.warn("awakeAgent facilityId=" + facilityId + " " + e.getClass().getSimpleName() + ", " + e.getMessage(), e); } catch (IOException e) { m_log.warn("awakeAgent facilityId=" + facilityId + " " + e.getClass().getSimpleName() + ", " + e.getMessage(), e); } finally { if (soc != null) { soc.close(); } } }
From source file:org.opennms.netmgt.syslogd.SyslogdLoadIT.java
@Test @Transactional/* w w w. jav a2 s .c o m*/ public void testRfcSyslog() throws Exception { loadSyslogConfiguration("/etc/syslogd-rfc-configuration.xml"); startSyslogdJavaNet(); m_eventCounter.anticipate(); InetAddress address = InetAddress.getLocalHost(); // handle an invalid packet byte[] bytes = "<34>1 2010-08-19T22:14:15.000Z localhost - - - - BOMfoo0: load test 0 on tty1\0".getBytes(); DatagramPacket pkt = new DatagramPacket(bytes, bytes.length, address, SyslogClient.PORT); new SyslogConnectionHandlerDefaultImpl().handleSyslogConnection(new SyslogConnection(pkt, m_config)); // handle a valid packet bytes = "<34>1 2003-10-11T22:14:15.000Z plonk -ev/pts/8\0".getBytes(); pkt = new DatagramPacket(bytes, bytes.length, address, SyslogClient.PORT); new SyslogConnectionHandlerDefaultImpl().handleSyslogConnection(new SyslogConnection(pkt, m_config)); m_eventCounter.waitForFinish(120000); assertEquals(1, m_eventCounter.getCount()); }