java.net.DatagramPacket Java Examples

The following examples show how to use java.net.DatagramPacket. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: jblink   Author: pantor-engineering   File: Client.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
    Sends a collection of messages to the server

    @param objs the messages to send
    @throws BlinkException if there is a schema or binding problem
    @throws IOException if there is a socket or communications problem
 */

 public void send (Iterable<?> objs) throws BlinkException, IOException
 {
    wr.write (objs);
    wr.flush ();

    if (udpsock != null)
    {
byte [] data = bs.toByteArray ();
bs.reset ();
DatagramPacket p =
   new DatagramPacket (data, data.length,
		udpsock.getRemoteSocketAddress ());
udpsock.send (p);
    }
 }
 
Example #2
Source Project: tomee   Author: apache   File: MulticastDiscoveryAgent.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    final byte[] buf = new byte[BUFF_SIZE];
    final DatagramPacket packet = new DatagramPacket(buf, 0, buf.length);
    while (running.get()) {
        tracker.checkServices();
        try {
            multicast.receive(packet);
            if (packet.getLength() > 0) {
                final String str = new String(packet.getData(), packet.getOffset(), packet.getLength());
                //                        System.out.println("read = " + str);
                tracker.processData(str);
            }
        } catch (SocketTimeoutException se) {
            // ignore
        } catch (IOException e) {
            if (running.get()) {
                LOGGER.error("failed to process packet: " + e);
            }
        }
    }
}
 
Example #3
Source Project: wildfly-core   Author: wildfly   File: SimpleSyslogServer.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void run(){

    while (!closed.get()){
        try {
            DatagramPacket packet = new DatagramPacket(new byte[2048], 2048);
            socket.receive(packet);
            byte[] bytes = new byte[packet.getLength()];
            System.arraycopy(packet.getData(), 0, bytes, 0, packet.getLength());
            receivedData.add(bytes);
        } catch (IOException e) {
            if (!closed.get()){
                e.printStackTrace();
                close();
            }
        }
    }
}
 
Example #4
Source Project: jamod   Author: jeick   File: UDPSlaveTerminal.java    License: Apache License 2.0 6 votes vote down vote up
public void run() {
	do {
		try {
			// 1. Prepare buffer and receive package
			byte[] buffer = new byte[256];// max size
			DatagramPacket packet = new DatagramPacket(buffer,
					buffer.length);
			m_Socket.receive(packet);
			// 2. Extract TID and remember request
			Integer tid = new Integer(ModbusUtil.registersToInt(buffer));
			m_Requests.put(tid, packet);
			// 3. place the data buffer in the queue
			m_ReceiveQueue.put(buffer);
			if (Modbus.debug)
				System.out.println("Received package to queue.");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	} while (m_Continue);
}
 
Example #5
Source Project: jdk8u60   Author: chenghanpeng   File: SnmpRequestHandler.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Full constructor
 */
public SnmpRequestHandler(SnmpAdaptorServer server, int id,
                          DatagramSocket s, DatagramPacket p,
                          SnmpMibTree tree, Vector<SnmpMibAgent> m,
                          InetAddressAcl a,
                          SnmpPduFactory factory,
                          SnmpUserDataFactory dataFactory,
                          MBeanServer f, ObjectName n)
{
    super(server, id, f, n);

    // Need a reference on SnmpAdaptorServer for getNext & getBulk,
    // in case of oid equality (mib overlapping).
    //
    adaptor = server;
    socket = s;
    packet = p;
    root= tree;
    mibs = new Vector<>(m);
    subs= new Hashtable<>(mibs.size());
    ipacl = a;
    pduFactory = factory ;
    userDataFactory = dataFactory ;
    //thread.start();
}
 
Example #6
Source Project: oodt   Author: apache   File: DatagramLogger.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] argv) throws Throwable {
	if (argv.length > 0) {
		System.err.println("This program takes NO command line arguments.");
		System.err.println("Set the activity.port property to adjust the port number.");
		System.err.println("Set the activity.storage property to set the Storage class to use.");
		System.exit(1);
	}
	int port = Integer.getInteger("activity.port", VAL);
	String className = System.getProperty("activity.storage");
	if (className == null) {
		System.err.println("No Storage class defined via the `activity.storage' property; exiting...");
		System.exit(1);
	}
	Class storageClass = Class.forName(className);
	storage = (Storage) storageClass.newInstance();
	DatagramSocket socket = new DatagramSocket(port);
	byte[] buf = new byte[INT];
	DatagramPacket packet = new DatagramPacket(buf, buf.length);
	for (;;) {
		socket.receive(packet);
		byte[] received = new byte[packet.getLength()];
		System.arraycopy(packet.getData(), packet.getOffset(), received, 0, packet.getLength());
		new ReceiverThread(received).start();
	} 
}
 
