Java Code Examples for java.net.datagramsocket#receive()
The following examples show how to use
java.net.datagramsocket#receive() .
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: Network.java From OberonEmulator with ISC License | 6 votes |
public Network(InetSocketAddress addr) throws IOException { this.addr = addr; ds = new DatagramSocket(null); ds.setReuseAddress(true); ds.bind(new InetSocketAddress((InetAddress) null, addr.getPort())); Thread t = new Thread(new Runnable() { @Override public void run() { try { while (true) { byte[] buf = new byte[576]; DatagramPacket dp = new DatagramPacket(buf, buf.length); ds.receive(dp); if (dp.getLength() % 32 == 0) netQueue.put(dp); } } catch (Exception ex) { throw new RuntimeException(ex); } } }); t.setDaemon(true); t.start(); }
Example 2
Source File: TestBookKeeperServer.java From rubix with Apache License 2.0 | 6 votes |
/** * Check if StatsDReporter is correctly firing metrics. * * @param receivePort The port on which to receive responses from the mock StatsD server. * @return True if the mock StatsDReporter has received a response * @throws IOException if an I/O error occurs while waiting for a response. */ private boolean isStatsDReporterFiring(int receivePort) throws IOException { byte[] data = new byte[TEST_PACKET_SIZE]; DatagramSocket socket = new DatagramSocket(receivePort); DatagramPacket packet = new DatagramPacket(data, data.length); socket.setSoTimeout(TEST_SOCKET_TIMEOUT); try { socket.receive(packet); } catch (SocketTimeoutException e) { return false; } return true; }
Example 3
Source File: DatagramLogger.java From oodt with Apache License 2.0 | 6 votes |
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 4
Source File: QueryStatsdDClientTest.java From datawave with Apache License 2.0 | 6 votes |
public void run() { try { DatagramSocket serverSocket = new DatagramSocket(port); running = true; while (!stop) { byte[] receiveData = new byte[1024]; DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); int len = -1; for (int i = 0; len == -1 && i < receiveData.length; i++) { if (receiveData[i] == '\0') { len = i; } } String sentence = new String(receiveData, 0, (len == -1 ? receiveData.length : len)); messages.add(sentence); } } catch (IOException ioe) { exception = ioe; } running = false; }
Example 5
Source File: DiscoveryThread.java From LocalNetwork with MIT License | 6 votes |
@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 6
Source File: DiscoverySocketThread.java From LocalNetwork with MIT License | 5 votes |
@Override public void run() { try { int port = NetworkUtil.BASE_PORT; boolean portAvailable = false; do { if (NetworkUtil.available(port)) portAvailable = true; else port--; } while (!portAvailable); socket = new DatagramSocket(port, InetAddress.getByName("0.0.0.0")); socket.setBroadcast(true); while (true) { // Receive broadcast packet Log.d("USER", "Waiting for 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 7
Source File: BLDevice.java From broadlink-java-api with MIT License | 5 votes |
/** * Sends a compiled packet to a destination host and port, and receives a * datagram from the source port specified. * * @param sock * Uses an external socket * @param pkt * The compiled packet to be sent * @param destIpAddr * Destination IP address * @param destPort * Destination Port * @param timeout * Socket timeout. 0 will disable the timeout * @param bufSize * Receiving datagram's buffer size * @return The received datagram * @throws IOException * Thrown if socket timed out, cannot bind source IP and source * port, no permission, etc. */ public static DatagramPacket sendPkt(DatagramSocket sock, Packet pkt, InetAddress destIpAddr, int destPort, int timeout, int bufSize) throws IOException { String boundHost = null; if(sock.getInetAddress() == null) boundHost = "0.0.0.0"; else boundHost = sock.getInetAddress().getHostAddress(); log.debug("sendPkt - call with given sock for " + boundHost + " and port " + sock.getPort()); byte[] data = pkt.getData(); DatagramPacket sendpack = new DatagramPacket(data, data.length, destIpAddr, destPort); log.debug("snedPkt - data for length: " + data.length + " to: " + sendpack.getAddress().getHostAddress() + " for port: " + sendpack.getPort()); byte[] rece = new byte[bufSize]; DatagramPacket recepack = new DatagramPacket(rece, 0, rece.length); long startTime = System.currentTimeMillis(); long elapsed; while ((elapsed = System.currentTimeMillis() - startTime) < timeout) { try { sock.send(sendpack); sock.setSoTimeout(1000); sock.receive(recepack); break; } catch (SocketTimeoutException e) { if (elapsed > timeout) { break; } continue; } } log.debug("sendPkt - recv data bytes (" + recepack.getData().length +") after initial req: {}", DatatypeConverter.printHexBinary(recepack.getData())); recepack.setData(removeNullsFromEnd(recepack.getData(), 0)); return recepack; }
Example 8
Source File: UDPRelayServer.java From T0rlib4Android with Apache License 2.0 | 5 votes |
private void pipe(DatagramSocket from, DatagramSocket to, boolean out) throws IOException { final byte[] data = new byte[datagramSize]; final DatagramPacket dp = new DatagramPacket(data, data.length); while (true) { try { from.receive(dp); lastReadTime = System.currentTimeMillis(); if (auth.checkRequest(dp, out)) { to.send(dp); } } catch (final UnknownHostException uhe) { log.info("Dropping datagram for unknown host"); } catch (final InterruptedIOException iioe) { // log("Interrupted: "+iioe); // If we were interrupted by other thread. if (iddleTimeout == 0) { return; } // If last datagram was received, long time ago, return. final long timeSinceRead = System.currentTimeMillis() - lastReadTime; if (timeSinceRead >= iddleTimeout - 100) { return; } } dp.setLength(data.length); } }
Example 9
Source File: AdminApi.java From android with GNU General Public License v3.0 | 5 votes |
public Map perform(Map request) throws IOException { DatagramSocket socket = newSocket(); byte[] data = serialize(request); DatagramPacket dgram = new DatagramPacket(data, data.length, this.address, this.port); socket.send(dgram); DatagramPacket responseDgram = new DatagramPacket(new byte[DGRAM_LENGTH], DGRAM_LENGTH); socket.receive(responseDgram); socket.close(); Map response = parse(responseDgram.getData()); Log.i("cjdns_AdminAPI", "response: " + response.toString()); return response; }
Example 10
Source File: AcceptorTest.java From game-server with MIT License | 5 votes |
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 11
Source File: BroadcastDiscovery.java From scheduling with GNU Affero General Public License v3.0 | 5 votes |
/** * Starts a new thread to reply to broadcast discovery requests from nodes. * * @throws SocketException if cannot bind UDP socket * @throws UnknownHostException if cannot bind to 0.0.0.0 */ public void start() throws SocketException, UnknownHostException { broadcastSocket = new DatagramSocket(port, InetAddress.getByName("0.0.0.0")); broadcastSocket.setBroadcast(true); discoveryThread = new Thread(new Runnable() { @Override public void run() { for (;;) { try { DatagramPacket nodePacket = new DatagramPacket(new byte[0], 0); broadcastSocket.receive(nodePacket); byte[] urlAsBytes = url.getBytes(BroadcastDiscoveryClient.BROADCAST_ENCODING); DatagramPacket replyPacket = new DatagramPacket(urlAsBytes, urlAsBytes.length, nodePacket.getAddress(), nodePacket.getPort()); broadcastSocket.send(replyPacket); } catch (SocketException e) { if (needsToStop) { return; } else { logger.warn("Could not broadcast URL to node", e); } } catch (Exception e) { logger.warn("Could not broadcast URL to node", e); } } } }, "BroadcastDiscovery"); discoveryThread.start(); }
Example 12
Source File: Socks5UDPAssociateClient.java From sockslib with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws InterruptedException { DatagramSocket clientSocket = null; Socks5 proxy = new Socks5(new InetSocketAddress("localhost", 1080)); try { NetworkMonitor networkMonitor = new NetworkMonitor(); clientSocket = new Socks5DatagramSocket(proxy); clientSocket = new MonitorDatagramSocketWrapper(clientSocket, networkMonitor); String message = "I am client using SOCKS proxy"; byte[] sendBuffer = message.getBytes(); DatagramPacket packet = new DatagramPacket(sendBuffer, sendBuffer.length, new InetSocketAddress("localhost", 5050)); clientSocket.send(packet); //Received response message from UDP server. byte[] receiveBuf = new byte[100]; DatagramPacket receivedPacket = new DatagramPacket(receiveBuf, receiveBuf.length); clientSocket.receive(receivedPacket); String receiveStr = new String(receivedPacket.getData(), 0, receivedPacket.getLength()); System.out.println("received:" + receiveStr); System.out.println("UDP client information:"); System.out.println("Total Sent: " + networkMonitor.getTotalSend() + " bytes"); System.out.println("Total Received: " + networkMonitor.getTotalReceive() + " bytes"); System.out.println("Total: " + networkMonitor.getTotal() + " bytes"); } catch (IOException e) { e.printStackTrace(); } finally { ResourceUtil.close(clientSocket); } }
Example 13
Source File: BroadcastDiscoveryClient.java From scheduling with GNU Affero General Public License v3.0 | 5 votes |
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 14
Source File: NTPClient.java From swift-k with Apache License 2.0 | 5 votes |
/** * 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 15
Source File: myQQ.java From javaQQ with MIT License | 5 votes |
public void receive(String port) throws NumberFormatException, SocketException { ds1 = new DatagramSocket(Integer.parseInt(port)); thread = new Thread(new Runnable() { public void run() { byte buf[] = new byte[1024]; DatagramPacket dp = new DatagramPacket(buf,buf.length); while(true) { try { ds1.receive(dp); String message=new String(buf,0,dp.getLength()); if(message.charAt(0)=='$') { StringTokenizer x=new StringTokenizer(message,"$"); filename=x.nextToken(); filesize=x.nextToken(); panel.setfileinfo(filename, filesize); dlg.setVisible(true); } else showmessage.setText(showmessage.getText() + new String(buf,0,dp.getLength()) + "\r\n"); } catch(Exception e) { e.printStackTrace(); } } } } ); thread.start(); }
Example 16
Source File: UDPBurstTask.java From Mobilyzer with Apache License 2.0 | 4 votes |
/** * Receives a burst from the remote server and counts the number of packets that were received. * * @param sock the datagram socket that can be used to receive the server's burst * * @return the number of packets received from the server * @throws MeasurementError if an error occurs */ private UDPResult recvDownResponse(DatagramSocket sock) throws MeasurementError { int pktRecv = 0; UDPBurstDesc desc = (UDPBurstDesc) measurementDesc; // Receive response Logger.i("Waiting for UDP burst from " + desc.target); // Reconstruct UDP packet from flattened network data byte buffer[] = new byte[desc.packetSizeByte]; DatagramPacket recvpacket = new DatagramPacket(buffer, buffer.length); MetricCalculator metricCalculator = new MetricCalculator(desc.udpBurstCount); for (int i = 0; i < desc.udpBurstCount; i++) { if (stopFlag) { throw new MeasurementError("Cancelled"); } try { sock.setSoTimeout(RCV_DOWN_TIMEOUT); sock.receive(recvpacket); } catch (IOException e) { Logger.e("Timeout at round " + i); break; } UDPPacket dataPacket = new UDPPacket(recvpacket.getData()); dataConsumed+=recvpacket.getLength(); if (dataPacket.type == UDPBurstTask.PKT_DATA) { // Received seq number must be same with client seq if (dataPacket.seq != seq) { String err = "Server send data packets with different seq, old " + seq + " => new " + dataPacket.seq; Logger.e(err); throw new MeasurementError(err); } Logger.i("Recv UDP response from " + desc.target + " type:" + dataPacket.type + " burst:" + dataPacket.burstCount + " pktnum:" + dataPacket.packetNum + " timestamp:" + dataPacket.timestamp); pktRecv++; metricCalculator.addPacket(dataPacket.packetNum, dataPacket.timestamp); } else { throw new MeasurementError("Error closing input stream from " + desc.target); } } // for() UDPResult udpResult = new UDPResult(); udpResult.packetCount = pktRecv; udpResult.outOfOrderRatio = metricCalculator.calculateOutOfOrderRatio(); udpResult.jitter = metricCalculator.calculateJitter(); return udpResult; }
Example 17
Source File: UdpTest.java From gsc-core with GNU Lesser General Public License v3.0 | 4 votes |
public void discover() throws Exception { InetAddress server = InetAddress.getByName("127.0.0.1"); Node from = Node.instanceOf("127.0.0.1:10002"); Node peer1 = Node.instanceOf("127.0.0.1:10003"); Node peer2 = Node.instanceOf("127.0.0.1:10004"); Assert.assertTrue(!nodeManager.hasNodeHandler(peer1)); Assert.assertTrue(!nodeManager.hasNodeHandler(peer2)); Assert.assertTrue(nodeManager.getTable().getAllNodes().isEmpty()); PingMessage pingMessage = new PingMessage(from, nodeManager.getPublicHomeNode()); DatagramPacket pingPacket = new DatagramPacket(pingMessage.getSendData(), pingMessage.getSendData().length, server, port); FindNodeMessage findNodeMessage = new FindNodeMessage(from, Node.getNodeId()); DatagramPacket findNodePacket = new DatagramPacket(findNodeMessage.getSendData(), findNodeMessage.getSendData().length, server, port); DatagramSocket socket = new DatagramSocket(); // send ping msg socket.send(pingPacket); byte[] data = new byte[1024]; DatagramPacket packet = new DatagramPacket(data, data.length); boolean pingFlag = false; boolean pongFlag = false; boolean findNodeFlag = false; boolean neighborsFlag = false; while (true) { socket.receive(packet); byte[] bytes = Arrays.copyOfRange(data, 0, packet.getLength()); Message msg = Message.parse(bytes); Assert.assertTrue( Arrays.equals(msg.getFrom().getId(), nodeManager.getPublicHomeNode().getId())); if (!pingFlag) { pingFlag = true; Assert.assertTrue(msg instanceof PingMessage); Assert.assertTrue(Arrays.equals(((PingMessage) msg).getTo().getId(), from.getId())); PongMessage pongMessage = new PongMessage(from, msg.getTimestamp()); DatagramPacket pongPacket = new DatagramPacket(pongMessage.getSendData(), pongMessage.getSendData().length, server, port); socket.send(pongPacket); } else if (!pongFlag) { pongFlag = true; Assert.assertTrue(msg instanceof PongMessage); } else if (!findNodeFlag) { findNodeFlag = true; Assert.assertTrue(msg instanceof FindNodeMessage); List<Node> peers = Lists.newArrayList(peer1, peer2); NeighborsMessage neighborsMessage = new NeighborsMessage(from, peers, msg.getTimestamp()); DatagramPacket neighborsPacket = new DatagramPacket(neighborsMessage.getSendData(), neighborsMessage.getSendData().length, server, port); socket.send(neighborsPacket); socket.send(findNodePacket); } else if (!neighborsFlag) { Assert.assertTrue(msg instanceof NeighborsMessage); break; } } Assert.assertTrue(nodeManager.hasNodeHandler(peer1)); Assert.assertTrue(nodeManager.hasNodeHandler(peer2)); Assert.assertTrue(nodeManager.getTable().getAllNodes().size() == 1); socket.close(); }
Example 18
Source File: UDPBurstTask.java From Mobilyzer with Apache License 2.0 | 4 votes |
/** * 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: DiscoveryTest.java From freeacs with MIT License | 4 votes |
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 20
Source File: SimpleRadiusConnection.java From Open-Lowcode with Eclipse Public License 2.0 | 4 votes |
/** * @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; }