List of usage examples for java.net DatagramPacket getSocketAddress
public synchronized SocketAddress getSocketAddress()
From source file:PacketReceiver.java
public static void main(String[] args) throws Exception { byte[] buffer = new byte[1024]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); DatagramSocket socket = new DatagramSocket(5002); socket.receive(packet);//from w w w . ja v a 2 s . c o m System.out.println(packet.getSocketAddress()); buffer = packet.getData(); System.out.println(new String(buffer)); }
From source file:Main.java
public static void main(String[] args) { try {// w w w . j av a 2 s .c om byte[] buffer = new byte[1024]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); DatagramSocket socket = new DatagramSocket(5002); System.out.println("Waiting for a packet..."); socket.receive(packet); System.out.println("Just received packet from " + packet.getSocketAddress()); buffer = packet.getData(); System.out.println(new String(buffer)); } catch (IOException e) { e.printStackTrace(); } }
From source file:Main.java
public static void main(String args[]) { try {// w ww.j a v a2 s .c om int port = 80; DatagramSocket ds = new DatagramSocket(port); byte buffer[] = new byte[BUFSIZE]; while (true) { DatagramPacket dp = new DatagramPacket(buffer, buffer.length); // Receive data ds.receive(dp); // Display address from the datagram packet InetAddress ia = dp.getAddress(); System.out.println(ia); System.out.println(dp.getSocketAddress()); } } catch (Exception e) { e.printStackTrace(); } }
From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java
/** * Returns the network address with which the task manager shall announce itself to the job manager. To determine * the address this method exchanges packets with the job manager. * /*from w ww . jav a2s . co m*/ * @param jobManagerAddress * the address of the job manager * @return the address with which the task manager shall announce itself to the job manager * @throws DiscoveryException * thrown if an error occurs during the packet exchange */ public static InetAddress getTaskManagerAddress(final InetAddress jobManagerAddress) throws DiscoveryException { final int magicNumber = GlobalConfiguration.getInteger(MAGICNUMBER_KEY, DEFAULT_MAGICNUMBER); final int discoveryPort = GlobalConfiguration.getInteger(DISCOVERYPORT_KEY, DEFAULT_DISCOVERYPORT); InetAddress taskManagerAddress = null; DatagramSocket socket = null; try { socket = new DatagramSocket(); LOG.debug("Setting socket timeout to " + CLIENTSOCKETTIMEOUT); socket.setSoTimeout(CLIENTSOCKETTIMEOUT); final DatagramPacket responsePacket = new DatagramPacket(new byte[RESPONSE_PACKET_SIZE], RESPONSE_PACKET_SIZE); for (int retries = 0; retries < DISCOVERFAILURERETRIES; retries++) { final DatagramPacket addressRequest = createTaskManagerAddressRequestPacket(magicNumber); addressRequest.setAddress(jobManagerAddress); addressRequest.setPort(discoveryPort); LOG.debug("Sending Task Manager address request to " + addressRequest.getSocketAddress()); socket.send(addressRequest); try { socket.receive(responsePacket); } catch (SocketTimeoutException ste) { LOG.warn("Timeout wainting for task manager address reply. Retrying..."); continue; } if (!isPacketForUs(responsePacket, magicNumber)) { LOG.warn("Received packet which is not destined to this Nephele setup"); continue; } final int packetTypeID = getPacketTypeID(responsePacket); if (packetTypeID != TM_ADDRESS_REPLY_ID) { LOG.warn("Received response of unknown type " + packetTypeID + ", discarding..."); continue; } taskManagerAddress = extractInetAddress(responsePacket); break; } } catch (IOException ioe) { throw new DiscoveryException(StringUtils.stringifyException(ioe)); } finally { if (socket != null) { socket.close(); } } if (taskManagerAddress == null) { throw new DiscoveryException("Unable to obtain task manager address"); } return taskManagerAddress; }
From source file:ch.aschaefer.udp.DatagramSocketToControlMessageConverter.java
@Override public ControlMessage convert(DatagramPacket source) { return new ControlMessage().timestamp(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(LocalDateTime.now())) .hex(toHex(source.getData())).source(source.getSocketAddress().toString()) .targetHost(source.getAddress().getHostAddress()).targetPort(source.getPort()); }
From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java
/** * Attempts to retrieve the job managers address in the network through an * IP broadcast. This method should be called by the task manager. * //from w ww. ja v a2s . c o m * @return the socket address of the job manager in the network * @throws DiscoveryException * thrown if the job manager's socket address could not be * discovered */ public static InetSocketAddress getJobManagerAddress() throws DiscoveryException { final int magicNumber = GlobalConfiguration.getInteger(MAGICNUMBER_KEY, DEFAULT_MAGICNUMBER); final int discoveryPort = GlobalConfiguration.getInteger(DISCOVERYPORT_KEY, DEFAULT_DISCOVERYPORT); InetSocketAddress jobManagerAddress = null; DatagramSocket socket = null; try { final Set<InetAddress> targetAddresses = getBroadcastAddresses(); if (targetAddresses.isEmpty()) { throw new DiscoveryException("Could not find any broadcast addresses available to this host"); } socket = new DatagramSocket(); LOG.debug("Setting socket timeout to " + CLIENTSOCKETTIMEOUT); socket.setSoTimeout(CLIENTSOCKETTIMEOUT); final DatagramPacket responsePacket = new DatagramPacket(new byte[RESPONSE_PACKET_SIZE], RESPONSE_PACKET_SIZE); for (int retries = 0; retries < DISCOVERFAILURERETRIES; retries++) { final DatagramPacket lookupRequest = createJobManagerLookupRequestPacket(magicNumber); for (InetAddress broadcast : targetAddresses) { lookupRequest.setAddress(broadcast); lookupRequest.setPort(discoveryPort); LOG.debug("Sending discovery request to " + lookupRequest.getSocketAddress()); socket.send(lookupRequest); } try { socket.receive(responsePacket); } catch (SocketTimeoutException ste) { LOG.debug("Timeout wainting for discovery reply. Retrying..."); continue; } if (!isPacketForUs(responsePacket, magicNumber)) { LOG.debug("Received packet which is not destined to this Nephele setup"); continue; } final int packetTypeID = getPacketTypeID(responsePacket); if (packetTypeID != JM_LOOKUP_REPLY_ID) { LOG.debug("Received unexpected packet type " + packetTypeID + ", discarding... "); continue; } final int ipcPort = extractIpcPort(responsePacket); // Replace port from discovery service with the actual RPC port // of the job manager if (USE_IPV6) { // TODO: No connection possible unless we remove the scope identifier if (responsePacket.getAddress() instanceof Inet6Address) { try { jobManagerAddress = new InetSocketAddress( InetAddress.getByAddress(responsePacket.getAddress().getAddress()), ipcPort); } catch (UnknownHostException e) { throw new DiscoveryException(StringUtils.stringifyException(e)); } } else { throw new DiscoveryException(responsePacket.getAddress() + " is not a valid IPv6 address"); } } else { jobManagerAddress = new InetSocketAddress(responsePacket.getAddress(), ipcPort); } LOG.debug("Discovered job manager at " + jobManagerAddress); break; } } catch (IOException ioe) { throw new DiscoveryException(ioe.toString()); } finally { if (socket != null) { socket.close(); } } if (jobManagerAddress == null) { LOG.debug("Unable to discover Jobmanager via IP broadcast"); throw new DiscoveryException("Unable to discover JobManager via IP broadcast!"); } return jobManagerAddress; }
From source file:org.openhealthtools.openatna.audit.server.UdpServer.java
private String logPacket(DatagramPacket packet) { String localAddress = udpConn.getServerSocket().getLocalAddress().getHostAddress(); int port = udpConn.getServerSocket().getLocalPort(); InetSocketAddress addr = (InetSocketAddress) packet.getSocketAddress(); return "UDP DatagramPacket received from:" + addr.getAddress().getHostAddress() + ":" + addr.getPort() + " to:" + localAddress + ":" + port; }
From source file:com.bitbreeds.webrtc.dtls.DtlsMuxStunTransport.java
public int receive(byte[] buf, int off, int len, int waitMillis) throws IOException { socket.setSoTimeout(waitMillis);/*from w w w . j av a2s.c o m*/ DatagramPacket packet = new DatagramPacket(buf, off, len); socket.receive(packet); logger.trace("Socket read msg: {}", Hex.encodeHexString(SignalUtil.copyRange(buf, new ByteRange(0, packet.getLength())))); if (buf.length >= 2 && buf[0] == 0 && buf[1] == 1) { SocketAddress currentSender = packet.getSocketAddress(); byte[] data = Arrays.copyOf(packet.getData(), packet.getLength()); byte[] out = bindingService.processBindingRequest(data, parent.getLocal().getUserName(), parent.getLocal().getPassword(), (InetSocketAddress) currentSender); logger.trace("Stun packet received, responding with {}", Hex.encodeHexString(out)); this.send(out, 0, out.length); return 0; //We do not want DTLS to process (not that it will anyway), so we return 0 here. } return packet.getLength(); }
From source file:org.springframework.integration.ip.udp.DatagramPacketMulticastSendingHandlerTests.java
@Test public void verifySendMulticastWithAcks() throws Exception { MulticastSocket socket;//from w w w. j a va 2s . co m try { socket = new MulticastSocket(); } catch (Exception e) { return; } final int testPort = socket.getLocalPort(); final AtomicInteger ackPort = new AtomicInteger(); final String multicastAddress = "225.6.7.8"; final String payload = "foobar"; final CountDownLatch listening = new CountDownLatch(2); final CountDownLatch ackListening = new CountDownLatch(1); final CountDownLatch ackSent = new CountDownLatch(2); Runnable catcher = () -> { try { byte[] buffer = new byte[1000]; DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length); MulticastSocket socket1 = new MulticastSocket(testPort); socket1.setInterface(InetAddress.getByName(multicastRule.getNic())); socket1.setSoTimeout(8000); InetAddress group = InetAddress.getByName(multicastAddress); socket1.joinGroup(group); listening.countDown(); assertTrue(ackListening.await(10, TimeUnit.SECONDS)); LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " waiting for packet"); socket1.receive(receivedPacket); socket1.close(); byte[] src = receivedPacket.getData(); int length = receivedPacket.getLength(); int offset = receivedPacket.getOffset(); byte[] dest = new byte[6]; System.arraycopy(src, offset + length - 6, dest, 0, 6); assertEquals(payload, new String(dest)); LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " received packet"); DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper(); mapper.setAcknowledge(true); mapper.setLengthCheck(true); Message<byte[]> message = mapper.toMessage(receivedPacket); Object id = message.getHeaders().get(IpHeaders.ACK_ID); byte[] ack = id.toString().getBytes(); DatagramPacket ackPack = new DatagramPacket(ack, ack.length, new InetSocketAddress(multicastRule.getNic(), ackPort.get())); DatagramSocket out = new DatagramSocket(); out.send(ackPack); LogFactory.getLog(getClass()) .debug(Thread.currentThread().getName() + " sent ack to " + ackPack.getSocketAddress()); out.close(); ackSent.countDown(); socket1.close(); } catch (Exception e) { listening.countDown(); e.printStackTrace(); } }; Executor executor = Executors.newFixedThreadPool(2); executor.execute(catcher); executor.execute(catcher); assertTrue(listening.await(10000, TimeUnit.MILLISECONDS)); MulticastSendingMessageHandler handler = new MulticastSendingMessageHandler(multicastAddress, testPort, true, true, "localhost", 0, 10000); handler.setLocalAddress(this.multicastRule.getNic()); handler.setMinAcksForSuccess(2); handler.setBeanFactory(mock(BeanFactory.class)); handler.afterPropertiesSet(); handler.start(); waitAckListening(handler); ackPort.set(handler.getAckPort()); ackListening.countDown(); handler.handleMessage(MessageBuilder.withPayload(payload).build()); assertTrue(ackSent.await(10000, TimeUnit.MILLISECONDS)); handler.stop(); socket.close(); }
From source file:com.liferay.util.transport.MulticastDatagramHandler.java
public void process(DatagramPacket packet) { byte[] bytes = packet.getData(); if (_gzipData) { try {/*from w ww . j a v a2 s.c o m*/ bytes = getUnzippedBytes(bytes); } catch (Exception e) { _log.error(e, e); } } if (_shortData) { byte[] temp = new byte[96]; System.arraycopy(bytes, 0, temp, 0, 96); bytes = temp; } StringBundler sb = new StringBundler(4); sb.append("["); sb.append(packet.getSocketAddress()); sb.append("] "); sb.append(new String(bytes)); if (_log.isInfoEnabled()) { _log.info(sb); } }