public static String getLocalAddressByDatagram() { try(final DatagramSocket socket = new DatagramSocket()){ socket.connect(InetAddress.getByName("8.8.8.8"), 10002); return socket.getLocalAddress().getHostAddress(); } catch (Exception e) { logger.error("Failed to retrieving ip address.", e); } return null; }
protected static Collection<InetAddress> getPhysicalAddresses(InetAddress addr, InetAddress bind_addr, int port, final long timeout) throws Exception { final DatagramSocket sock=new DatagramSocket(new InetSocketAddress(bind_addr, 0)); byte[] payload="member-addrs".getBytes(); DatagramPacket probe=new DatagramPacket(payload, 0, payload.length, addr, port); sock.send(probe); new Thread(() -> { Util.sleep(timeout); sock.close(); }).start(); long end_time=System.currentTimeMillis() + timeout; while(System.currentTimeMillis() < end_time) { byte[] buf=new byte[70000]; DatagramPacket rsp=new DatagramPacket(buf, 0, buf.length); try { sock.receive(rsp); } catch(Throwable t) { break; } byte[] data=rsp.getData(); String response=new String(data, 0, rsp.getLength()); Collection<InetAddress> retval=parseAddresses(response); if(retval != null && !retval.isEmpty()) return retval; } return null; }
/** * Receive a UDP packet from the tracker. * * @param attempt The attempt number, used to calculate the timeout for the * receive operation. * @retun Returns a {@link ByteBuffer} containing the packet data. */ private ByteBuffer recv(int attempt) throws IOException, SocketException, SocketTimeoutException { int timeout = UDP_BASE_TIMEOUT_SECONDS * (int) Math.pow(2, attempt); logger.trace("Setting receive timeout to {}s for attempt {}...", timeout, attempt); this.socket.setSoTimeout(timeout * 1000); try { DatagramPacket p = new DatagramPacket( new byte[UDP_PACKET_LENGTH], UDP_PACKET_LENGTH); this.socket.receive(p); return ByteBuffer.wrap(p.getData(), 0, p.getLength()); } catch (SocketTimeoutException ste) { throw ste; } } }
@Override protected boolean isPortAvailable(int port) { try { DatagramSocket socket = new DatagramSocket(port, InetAddress.getByName("localhost")); socket.close(); return true; } catch (Exception ex) { return false; } } };
/** * Returns the {@code SocketAddress} this socket is bound to, or null for an unbound socket. */ public SocketAddress getLocalSocketAddress() { if (!isBound()) { return null; } return new InetSocketAddress(getLocalAddress(), getLocalPort()); }
/** * Initializes a new {@link OctoRelay} instance, binding on a specific * address and port. * @param address the address on which to bind. * @param port the port on which to bind. */ public OctoRelay(String address, int port) throws UnknownHostException, SocketException { DatagramSocket s = new DatagramSocket( new InetSocketAddress(InetAddress.getByName(address), port)); socket = new MultiplexingDatagramSocket(s, true /* persistent */); this.port = port; String id = address + ":" + port; setRelayId(id); }
socket = new MulticastSocket(); final int testPort = socket.getLocalPort(); final AtomicInteger ackPort = new AtomicInteger(); socket1.receive(receivedPacket); socket1.close(); byte[] src = receivedPacket.getData(); int length = receivedPacket.getLength(); int offset = receivedPacket.getOffset(); byte[] dest = new byte[6]; 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); out.close(); ackSent.countDown(); socket1.close();
/** * Start this server, causing it to poll JMX at the configured frequency. */ @Override public void start() { try { socket = new DatagramSocket(); hostname = InetAddress.getLocalHost().getHostName(); } catch (SocketException ex) { logger.error("Could not create socket for metrics collection."); throw new FlumeException( "Could not create socket for metrics collection.", ex); } catch (Exception ex2) { logger.warn("Unknown error occured", ex2); } for (HostInfo host : hosts) { addresses.add(new InetSocketAddress( host.getHostName(), host.getPortNumber())); } collectorRunnable.server = this; if (service.isShutdown() || service.isTerminated()) { service = Executors.newSingleThreadScheduledExecutor(); } service.scheduleWithFixedDelay(collectorRunnable, 0, pollFrequency, TimeUnit.SECONDS); }
try (DatagramSocket responseSocket = new DatagramSocket(upnpResponsePort); MulticastSocket upnpMulticastSocket = new MulticastSocket(UPNP_DISCOVERY_PORT);) { InetSocketAddress socketAddress = new InetSocketAddress(UPNP_MULTICAST_ADDRESS, UPNP_DISCOVERY_PORT); Enumeration<NetworkInterface> ifs = NetworkInterface.getNetworkInterfaces(); InetAddress addr = addrs.nextElement(); log.debug(name + " ... has addr " + addr); if (InetAddressUtils.isIPv4Address(addr.getHostAddress())) { IPsPerNic++; upnpMulticastSocket.joinGroup(socketAddress, xface); log.debug("Adding " + name + " to our interface set"); DatagramPacket packet = new DatagramPacket(buf, buf.length); upnpMulticastSocket.receive(packet); String packetString = new String(packet.getData()); if(isSSDPDiscovery(packetString)){ log.debug("Got SSDP Discovery packet from " + packet.getAddress().getHostAddress() + ":" + packet.getPort()); for(int i = 0; i < portCount; i ++) { sendUpnpResponse(responseSocket, packet.getAddress(), packet.getPort(), portBase+i, i);
while (true) { byte[] buffer = new byte[1024 * 64]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); udpSocket.receive(packet); String json = new String(packet.getData(), 0, packet.getLength(), Charset.forName("UTF-8")).trim(); AckPacket ackPacket = JSON.parseObject(json, AckPacket.class); InetSocketAddress socketAddress = (InetSocketAddress) packet.getSocketAddress(); String ip = socketAddress.getAddress().getHostAddress(); int port = socketAddress.getPort();
_apiSocket.setReuseAddress(true); _udpSocket = DatagramChannel.open(); _udpSocket.socket().setReuseAddress(true); InetSocketAddress isa = new InetSocketAddress(H2O.SELF_ADDRESS, H2O_PORT); _udpSocket.socket().bind(isa); Log.info("Internal communication uses port: ", H2O_PORT,"\nListening for HTTP and REST traffic on http://",SELF_ADDRESS.getHostAddress(),":"+_apiSocket.getLocalPort()+"/"); ip[i] = (byte)(port>>>((3-i)<<3)); try { CLOUD_MULTICAST_GROUP = InetAddress.getByAddress(ip); } catch( UnknownHostException e ) { throw Log.errRTExcept(e); } CLOUD_MULTICAST_PORT = (port>>>16);
@Override public long open(DataSpec dataSpec) throws UdpDataSourceException { uri = dataSpec.uri; String host = uri.getHost(); int port = uri.getPort(); transferInitializing(dataSpec); try { address = InetAddress.getByName(host); socketAddress = new InetSocketAddress(address, port); if (address.isMulticastAddress()) { multicastSocket = new MulticastSocket(socketAddress); multicastSocket.joinGroup(address); socket = multicastSocket; } else { socket = new DatagramSocket(socketAddress); } } catch (IOException e) { throw new UdpDataSourceException(e); } try { socket.setSoTimeout(socketTimeoutMillis); } catch (SocketException e) { throw new UdpDataSourceException(e); } opened = true; transferStarted(dataSpec); return C.LENGTH_UNSET; }
public void run() { while (running) { buf = new byte[16000]; mcast_packet = new DatagramPacket(buf, buf.length); try { mcast_sock.receive(mcast_packet); req = (DiscoveryRequest) Util.objectFromByteBuffer(mcast_packet.getData()); System.out.println("<-- " + req); // send response back to req.sender_addr rsp = new DiscoveryResponse(new InetSocketAddress(local_addr, local_port), req.sender_addr.getAddress()); buf = Util.objectToByteBuffer(rsp); rsp_packet = new DatagramPacket(buf, buf.length, req.sender_addr); sock.send(rsp_packet); } catch (Exception ex) { System.err.println("McastReceiver.run(): " + ex + ", rsp_packet=" + rsp_packet.getSocketAddress() + ", length=" + rsp_packet.getLength() + " bytes"); ex.printStackTrace(); } } } }
public void createSocket() throws IOException { try { InetSocketAddress address = new InetSocketAddress(this.serverHost, this.serverPort); socket = new DatagramSocket(); packet = new DatagramPacket("".getBytes(StandardCharsets.UTF_8), 0, 0, address.getAddress(), this.serverPort); } catch (IOException ioe) { throw NetUtils.wrapException(this.serverHost, this.serverPort, "localhost", 0, ioe); } }
protected synchronized DatagramSocket getSocket() throws IOException { if (this.socket == null) { if (this.acknowledge) { if (this.localAddress == null) { this.socket = this.ackPort == 0 ? new DatagramSocket() : new DatagramSocket(this.ackPort); } else { InetAddress whichNic = InetAddress.getByName(this.localAddress); this.socket = new DatagramSocket(new InetSocketAddress(whichNic, this.ackPort)); } if (this.soReceiveBufferSize > 0) { this.socket.setReceiveBufferSize(this.soReceiveBufferSize); } if (logger.isDebugEnabled()) { logger.debug("Listening for acks on port: " + getAckPort()); } updateAckAddress(); } else { this.socket = new DatagramSocket(); } setSocketAttributes(this.socket); } return this.socket; }
/** * Binds UDP socket on the provided <code>port</code>. * * @throws IOException if any I/O error occurs. */ @Override public void bind() throws IOException { getJavaChannel().socket().bind(new InetSocketAddress(InetAddress.getLocalHost(), port)); getJavaChannel().configureBlocking(false); LOGGER.info("Bound UDP socket at port: {}", port); }
@Override public void run() { try { InputStream in = localTcpSocket.getInputStream(); InetAddress remoteHost = InetAddress.getByName(remoteUdpHost); process.start(); while (true) { byte[] b = new byte[500]; int s = in.read(b); // if (s == -1) continue; LOGGER.fine("TCP Client:" + new String(b, 0, s, "UTF-8")); DatagramPacket udpPacket = new DatagramPacket(b, s); udpPacket.setAddress(remoteHost); udpPacket.setPort(remoteUdpPort); localUdpSocket.send(udpPacket); } } catch (IOException e) { LOGGER.log(Level.WARNING, "exception", e); } }
@Override public void run() { try { //System.out.println("Listening for ECHO: " + socket.getLocalAddress().getHostAddress() + ":" + socket.getLocalPort()); while (true) { DatagramPacket packet = new DatagramPacket(new byte[8], 8); socket.receive(packet); System.out.println("ECHO Packet Received in: " + socket.getLocalAddress().getHostAddress() + ":" + socket.getLocalPort() + " From: " + packet.getAddress().getHostAddress() + ":" + packet.getPort()); for (DatagramListener listener : listeners) { listener.datagramReceived(packet); } packet.setAddress(packet.getAddress()); packet.setPort(packet.getPort()); if (!Arrays.equals(packet.getData(), password)) for (int i = 0; i < 3; i++) socket.send(packet); } } catch (IOException ioe) { if (enabled) { } } }
if (mSocket == null) { mSocket = new DatagramSocket(null); mSocket.setReuseAddress(true); mSocket.setBroadcast(true); mSocket.bind(new InetSocketAddress(BCAST_PORT)); }