Java Code Examples for java.net.DatagramSocket#setSoTimeout()

The following examples show how to use java.net.DatagramSocket#setSoTimeout() . 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 File: PortScanUDP.java    From HttpInfo with Apache License 2.0 6 votes vote down vote up
public static PortBean.PortNetBean scanAddress(InetAddress ia, int portNo, int timeoutMillis) {
    PortBean.PortNetBean portNetBean = new PortBean.PortNetBean();
    Long time = System.currentTimeMillis();
    try {
        byte[] bytes = new byte[128];
        DatagramPacket dp = new DatagramPacket(bytes, bytes.length);

        DatagramSocket ds = new DatagramSocket();
        ds.setSoTimeout(timeoutMillis);
        ds.connect(ia, portNo);
        ds.send(dp);
        ds.isConnected();
        ds.receive(dp);
        ds.close();
        portNetBean.setConnected(true);
    } catch (SocketTimeoutException e) {

    } catch (Exception ignore) {

    }
    portNetBean.setPort(portNo);
    portNetBean.setDelay(System.currentTimeMillis() - time);
    return portNetBean;
}
 
Example 2
Source File: UDPReceiver.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
private DatagramSocket createSocket0(int receiveBufferSize) {
    try {
        DatagramSocket socket = new DatagramSocket(null);
        socket.setReceiveBufferSize(receiveBufferSize);
        if (logger.isWarnEnabled()) {
            final int checkReceiveBufferSize = socket.getReceiveBufferSize();
            if (receiveBufferSize != checkReceiveBufferSize) {
                logger.warn("DatagramSocket.setReceiveBufferSize() error. {}!={}", receiveBufferSize, checkReceiveBufferSize);
            }
        }
        socket.setSoTimeout(1000 * 5);
        return socket;
    } catch (SocketException ex) {
        throw new RuntimeException("Socket create Fail. Caused:" + ex.getMessage(), ex);
    }
}
 
Example 3
Source File: UDPInputStreamTest.java    From perfmon-agent with Apache License 2.0 6 votes vote down vote up
/**
 * Test of read method, of class UDPInputStream.
 */
public void testRead() throws Exception {
    System.out.println("read");
    DatagramSocketEmulator emul = new DatagramSocketEmulator();
    DatagramSocket sock = emul;
    sock.setSoTimeout(100);
    UDPInputStream instance = new UDPInputStream(sock);

    emul.setDatagramToReceive(new DatagramPacket("\r\n".getBytes(), 1));
    int expResult = '\r';
    int result = instance.read();
    assertEquals(expResult, result);

    int expResult2 = '\n';
    int result2 = instance.read();
    assertEquals(expResult2, result2);

    int expResult3 = ' ';
    emul.setDatagramToReceive(new DatagramPacket(" ".getBytes(), 1));
    int result3 = instance.read();
    assertEquals(expResult3, result3);
}
 
Example 4
Source File: WakeOnLan.java    From AndroidNetworkTools with Apache License 2.0 5 votes vote down vote up
/**
 * Send a Wake-On-Lan packet
 *
 * @param address       - InetAddress to send wol packet to
 * @param macStr        - MAC address to wake up
 * @param port          - port to send packet to
 * @param timeoutMillis - timeout (millis)
 * @param packets       - number of packets to send
 *
 * @throws IllegalArgumentException - invalid ip or mac
 * @throws IOException - error sending packet
 */