Example #7
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: DatagramSocketAdaptor.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void receive(DatagramPacket p) throws IOException {
    synchronized (dc.blockingLock()) {
        if (!dc.isBlocking())
            throw new IllegalBlockingModeException();
        try {
            synchronized (p) {
                ByteBuffer bb = ByteBuffer.wrap(p.getData(),
                                                p.getOffset(),
                                                p.getLength());
                SocketAddress sender = receive(bb);
                p.setSocketAddress(sender);
                p.setLength(bb.position() - p.getOffset());
            }
        } catch (IOException x) {
            Net.translateException(x);
        }
    }
}
 
Example #8
Source Project: openhab1-addons   Author: openhab   File: MilightBinding.java    License: Eclipse Public License 2.0 6 votes vote down vote up
protected void sendMessage(String messageBytes, String bridgeId) {

        String bridgeIp = bridgeIpConfig.get(bridgeId);
        Integer bridgePort = bridgePortConfig.get(bridgeId);

        if (bridgePort == null) {
            bridgePort = DEFAULT_PORT;
        }

        try {
            byte[] buffer = getMessageBytes(messageBytes);

            InetAddress IPAddress = InetAddress.getByName(bridgeIp);
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length, IPAddress, bridgePort);
            DatagramSocket datagramSocket = new DatagramSocket();
            datagramSocket.send(packet);
            datagramSocket.close();
            logger.debug("Sent packet '{}' to bridge '{}' ({}:{})",
                    new Object[] { messageBytes, bridgeId, bridgeIp, bridgePort });
        } catch (Exception e) {
            logger.error("Failed to send Message to '{}': ", new Object[] { bridgeIp, e.getMessage() });
        }
    }
 
Example #9
Source Project: personaldnsfilter   Author: IngoZenz   File: DNSServer.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void resolve(DatagramPacket request, DatagramPacket response) throws IOException {
    for (int i = 0; i<2; i++) { //retry once in case of EOFException (pooled connection was already closed)
        Connection con = Connection.connect(address, timeout, ssl, null, Proxy.NO_PROXY);
        con.setSoTimeout(timeout);
        try {
            DataInputStream in = new DataInputStream(con.getInputStream());
            DataOutputStream out = new DataOutputStream(con.getOutputStream());
            out.writeShort(request.getLength());
            out.write(request.getData(), request.getOffset(), request.getLength());
            out.flush();
            int size = in.readShort();
            readResponseFromStream(in, size, response);
            response.setSocketAddress(address);
            con.release(true);
            return;
        } catch (EOFException eof) {
            con.release(false);
            if (i == 1)
                throw new IOException ("EOF when reading from "+this.toString(),eof); // retried already once, now throw exception
        } catch (IOException eio) {
            con.release(false);
            throw eio;
        }
    }
}
 
Example #10
Source Project: seventh   Author: tonysparks   File: LANServerRegistration.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 
 */
public LANServerRegistration(final ServerContext serverContext) {
    
    final LANServerConfig config = serverContext.getConfig().getLANServerConfig();
    this.listener = new BroadcastListener(config.getMtu(), config.getBroadcastAddress(), config.getPort());
    this.listener.addOnMessageReceivedListener(new OnMessageReceivedListener() {
            
        @Override
        public void onMessage(DatagramPacket packet) {
            String msg = new String(packet.getData(), packet.getOffset(), packet.getLength()).trim();
            if(msg.equalsIgnoreCase("ping")) {
                try(Broadcaster caster = new Broadcaster(config.getMtu(), config.getBroadcastAddress(), config.getPort())) {
                    ServerInfo info = new ServerInfo(serverContext);
                    caster.broadcastMessage(info.toString());
                }
                catch(Exception e) {
                    Cons.println("*** ERROR: Unable to broadcast response: " + e);
                }
            }
        }
    });
    
}
 