public static void sendWakeOnLan(final InetAddress address, final String macStr, final int port, final int timeoutMillis, final int packets) throws IllegalArgumentException, IOException {
    if (address == null) throw new IllegalArgumentException("Address cannot be null");
    if (macStr == null) throw new IllegalArgumentException("MAC Address cannot be null");
    if (port <= 0 || port > 65535) throw new IllegalArgumentException("Invalid port " + port);
    if (packets <= 0)
        throw new IllegalArgumentException("Invalid number of packets to send " + packets);

    byte[] macBytes = MACTools.getMacBytes(macStr);
    byte[] bytes = new byte[6 + 16 * macBytes.length];
    for (int i = 0; i < 6; i++) {
        bytes[i] = (byte) 0xff;
    }
    for (int i = 6; i < bytes.length; i += macBytes.length) {
        System.arraycopy(macBytes, 0, bytes, i, macBytes.length);
    }

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

    // Wake on lan is unreliable so best to send the packet a few times
    for (int i = 0; i < packets; i++) {
        DatagramSocket socket = new DatagramSocket();

        socket.setSoTimeout(timeoutMillis);

        socket.send(packet);
        socket.close();
    }
}
 
Example 5
Source File: BroadcastDiscoveryClient.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
private String readBroadcastReply(DatagramSocket broadcastSocket, int timeoutInMs) throws IOException {
    byte[] replyBuffer = new byte[URL_MAX_LENGTH];
    DatagramPacket replyPacket = new DatagramPacket(replyBuffer, replyBuffer.length);
    broadcastSocket.setSoTimeout(timeoutInMs);
    broadcastSocket.receive(replyPacket);

    if (replyPacket.getLength() > 0) {
        return new String(replyPacket.getData(), 0, replyPacket.getLength(), BROADCAST_ENCODING);
    } else {
        throw new IllegalStateException("Could not retrieve URL using broadcast discovery, received a malformed packet from " +
                                        replyPacket.getAddress());
    }
}
 
Example 6
Source File: UdpSocket.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
 * タイムアウトをセット, 0ならタイムアウトなし
 * @param timeout [ミリ秒]
 * @throws SocketException
 */
public void setSoTimeout(final int timeout) throws SocketException {
	final DatagramSocket socket = channel != null ? channel.socket() : null;
	if (socket != null) {
		socket.setSoTimeout(timeout);
	}
}
 
Example 7
Source File: SyslogAppenderTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Tests that any header or footer in layout is sent.
 * @throws Exception if exception during test.
 */
public void testLayoutHeader() throws Exception {
    DatagramSocket ds = new DatagramSocket();
    ds.setSoTimeout(2000);

  SyslogAppender appender = new SyslogAppender();
  appender.setSyslogHost("localhost:" + ds.getLocalPort());
  appender.setName("name");
  appender.setHeader(false);
  HTMLLayout pl = new HTMLLayout();
  appender.setLayout(pl);
  appender.activateOptions();

  Logger l = Logger.getRootLogger();
  l.addAppender(appender);
  l.info("Hello, World");
  appender.close();
  String[] s = new String[3];
  byte[] buf = new byte[1000];
  for(int i = 0; i < 3; i++) {
      DatagramPacket p = new DatagramPacket(buf, 0, buf.length);
      ds.receive(p);
      s[i] = new String(p.getData(), 0, p.getLength());
  }
  ds.close();
  assertEquals("<14><!DOCTYPE", s[0].substring(0,13));
  assertEquals("<14></table>", s[2].substring(0,12));
}
 
Example 8
Source File: TransportFactory.java    From perfmon-agent with Apache License 2.0 5 votes vote down vote up
/**
 * Returns new UDP Transport instance
 * connected to specified socket address
 *
 * @param addr
 * @return connected Transport
 * @throws IOException
 */
public static Transport UDPInstance(SocketAddress addr) throws IOException {
    DatagramSocket sock = new DatagramSocket();
    sock.setSoTimeout(getTimeout());
    sock.connect(addr);

    StreamTransport trans = new StreamTransport();
    trans.setStreams(new UDPInputStream(sock), new UDPOutputStream(sock));
    trans.setAddressLabel(addr.toString());
    return trans;
}
 