Example #11
Source Project: Connect-SDK-Android-Core   Author: ConnectSDK   File: SSDPPacketTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testParseLowercaseDatagram() {
    String testDatagramData =
            "NOTIFY * HTTP/1.1\r\n" +
            "host: 239.255.255.250:1900\r\n" +
            "nt: nt_value\r\n" +
            "Nts: ssdp:byebye\r\n" +
            "uSN: uuid:advertisement_UUID\r\n\r\n";
    mDatagramPacket = new DatagramPacket(testDatagramData.getBytes(), 0);
    ssdpPacket = new SSDPPacket(mDatagramPacket);
    Assert.assertEquals("NOTIFY * HTTP/1.1", ssdpPacket.getType());
    Assert.assertEquals("239.255.255.250:1900", ssdpPacket.getData().get("HOST"));
    Assert.assertEquals("nt_value", ssdpPacket.getData().get("NT"));
    Assert.assertEquals("ssdp:byebye", ssdpPacket.getData().get("NTS"));
    Assert.assertEquals("uuid:advertisement_UUID", ssdpPacket.getData().get("USN"));
}
 
Example #12
Source Project: sockslib   Author: fengyouchao   File: Socks5DatagramPacketHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public DatagramPacket encapsulate(DatagramPacket packet, SocketAddress destination) throws
    SocksException {
  if (destination instanceof InetSocketAddress) {
    InetSocketAddress destinationAddress = (InetSocketAddress) destination;
    final byte[] data = packet.getData();
    final InetAddress remoteServerAddress = packet.getAddress();
    final byte[] addressBytes = remoteServerAddress.getAddress();
    final int ADDRESS_LENGTH = remoteServerAddress.getAddress().length;
    final int remoteServerPort = packet.getPort();
    byte[] buffer = new byte[6 + packet.getLength() + ADDRESS_LENGTH];

    buffer[0] = buffer[1] = 0; // reserved byte
    buffer[2] = 0; // fragment byte
    buffer[3] = (byte) (ADDRESS_LENGTH == 4 ? AddressType.IPV4 : AddressType.IPV6);
    System.arraycopy(addressBytes, 0, buffer, 4, ADDRESS_LENGTH);
    buffer[4 + ADDRESS_LENGTH] = SocksUtil.getFirstByteFromInt(remoteServerPort);
    buffer[5 + ADDRESS_LENGTH] = SocksUtil.getSecondByteFromInt(remoteServerPort);
    System.arraycopy(data, 0, buffer, 6 + ADDRESS_LENGTH, packet.getLength());
    return new DatagramPacket(buffer, buffer.length, destinationAddress.getAddress(),
        destinationAddress.getPort());
  } else {
    throw new IllegalArgumentException("Only support java.net.InetSocketAddress");
  }
}
 
Example #13
Source Project: TencentKona-8   Author: Tencent   File: SnmpAdaptorServer.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Send the specified message on trapSocket.
 */
private void sendTrapMessage(SnmpMessage msg)
    throws IOException, SnmpTooBigException {

    byte[] buffer = new byte[bufferSize] ;
    DatagramPacket packet = new DatagramPacket(buffer, buffer.length) ;
    int encodingLength = msg.encodeMessage(buffer) ;
    packet.setLength(encodingLength) ;
    packet.setAddress(msg.address) ;
    packet.setPort(msg.port) ;
    if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINER)) {
        SNMP_ADAPTOR_LOGGER.logp(Level.FINER, dbgTag,
            "sendTrapMessage", "sending trap to " + msg.address + ":" +
              msg.port);
    }
    trapSocket.send(packet) ;
    if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINER)) {
        SNMP_ADAPTOR_LOGGER.logp(Level.FINER, dbgTag,
            "sendTrapMessage", "sent to " + msg.address + ":" +
              msg.port);
    }
    snmpOutTraps++;
    snmpOutPkts++;
}
 
Example #14
Source Project: WirelessHid   Author: CreateChance   File: WirelessHidService.java    License: Apache License 2.0 6 votes vote down vote up
private void sendDisconnectMsg() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            if (mMulticastSocket != null) {
                DatagramPacket packet = new DatagramPacket(Constant.HID_SERVICE_DISCONNECT.getBytes(),
                        Constant.HID_SERVICE_DISCONNECT.length(),
                        group, Constant.HID_MULTICAST_PORT);
                try {
                    mMulticastSocket.send(packet);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                mPCDiscoverer.stopDiscover();
            }
        }
    }).start();
}
 
Example #15
Source Project: modbus4j   Author: infiniteautomation   File: UdpMaster.java    License: GNU General Public License v3.0 6 votes vote down vote up
private IpMessageResponse receiveImpl() throws IOException, ModbusTransportException {
    DatagramPacket packet = new DatagramPacket(new byte[MESSAGE_LENGTH], MESSAGE_LENGTH);
    socket.receive(packet);

    // We could verify that the packet was received from the same address to which the request was sent,
    // but let's not bother with that yet.

    ByteQueue queue = new ByteQueue(packet.getData(), 0, packet.getLength());
    IpMessageResponse response;
    try {
        response = (IpMessageResponse) messageParser.parseMessage(queue);
    }
    catch (Exception e) {
        throw new ModbusTransportException(e);
    }

    if (response == null)
        throw new ModbusTransportException("Invalid response received");

    return response;
}
 
Example #16
Source Project: LocalNetwork   Author: itsJoKr   File: DiscoveryThread.java    License: MIT License 6 votes vote down vote up
@Override
public void run() {
    try {
        int port = NetworkUtil.BASE_PORT;
        do {
            socket = new DatagramSocket(port, InetAddress.getByName("0.0.0.0"));
            port--;
        } while (socket == null);

        socket.setBroadcast(true);

        while (true) {
            // Receive broadcast packet
            byte[] buffer = new byte[15000];
            DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
            socket.receive(receivePacket);
            Log.d("USER", "Received packet from: " + receivePacket.getAddress().getHostAddress());

            // Send reply
            byte[] replyPacket = SerializationUtil.serialize(reply);
            socket.send(new DatagramPacket(replyPacket, replyPacket.length, receivePacket.getAddress(), receivePacket.getPort()));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #17
Source Project: jdk8u-jdk   Author: lambdalab-mirror   File: SnmpAdaptorServer.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Send the specified message on trapSocket.
 */
private void sendTrapMessage(SnmpMessage msg)
    throws IOException, SnmpTooBigException {

    byte[] buffer = new byte[bufferSize] ;
    DatagramPacket packet = new DatagramPacket(buffer, buffer.length) ;
    int encodingLength = msg.encodeMessage(buffer) ;
    packet.setLength(encodingLength) ;
    packet.setAddress(msg.address) ;
    packet.setPort(msg.port) ;
    if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINER)) {
        SNMP_ADAPTOR_LOGGER.logp(Level.FINER, dbgTag,
            "sendTrapMessage", "sending trap to " + msg.address + ":" +
              msg.port);
    }
    trapSocket.send(packet) ;
    if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINER)) {
        SNMP_ADAPTOR_LOGGER.logp(Level.FINER, dbgTag,
            "sendTrapMessage", "sent to " + msg.address + ":" +
              msg.port);
    }
    snmpOutTraps++;
    snmpOutPkts++;
}
 
Example #18
Source Project: sockslib   Author: fengyouchao   File: UDPRelayServer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
  try {
    byte[] buffer = new byte[bufferSize];
    while (running) {
      DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
      server.receive(packet);
      if (isFromClient(packet)) {
        datagramPacketHandler.decapsulate(packet);
        server.send(packet);
      } else {
        packet =
            datagramPacketHandler.encapsulate(packet, new InetSocketAddress(clientAddress,
                clientPort));
        server.send(packet);
      }
    }
  } catch (IOException e) {
    if (e.getMessage().equalsIgnoreCase("Socket closed") && !running) {
      logger.debug("UDP relay server stopped");
    } else {
      logger.error(e.getMessage(), e);
    }
  }
}
 