Example 9
Source File: AcceptorTest.java    From game-server with MIT License 5 votes vote down vote up
public void testUDP() throws Exception {
	DatagramSocket client = new DatagramSocket();
	client.connect(new InetSocketAddress("127.0.0.1", port));
	client.setSoTimeout(500);

	byte[] writeBuf = new byte[16];
	byte[] readBuf = new byte[writeBuf.length];
	DatagramPacket wp = new DatagramPacket(writeBuf, writeBuf.length);
	DatagramPacket rp = new DatagramPacket(readBuf, readBuf.length);

	for (int i = 0; i < 10; i++) {
		fillWriteBuffer(writeBuf, i);
		client.send(wp);

		client.receive(rp);
		assertEquals(writeBuf.length, rp.getLength());
		assertTrue(Arrays.equals(writeBuf, readBuf));
	}

	try {
		client.receive(rp);
		fail("Unexpected incoming data.");
	} catch (SocketTimeoutException e) {
	}

	client.close();
}
 
Example 10
Source File: ServerInfoTask.java    From Plumble with GNU General Public License v3.0 5 votes vote down vote up
@Override
	protected ServerInfoResponse doInBackground(Server... params) {
		server = params[0];
		try {
			InetAddress host = InetAddress.getByName(server.getHost());
			
			// Create ping message
			ByteBuffer buffer = ByteBuffer.allocate(12);
			buffer.putInt(0); // Request type
			buffer.putLong(server.getId()); // Identifier
			DatagramPacket requestPacket = new DatagramPacket(buffer.array(), 12, host, server.getPort());
			
			// Send packet and wait for response
			DatagramSocket socket = new DatagramSocket();
			socket.setSoTimeout(1000);
			socket.setReceiveBufferSize(1024);

            long startTime = System.nanoTime();

            socket.send(requestPacket);
			
			byte[] responseBuffer = new byte[24];
			DatagramPacket responsePacket = new DatagramPacket(responseBuffer, responseBuffer.length);
			socket.receive(responsePacket);

            int latencyInMs = (int) ((System.nanoTime()-startTime)/1000000);
			
			ServerInfoResponse response = new ServerInfoResponse(server, responseBuffer, latencyInMs);
							
			Log.i(Constants.TAG, "DEBUG: Server version: "+response.getVersionString()+"\nUsers: "+response.getCurrentUsers()+"/"+response.getMaximumUsers());
			
			return response;
			
		} catch (Exception e) {
//			e.printStackTrace();
		}

		return new ServerInfoResponse(); // Return dummy in case of failure
	}
 
Example 11
Source File: BroadcastSearch.java    From onpc with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected Void doInBackground(Void... params)
{
    Logging.info(this, "started, network=" + connectionState.isNetwork()
            + ", wifi=" + connectionState.isWifi());

    final Character[] models = new Character[]{ 'x', 'p' };
    int modelId = 0;

    try
    {
        final InetAddress target = InetAddress.getByName("255.255.255.255");

        final DatagramSocket socket = new DatagramSocket(null);
        socket.setReuseAddress(true);
        socket.setBroadcast(true);
        socket.setSoTimeout(500);
        socket.bind(new InetSocketAddress(ISCP_PORT));

        while (!isStopped())
        {
            request(socket, target, models[modelId]);
            modelId++;
            if (modelId > 1)
            {
                modelId = 0;
            }
        }
        socket.close();
    }
    catch (Exception e)
    {
        Logging.info(this, "Can not open socket: " + e.toString());
    }

    Logging.info(this, "stopped");
    return null;
}
 
Example 12
Source File: UdpMaster.java    From modbus4j with GNU General Public License v3.0 5 votes vote down vote up
public void init() throws ModbusInitException {
    if (ipParameters.isEncapsulated())
        messageParser = new EncapMessageParser(true);
    else
        messageParser = new XaMessageParser(true);

    try {
        socket = new DatagramSocket();
        socket.setSoTimeout(getTimeout());
    }
    catch (SocketException e) {
        throw new ModbusInitException(e);
    }
    initialized = true;
}
 