Example #19
Source Project: jamod   Author: jeick   File: UDPSlaveTerminal.java    License: Apache License 2.0 6 votes vote down vote up
public void run() {
	do {
		try {
			// 1. pickup the message and corresponding request
			byte[] message = (byte[]) m_SendQueue.take();
			DatagramPacket req = (DatagramPacket) m_Requests
					.remove(new Integer(ModbusUtil
							.registersToInt(message)));
			// 2. create new Package with corresponding address and port
			DatagramPacket res = new DatagramPacket(message,
					message.length, req.getAddress(), req.getPort());
			m_Socket.send(res);
			if (Modbus.debug)
				System.out.println("Sent package from queue.");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	} while (m_Continue || !m_SendQueue.isEmpty());
}
 
Example #20
Source Project: dubbox   Author: learningtcc   File: MulticastExchangeGroup.java    License: Apache License 2.0 5 votes vote down vote up
private void send(String msg) throws RemotingException {
    DatagramPacket hi = new DatagramPacket(msg.getBytes(), msg.length(), mutilcastAddress, mutilcastSocket.getLocalPort());
    try {
        mutilcastSocket.send(hi);
    } catch (IOException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}
 
Example #21
Source Project: dubbox   Author: hutai123   File: MulticastGroup.java    License: Apache License 2.0 5 votes vote down vote up
private void send(String msg) throws RemotingException {
    DatagramPacket hi = new DatagramPacket(msg.getBytes(), msg.length(), mutilcastAddress, mutilcastSocket.getLocalPort());
    try {
        mutilcastSocket.send(hi);
    } catch (IOException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}
 
Example #22
Source Project: AirMapSDK-Android   Author: airmap   File: TelemetryService.java    License: Apache License 2.0 5 votes vote down vote up
private void send(List<MessageLite> messageList) {
    try {
        byte[] message = buildPacketData(comm.getKey(), flightId, Encryption.AES256CBC, messageList);
        DatagramPacket packet = new DatagramPacket(message, message.length);
        socket.send(packet);
        packetNumber++;
    } catch (IOException | NoSuchAlgorithmException | InvalidKeyException | InvalidAlgorithmParameterException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) {
        Timber.e(e, "Unable to build or send packet");
    }
}
 
Example #23
Source Project: freeacs   Author: freeacs   File: BindingLifetimeTest.java    License: MIT License 5 votes vote down vote up
private boolean bindingCommunicationInitialSocket()
    throws UtilityException, IOException, MessageHeaderParsingException,
        MessageAttributeParsingException {
  MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest);
  sendMH.generateTransactionID();
  ChangeRequest changeRequest = new ChangeRequest();
  sendMH.addMessageAttribute(changeRequest);
  byte[] data = sendMH.getBytes();

  DatagramPacket send =
      new DatagramPacket(data, data.length, InetAddress.getByName(stunServer), port);
  initialSocket.send(send);
  LOGGER.debug("Binding Request sent.");

  MessageHeader receiveMH = new MessageHeader();
  while (!receiveMH.equalTransactionID(sendMH)) {
    DatagramPacket receive = new DatagramPacket(new byte[200], 200);
    initialSocket.receive(receive);
    receiveMH = MessageHeader.parseHeader(receive.getData());
    receiveMH.parseAttributes(receive.getData());
  }
  ma =
      (MappedAddress)
          receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.MappedAddress);
  ErrorCode ec =
      (ErrorCode) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode);
  if (ec != null) {
    LOGGER.debug("Message header contains an Errorcode message attribute.");
    return true;
  }
  if (ma == null) {
    LOGGER.debug("Response does not contain a Mapped Address message attribute.");
    return true;
  }
  return false;
}
 
Example #24
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: CheckBoundaries.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    boolean exception = false;
    try {
        final int offset = Integer.MAX_VALUE;
        final int length = 1;
        new DatagramPacket(new byte[1024], offset, length);
    } catch (IllegalArgumentException e) {
        exception = true;
    }
    if (!exception)
        throw new RuntimeException("IllegalArgumentException not thrown!");
}
 
Example #25
Source Project: seventh   Author: tonysparks   File: NetworkDisruptor.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void run() throws Exception {
    if(this.isRunning.get()) {
        return;
    }
    
    this.isRunning.set(true);
    
    this.proxySocket = DatagramChannel.open();
    this.proxySocket.configureBlocking(false);
    
    this.proxySocket.bind(new InetSocketAddress("localhost", this.proxyPort));
    
    System.out.println("Proxy server started on " + this.proxySocket.getLocalAddress());
    
    while(this.isRunning.get()) {
        this.recvBuffer.clear();
        
        SocketAddress remoteAddr = this.proxySocket.receive(this.recvBuffer);
        if(remoteAddr != null) {
            System.out.println("Received message from: " + remoteAddr);
            
            this.recvBuffer.flip();
        
            byte[] buf = copy(this.recvBuffer);
            DatagramPacket packet = new DatagramPacket(buf, buf.length, remoteAddr);
            Packet p = new Packet(packet);
            
            if(this.proxiedServerAddress.equals(remoteAddr)) {
                this.pendingServerSendPackets.add(p);
            }
            else {
                this.proxiedClientAddress = remoteAddr;
                this.pendingClientSendPackets.add(p);
            }            
        }
        
        sendPackets(this.pendingServerSendPackets, this.proxiedClientAddress);
        sendPackets(this.pendingClientSendPackets, this.proxiedServerAddress);
    }
}
 