Example 13
Source File: RUDPClient.java    From jRUDP with MIT License 4 votes vote down vote up
public void connect() throws SocketTimeoutException, SocketException, UnknownHostException, IOException, InstantiationException, IllegalAccessException{
	System.out.println("[RUDPClient] Connecting to UDP port "+port+"...");
	if(state == ConnectionState.STATE_CONNECTED){System.out.println("[RUDPClient] Client already connected !");return;}
	if(state == ConnectionState.STATE_CONNECTING){System.out.println("[RUDPClient] Client already connecting !");return;}
	if(state == ConnectionState.STATE_DISCONNECTING){System.out.println("[RUDPClient] Client currently disconnecting !");return;}
	
	if(packetHandlerClass == null) throw new IOException("Unable to connect without packet handler");
	packetHandler = packetHandlerClass.newInstance();
	packetHandler.rudp = this;

	socket = new DatagramSocket();
	socket.setSoTimeout(RUDPConstants.CLIENT_TIMEOUT_TIME);

	lastPacketReceiveTime = System.currentTimeMillis();

	state = ConnectionState.STATE_CONNECTING;
	try {
		//Send handshake packet
		byte[] handshakePacket = new byte[9];
		handshakePacket[0] = RUDPConstants.PacketType.HANDSHAKE_START;
		NetUtils.writeBytes(handshakePacket, 1, RUDPConstants.VERSION_MAJOR);
		NetUtils.writeBytes(handshakePacket, 5, RUDPConstants.VERSION_MINOR);
		sendPacketRaw(handshakePacket);

		//Receive handshake response packet
		byte[] buffer = new byte[8196];
		DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length, address, port);
		socket.receive(datagramPacket);
		byte[] data = new byte[datagramPacket.getLength()];
		System.arraycopy(datagramPacket.getData(), datagramPacket.getOffset(), data, 0, datagramPacket.getLength());

		//Handle handshake response packet
		if(data[0] != RUDPConstants.PacketType.HANDSHAKE_OK){

			state = ConnectionState.STATE_DISCONNECTED;
			byte[] dataText = new byte[data.length-1];
			System.arraycopy(data, 1, dataText, 0, dataText.length);
			throw new IOException("Unable to connect: "+new String(dataText, "UTF-8"));

		}
		else{

			state = ConnectionState.STATE_CONNECTED;
			initReceiveThread();
			initPingThread();
			initRelyThread();

			reliableThread.start();
			receiveThread.start();
			pingThread.start();

			System.out.println("[RUDPClient] Connected !");

		}
	} catch (IOException e) {
		state = ConnectionState.STATE_DISCONNECTED;
		throw e;
	}
}
 
Example 14
Source File: UDPChecker.java    From pinpoint with Apache License 2.0 4 votes vote down vote up
private DatagramSocket createSocket() throws IOException {
    DatagramSocket socket = new DatagramSocket();

    socket.setSoTimeout(3000);
    return socket;
}
 
Example 15
Source File: DiscoveryTest.java    From freeacs with MIT License 4 votes vote down vote up
private void test3()
    throws UtilityException, SocketException, UnknownHostException, IOException,
        MessageAttributeParsingException, MessageAttributeException,
        MessageHeaderParsingException {
  int timeSinceFirstTransmission = 0;
  int timeout = timeoutInitValue;
  do {
    try {
      // Test 3 including response
      DatagramSocket sendSocket = new DatagramSocket(new InetSocketAddress(iaddress, 0));
      sendSocket.connect(InetAddress.getByName(stunServer), port);
      sendSocket.setSoTimeout(timeout);

      MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest);
      sendMH.generateTransactionID();

      ChangeRequest changeRequest = new ChangeRequest();
      changeRequest.setChangePort();
      sendMH.addMessageAttribute(changeRequest);

      byte[] data = sendMH.getBytes();
      DatagramPacket send = new DatagramPacket(data, data.length);
      sendSocket.send(send);
      LOGGER.debug("Test 3: Binding Request sent.");

      int localPort = sendSocket.getLocalPort();
      InetAddress localAddress = sendSocket.getLocalAddress();

      sendSocket.close();

      DatagramSocket receiveSocket = new DatagramSocket(localPort, localAddress);
      receiveSocket.connect(InetAddress.getByName(stunServer), ca.getPort());
      receiveSocket.setSoTimeout(timeout);

      MessageHeader receiveMH = new MessageHeader();
      while (!receiveMH.equalTransactionID(sendMH)) {
        DatagramPacket receive = new DatagramPacket(new byte[200], 200);
        receiveSocket.receive(receive);
        receiveMH = MessageHeader.parseHeader(receive.getData());
        receiveMH.parseAttributes(receive.getData());
      }
      ErrorCode ec =
          (ErrorCode)
              receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode);
      if (ec != null) {
        di.setError(ec.getResponseCode(), ec.getReason());
        LOGGER.debug("Message header contains an Errorcode message attribute.");
        return;
      }
      if (nodeNatted) {
        di.setRestrictedCone();
        LOGGER.debug("Node is behind a restricted NAT.");
        return;
      }
    } catch (SocketTimeoutException ste) {
      if (timeSinceFirstTransmission < 7900) {
        LOGGER.debug("Test 3: Socket timeout while receiving the response.");
        timeSinceFirstTransmission += timeout;
        int timeoutAddValue = timeSinceFirstTransmission * 2;
        if (timeoutAddValue > 1600) {
          timeoutAddValue = 1600;
        }
        timeout = timeoutAddValue;
      } else {
        LOGGER.debug(
            "Test 3: Socket timeout while receiving the response. Maximum retry limit exceed. Give up.");
        di.setPortRestrictedCone();
        LOGGER.debug("Node is behind a port restricted NAT.");
        return;
      }
    }
  } while (true);
}
 
Example 16
Source File: DiscoveryTest.java    From freeacs with MIT License 4 votes vote down vote up
private boolean test2()
    throws UtilityException, SocketException, UnknownHostException, IOException,
        MessageAttributeParsingException, MessageAttributeException,
        MessageHeaderParsingException {
  int timeSinceFirstTransmission = 0;
  int timeout = timeoutInitValue;
  do {
    try {
      // Test 2 including response
      DatagramSocket sendSocket = new DatagramSocket(new InetSocketAddress(iaddress, 0));
      sendSocket.connect(InetAddress.getByName(stunServer), port);
      sendSocket.setSoTimeout(timeout);

      MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest);
      sendMH.generateTransactionID();

      ChangeRequest changeRequest = new ChangeRequest();
      changeRequest.setChangeIP();
      changeRequest.setChangePort();
      sendMH.addMessageAttribute(changeRequest);

      byte[] data = sendMH.getBytes();
      DatagramPacket send = new DatagramPacket(data, data.length);
      sendSocket.send(send);
      LOGGER.debug("Test 2: Binding Request sent.");

      int localPort = sendSocket.getLocalPort();
      InetAddress localAddress = sendSocket.getLocalAddress();

      sendSocket.close();

      DatagramSocket receiveSocket = new DatagramSocket(localPort, localAddress);
      receiveSocket.connect(ca.getAddress().getInetAddress(), ca.getPort());
      receiveSocket.setSoTimeout(timeout);

      MessageHeader receiveMH = new MessageHeader();
      while (!receiveMH.equalTransactionID(sendMH)) {
        DatagramPacket receive = new DatagramPacket(new byte[200], 200);
        receiveSocket.receive(receive);
        receiveMH = MessageHeader.parseHeader(receive.getData());
        receiveMH.parseAttributes(receive.getData());
      }
      ErrorCode ec =
          (ErrorCode)
              receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode);
      if (ec != null) {
        di.setError(ec.getResponseCode(), ec.getReason());
        LOGGER.debug("Message header contains an Errorcode message attribute.");
        return false;
      }
      if (!nodeNatted) {
        di.setOpenAccess();
        LOGGER.debug(
            "Node has open access to the Internet (or, at least the node is behind a full-cone NAT without translation).");
      } else {
        di.setFullCone();
        LOGGER.debug("Node is behind a full-cone NAT.");
      }
      return false;
    } catch (SocketTimeoutException ste) {
      if (timeSinceFirstTransmission < 7900) {
        LOGGER.debug("Test 2: Socket timeout while receiving the response.");
        timeSinceFirstTransmission += timeout;
        int timeoutAddValue = timeSinceFirstTransmission * 2;
        if (timeoutAddValue > 1600) {
          timeoutAddValue = 1600;
        }
        timeout = timeoutAddValue;
      } else {
        LOGGER.debug(
            "Test 2: Socket timeout while receiving the response. Maximum retry limit exceed. Give up.");
        if (!nodeNatted) {
          di.setSymmetricUDPFirewall();
          LOGGER.debug("Node is behind a symmetric UDP firewall.");
          return false;
        } else {
          // not is natted
          // redo test 1 with address and port as offered in the changed-address message attribute
          return true;
        }
      }
    }
  } while (true);
}
 