Example #26
Source Project: finalspeed-91yun   Author: sync4git   File: CloseMessage_Stream.java    License: GNU General Public License v2.0 5 votes vote down vote up
public CloseMessage_Stream(DatagramPacket dp){
	this.dp=dp;
	dpData=dp.getData();
	ver=ByteShortConvert.toShort(dpData, 0);
	sType=ByteShortConvert.toShort(dpData, 2);
	
	connectId=ByteIntConvert.toInt(dpData, 4);
	clientId=ByteIntConvert.toInt(dpData, 8);
	closeOffset=ByteIntConvert.toInt(dpData, 12);
	////#MLog.println("vCloseMessagebbb"+clientId+"v");
}
 
Example #27
Source Project: swift-k   Author: swift-lang   File: NTPClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * queries the NTP serevr and calculates the time difference.
 *
 */
public void update() throws IOException {

	// reset the data to erase previous result
	NTPData[0] = 0x1B;
	for (int i = 1; i < 48; i++) {
		NTPData[i] = 0;
	}

	InetAddress IPAddress = InetAddress.getByName(server);
	DatagramSocket NTPSocket = new DatagramSocket();
	DatagramPacket NTPPacket = new DatagramPacket(NTPData, NTPData.length, IPAddress, NTPPort);

	long startTime = System.currentTimeMillis();
	transmitTime = startTime + dT1900to1970;
	toBytes(transmitTime, transmitOffset);

	NTPSocket.send(NTPPacket);
	NTPSocket.receive(NTPPacket);

	destinationTimestamp = System.currentTimeMillis();
	destinationTimestamp += dT1900to1970;

	NTPData = NTPPacket.getData(); //get NTP data from the buffer
	convert();
	NTPSocket.close(); //close connection with NTP server 
}
 
Example #28
Source Project: pinpoint   Author: naver   File: PacketUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSliceData3() throws Exception {
    DatagramPacket packet = createPacket(10);
    Arrays.fill(packet.getData(), 1, 8, (byte)'a');
    packet.setLength(4);

    byte[] bytes1 = PacketUtils.sliceData(packet, 0);
    Assert.assertArrayEquals(bytes1, Arrays.copyOf(packet.getData(), 4));
}
 
Example #29
Source Project: openhab1-addons   Author: openhab   File: WolBinding.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private void sendWolPacket(WolBindingConfig config) {

        if (config == null) {
            logger.error("given parameter 'config' must not be null");
            return;
        }

        InetAddress address = config.address;
        byte[] macBytes = config.macBytes;

        try {

            byte[] bytes = fillMagicBytes(macBytes);

            DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, PORT);

            DatagramSocket socket = new DatagramSocket();
            socket.send(packet);
            socket.close();

            logger.info("Wake-on-LAN packet sent [broadcastIp={}, macaddress={}]", address.getHostName(),
                    String.valueOf(Hex.encodeHex(macBytes)));
        } catch (Exception e) {
            logger.error("Failed to send Wake-on-LAN packet [broadcastIp=" + address.getHostAddress() + ", macaddress="
                    + String.valueOf(Hex.encodeHex(macBytes)) + "]", e);
        }

    }
 
Example #30
Source Project: ict   Author: iotaledger   File: Receiver.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    while (isRunning()) {
        DatagramPacket packet = new DatagramPacket(new byte[Constants.PACKET_SIZE_BYTES], Constants.PACKET_SIZE_BYTES);
        try {
            node.socket.receive(packet);
            processIncoming(packet);
        } catch (IOException e) {
            if (isRunning())
                e.printStackTrace();
        }
    }
}