Example 17
Source File: NameServerProxy.java    From big-c with Apache License 2.0 4 votes vote down vote up
public static NameServerProxy locateNS(String host, int port, byte[] hmacKey) throws IOException {
	if(host!=null) {
		if(port==0)
			port=Config.NS_PORT;
		NameServerProxy proxy=new NameServerProxy(host, port);
		proxy.pyroHmacKey = hmacKey;
		proxy.ping();
		return proxy;
	}
	if(port==0)
		port=Config.NS_BCPORT;
	DatagramSocket udpsock=new DatagramSocket();
	udpsock.setSoTimeout(3000);
	udpsock.setBroadcast(true);
	byte[] buf="GET_NSURI".getBytes();
	if(host==null)
		host="255.255.255.255";
	InetAddress address=InetAddress.getByName(host);
	DatagramPacket packet=new DatagramPacket(buf, buf.length, address, port);
	udpsock.send(packet);
	
	DatagramPacket response=new DatagramPacket(new byte[100], 100);
	try
	{
		udpsock.receive(response);
	}
	catch(SocketTimeoutException x)
	{
		// try localhost explicitly (if host wasn't localhost already)
		if(!host.startsWith("127.0") && !host.equals("localhost"))
			return locateNS("localhost", Config.NS_PORT, hmacKey);
		else
			throw x;
	}
	finally {
		udpsock.close();
	}
	String location=new String(response.getData(), 0, response.getLength());
	NameServerProxy nsp = new NameServerProxy(new PyroURI(location));
	nsp.pyroHmacKey = hmacKey;
	return nsp;
}
 
Example 18
Source File: UDPBurstTask.java    From Mobilyzer with Apache License 2.0 4 votes vote down vote up
/**
 * Receive a response from the server after the burst of uplink packets was sent, parse it, and
 * return the number of packets the server received.
 * 
 * @param sock the socket used to receive the server's response
 * @return the number of packets the server received
 * 
 * @throws MeasurementError if an error or a timeout occurs
 */
private UDPResult recvUpResponse(DatagramSocket sock) throws MeasurementError {
  UDPBurstDesc desc = (UDPBurstDesc) measurementDesc;

  UDPResult udpResult = new UDPResult();
  // Receive response
  Logger.i("Waiting for UDP response from " + desc.target + ": " + targetIp);

  byte buffer[] = new byte[UDPBurstTask.MIN_PACKETSIZE];
  DatagramPacket recvpacket = new DatagramPacket(buffer, buffer.length);

  if (stopFlag) {
    throw new MeasurementError("Cancelled");
  }

  try {
    sock.setSoTimeout(RCV_UP_TIMEOUT);
    sock.receive(recvpacket);
  } catch (SocketException e1) {
    sock.close();
    throw new MeasurementError("Timed out reading from " + desc.target);
  } catch (IOException e) {
    sock.close();
    throw new MeasurementError("Error reading from " + desc.target);
  }
  // Reconstruct UDP packet from flattened network data
  UDPPacket responsePacket = new UDPPacket(recvpacket.getData());
  dataConsumed+=recvpacket.getLength();

  if (responsePacket.type == PKT_RESPONSE) {
    // Received seq number must be same with client seq
    if (responsePacket.seq != seq) {
      Logger.e("Error: Server send response packet with different seq, old " + seq + " => new "
          + responsePacket.seq);
    }

    Logger.i("Recv UDP resp from " + desc.target + " type:" + responsePacket.type + " burst:"
        + responsePacket.burstCount + " pktnum:" + responsePacket.packetNum
        + " out_of_order_num: " + responsePacket.outOfOrderNum + " jitter: "
        + responsePacket.timestamp);

    udpResult.packetCount = responsePacket.packetNum;
    udpResult.outOfOrderRatio = (double) responsePacket.outOfOrderNum / responsePacket.packetNum;
    udpResult.jitter = responsePacket.timestamp;
    return udpResult;
  } else {
    throw new MeasurementError("Error: not a response packet! seq: " + seq);
  }
}
 
Example 19
Source File: SimpleRadiusConnection.java    From Open-Lowcode with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * @param userid user id for security check
 * @param otp    one time password
 * @return true if the authentication was confirmed, false else
 * @throws UnknownHostException         if the server is not known
 * @throws UnsupportedEncodingException if UTF-8 is not installed on the server
 * @throws IOException                  if anything bad happens and connection
 *                                      could not be retried
 */
public boolean checkOTP(String userid, String otp)
		throws UnknownHostException, UnsupportedEncodingException, IOException {
	RequestSummary requestsummary = generateRequestPacket(userid, otp);
	DatagramPacket reply = new DatagramPacket(new byte[MAX_PACKET_SIZE], MAX_PACKET_SIZE);

	DatagramSocket socket = new DatagramSocket();
	socket.setSoTimeout(TIMEOUT);
	int retrycount = 0;
	boolean success = false;
	while (retrycount <= RETRY & !success) {
		try {
			socket.send(requestsummary.getPayload());
			socket.receive(reply);
			success = true;
		} catch (IOException e) {
			logger.warning("Exception in communicating with Radius server "+e.getMessage());
			for (int i=0;i<e.getStackTrace().length;i++) logger.warning("   - "+e.getStackTrace()[i]);
			try {
				Thread.sleep(300);
			} catch (InterruptedException e1) {
				logger.warning("Interrupted Exception " + e1.getMessage());
			}
		}
	}
	socket.close();
	ByteArrayInputStream in = new ByteArrayInputStream(reply.getData());
	int responsetype = in.read() & 0x0ff;
	int serverid = in.read() & 0x0ff;
	int messagelength = (in.read() & 0x0ff) << 8 | (in.read() & 0x0ff);
	byte[] authenticator = new byte[16];
	byte[] attributepayload = new byte[messagelength - HEADER_LENGTH];
	in.read(authenticator);
	in.read(attributepayload);
	in.close();
	checkReplyAuthenticator(secret, responsetype, serverid, messagelength, attributepayload,
			requestsummary.getAuthenticator(), authenticator);
	if (responsetype == ACCESS_ACCEPT)
		return true;
	return false;

}
 
Example 20
Source File: UdpMessenger.java    From ipmilib with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Initiates UdpMessenger, binds it to the specified port and IP address and
 * starts listening.
 * 
 * @param port
 *            - port to bind socket to.
 * @param address
 *            - IP address to bind socket to.
 * @throws SocketException
 *             if the socket could not be opened, or the socket could not
 *             bind to the specified local port.
 */
public UdpMessenger(int port, InetAddress address) throws SocketException {
	this.port = port;
	listeners = new ArrayList<UdpListener>();
	bufferSize = DEFAULTBUFFERSIZE;
	socket = new DatagramSocket(this.port, address);
	socket.setSoTimeout(0);
	this.setDaemon(true);
	this.setName("IPMIListener" + address + ":" + socket.getLocalPort());
	this.start();
}