How to effectively ping and discover all clients on a network? - java

The problem I am having is acquiring all reachable clients on a network.The below method returns some clients when called. In most cases other android clients.However for the PC it fails when firewall is on.Is there a more effective way to get all clients in Java/android purely or will I need to use android NDK?Any help from experts in this domain will be appreciated.Thanks in advance.
/***
* ping_JavaStyle(final int j)
* uses multi threads to enhance performance
* while pinging from 0>j<=255
* #param j
*/
private void ping_JavaStyle(final int j)
{
new Thread(new Runnable() { // new thread for parallel execution
public void run() {
try {
String testIp = prefix + String.valueOf(j);
InetAddress address = InetAddress.getByName(testIp);
String output = address.toString().substring(1);
if (address.isReachable(3000)) {
System.out.println(output + " is on the network");
ipList.add(testIp);
} else {
if (retest(testIp, 139)) {
ipList.add(testIp);
} else {
System.out.println("Not Reachable: " + output);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}

After Researching some more, got this working.With help of this repo:https://github.com/stealthcopter/AndroidNetworkTools
Below code solves the problem:
** RunnableTask.Java
* Created by Kirk on 10/29/2017.
*/
public class RunnableTask implements Callable<Boolean> {
private String testIp = "";
private Boolean is_Reachable = false;
public RunnableTask(String testIp) {
this.testIp = testIp;
}
#Override
public Boolean call() throws Exception {
try {
PingResult pingResult = Ping.onAddress(this.testIp).setTimes(1).setTimeOutMillis(1500).doPing();
if (pingResult.isReachable) {
is_Reachable = true;
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
return is_Reachable;
}
}
And use in the caller method:
private static final int NTHREDS = 255;
//.......
ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
List<Future<Boolean>> thread_Values_list = new ArrayList<>();
for (int i = 1; i <= 255; i++) {
final int j = i;
try {
try {
String testIp = prefix + String.valueOf(j);
RunnableTask worker = new RunnableTask(testIp);
Future<Boolean> submit = executor.submit(worker);
thread_Values_list.add(submit);
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
}
}
for (Future<Boolean> finishedThread : thread_Values_list) {
String reachable_Ip = "";
try {
if (finishedThread.get()) {
reachable_Ip = prefix + String.valueOf(finishThread_counter);
ipList.add(reachable_Ip);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
finishThread_counter++;
}
executor.shutdown();
}

Related

Java Blocking Q test stops executing

I have the following test code for learning purposes, in which I am trying to run a producer and a consumer threads running endlessly on a blocking Q.
For some reason which I cannot understand, the output is as follows:
Produced 3001
Q puts 3001
put: Q size = 1
Produced 3002
Q puts 3002
put: Q size = 2
Q takes 3001
take: Q size = 1
Consumed 3001
The code is as follows:
#Getter #Setter #NoArgsConstructor
public class MyBlockingQ {
public BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(5);
public Integer take() {
try {
Integer i = queue.take();
System.out.println("Q takes " + i);
System.out.println("take: Q size = " + queue.size());
return i;
} catch (InterruptedException e) {
e.printStackTrace();
return null;
}
}
public void put(Integer produce) {
try {
System.out.println("Q puts " + produce);
queue.put(produce);
System.out.println("put: Q size = " + queue.size());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class MyProducer implements Runnable {
private final MyBlockingQ queue;
private Integer i = 3000;
public MyProducer(MyBlockingQ q) {
queue = q;
}
public void run() {
while (true) {
queue.put(produce());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Integer produce() {
i++;
System.out.println("Produced " + i);
return i;
}
}
public class MyConsumer implements Runnable {
private final MyBlockingQ queue;
public MyConsumer(MyBlockingQ q) {
queue = q;
}
public void run() {
while (true) {
consume(queue.take());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
void consume(Integer x) {
System.out.println("Consumed " + x);
}
}
#Test
public void testBlockingQ(){
MyBlockingQ q = new MyBlockingQ();
MyProducer p1 = new MyProducer(q);
MyConsumer c1 = new MyConsumer(q);
new Thread(p1).start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(c1).start();
}
I cannot understand why does the code stop executing after the last output line as shown above?
I am working with JavaSE-15 on latest VSCode.
Threads are terminated, when your test method reaches to the end. If you want your threads to run longer, you need to add more sleep time at the end of your test method.
#Test
public void testBlockingQ(){
MyBlockingQ q = new MyBlockingQ();
MyProducer p1 = new MyProducer(q);
MyConsumer c1 = new MyConsumer(q);
new Thread(p1).start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(c1).start();
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

Simple java bot telegram: messages in loop

I'm trying to make simple telegram bot on Java.
The question is: how can I receive messages in a loop, when the user typed /start? I have already some
#Override
public void onUpdateReceived(Update update) {
Message msg = update.getMessage();
String txt = msg.getText();
if (txt.equals("/start")) {
sendMsg(msg, "Привет, меня зовут бот " + name + "!");
showHelp(msg);
run(msg, update);
} else if (txt.equals("/help")) {
showHelp(msg);
}
}
Here's showhelp:
private void showHelp(Message msg) {
try {
String inAbout = ReadFile.readFileInString(this.about);
sendMsg(msg, inAbout);
} catch (Exception ex) {
ex.printStackTrace();
}
}
sendMsg:
private void sendMsg(Message msg, String text) {
SendMessage s = new SendMessage();
s.setChatId(msg.getChatId());
s.setText(text);
try {
execute(s);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
In Run I want to read questions from data and wait for users answer, check if correct and do it in loop. In the end show how many he answered correct.
public void run(Message msg, Update update) {
try {
List<String> data = ReadFile.readFileInList(this.getData());
List<String> dataAnswers = ReadFile.readFileInList(this.answers);
this.sizeOfAnswers = data.size();
for (int i = 0; i < data.size(); i++) {
String line = data.get(i);
sendMsg(msg, line);
String inAnswer = update.getMessage().getText();
String rAns = dataAnswers.get(i);
boolean flag = checkAnswer(inAnswer, rAns);
if (flag) {
this.currentUser.incrementScore();
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
String finalString = "Поздравляю, ты ответил на " + this.currentUser.getScore() + "/" + this.sizeOfAnswers
+ " вопросов!";
sendMsg(msg, finalString);
}
}
Also here is maybe some multi user problems. How should I do it? Now it's showing all questions in one second without waiting for an answer.
How it's working now

How can I use DigitalIn in ProcessImage - Modbus

I'm working on a modbus UDP implementation [ J2Mod(2.3.4) ] in Java. I have found almost no useful documentation. I have a boolean array like flags.
Slave will read it via SimpleProcessImage->DigitalIn
Slave will use that flags and change them
Then write it to SimpleProcessImage->DigitalOut in every 10 secs.
I need help on 1st step. When I use master.readCoils(i, 1) and master.writeCoils(i, true). It only use DigitalOut. It write to DigitalOut and read from DigitalOut.
for (int i = 0; i < interSize ; i++) {
SimpleDigitalOut dout = (SimpleDigitalOut) image.getDigitalOut(i);
dout.set(i%5==0);
image.setDigitalOut(i, dout);
}
If I change DigitalOut on slave side as shown above, I can get changed values through DigitalOut. But I need to use them both; DigitalOut and DigitalIn.
Here's my code for slave.
public class Slave {
private SimpleProcessImage image;
private ModbusSlave slave;
private int interSize = 62000;
int step;
public Slave(){
image = new SimpleProcessImage();
step=0;
for (int i = 0; i < interSize; i++) {
image.addDigitalOut(i, new SimpleDigitalOut(false));
image.addDigitalIn(i, new SimpleDigitalIn(false));
}
(new Timer()).scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
read();
write();
}
}, 0, 10000);
startServer();
}
private void read() {
System.out.print("Read In : ");
for (int i = 0; i < interSize; i++) {
System.out.print((image.getDigitalIn(i).isSet() ? 1 : 0) + " ");
}
System.out.print("Read Out: ");
for (int i = 0; i < interSize; i++) {
System.out.print((image.getDigitalOut(i).isSet() ? 1 : 0) + " ");
}
}
public void startServer() {
try {
slave = ModbusSlaveFactory.createUDPSlave(502);
slave.addProcessImage(0, image);
slave.open();
} catch (ModbusException e) {
e.printStackTrace();
}
}
}
Also here my client
public class Client {
private ModbusUDPMaster master;
int interSize = 62000 ;
Client() {
master = new ModbusUDPMaster("127.0.0.1", 502);
try {
master.connect();
} catch (Exception e) {
e.printStackTrace();
}
write();
while(true){
read();
}
}
public static void main(String... args) {
new Client();
}
private void write() {
for (int i = 0; i < interSize; i++) {
try {
master.writeCoil(i, i%3==0);
} catch (ModbusException e) {
e.printStackTrace();
}
}
}
private void read() {
try {
for (int i = 0; i < interSize; i++) {
System.out.print(master.readCoils(i, 1).toString());
}
} catch (ModbusException e) {
e.printStackTrace();
}
}
}
If anybody still looking for answer, as shown here, you can read DigitalIn via readInputDiscretes function.
Read Discretes
// master.readInputDiscretes(<discrete ref>, <count>); // Uses a UNIT ID of 1
master.readInputDiscretes(<unit id>, <discrete ref>, <count>);

How to handle wait() notify()?

Here I have two run methods which should synchronize each other.
Poller Class:
*/
public void run() {
int seqId = 0;
while(true) {
List<KpiMessage> list = null;
try{
if(!accumulator.isUsed){
try {
list = fullPoll(seqId);
if (!list.isEmpty()) {
seqId = list.get(0).getSequence();
accumulator.manageIngoing(list);
}
System.out.println("Updated");
wait();
} catch (Exception e1) {
e1.printStackTrace();
}
}
} catch (Exception e){
// TODO:
System.err.println(e.getMessage());
e.printStackTrace();
}
}
}
/**
* Method which defines polling of the database and also count the number of Queries
* #param lastSeq
* #return pojo col
* #throws Exception
*/
public List<KpiMessage> fullPoll(int lastSeq) throws Exception {
Statement st = dbConnection.createStatement();
System.out.println("Polling");
ResultSet rs = st.executeQuery("Select * from msg_new_to_bde where ACTION = 814 and
STATUS = 200 order by SEQ DESC");
List<KpiMessage> pojoCol = new ArrayList<KpiMessage>();
try {
while (rs.next()) {
KpiMessage filedClass = convertRecordsetToPojo(rs);
pojoCol.add(filedClass);
}
for (KpiMessage pojoClass : pojoCol) {
System.out.print(" " + pojoClass.getSequence());
System.out.print(" " + pojoClass.getTableName());
System.out.print(" " + pojoClass.getAction());
System.out.print(" " + pojoClass.getKeyInfo1());
System.out.print(" " + pojoClass.getKeyInfo2());
System.out.print(" "+ pojoClass.getStatus());
System.out.println(" " + pojoClass.getEntryTime());
}
} finally {
try {
st.close();
rs.close();
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
}
Processing and Updating Class:
public void run() {
while(true){
try {
while(!accumulator.isUsed)
{
try {
System.out.println("Waiting for new outgoingmessages");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Collection<KpiMessage> outgoingQueue = generate(accumulator.outgoingQueue);
accumulator.manageOutgoing(outgoingQueue, dbConnection);
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
}
}
}
I have a logical error:
The poller is polling not only for new messsage but also reads the DB again and again from the first.
Also Updates again and again.
How to solve this synchronization problem.
Alternatively you could use a BlockingQueue to transfer the data between threads.
See BlockingQueue for details.
// The end of the list.
private static final Integer End = -1;
static class Producer implements Runnable {
final Queue<Integer> queue;
private int i = 0;
public Producer(Queue<Integer> queue) {
this.queue = queue;
}
#Override
public void run() {
try {
for (int i = 0; i < 1000; i++) {
queue.add(i++);
Thread.sleep(1);
}
// Finish the queue.
queue.add(End);
} catch (InterruptedException ex) {
// Just exit.
}
}
}
static class Consumer implements Runnable {
final Queue<Integer> queue;
private int i = 0;
public Consumer(Queue<Integer> queue) {
this.queue = queue;
}
#Override
public void run() {
boolean ended = false;
while (!ended) {
Integer i = queue.poll();
if ( i != null ) {
ended = i == End;
System.out.println(i);
}
}
}
}
public void test() throws InterruptedException {
Queue queue = new LinkedBlockingQueue();
Producer p = new Producer(queue);
Consumer c = new Consumer(queue);
Thread pt = new Thread(p);
Thread ct = new Thread(c);
// Start it all going.
pt.start();
ct.start();
// Close it down
pt.join();
ct.join();
}
You should synchronize or rather hold the lock or monitor for the object that you are calling wait() or notify() on.
Here is what will help you : wait() throwing IllegalArgumentException
synchronized(lockObject){
lockObject.wait(); //you should hold the lock to be able to call wait()
}

Bluetooth OBEX FTP server on Android 2.X

I'm using the Bluecove library to devolep an Obex ftp client/server on android 2.X.
So far i managed to connect as a client from android to a pc.
I tried the bluecove example code for a server but doesn't work.
Is it possible to develop a server on android 2.X. Does any one have the code to do it.
Thank you.
public class OBEXServer implements Runnable {
private SessionNotifier serverConnection;
private boolean isStoped = false;
private boolean isRunning = false;
public final UUID OBEX_OBJECT_PUSH = new UUID(0x1105);
public static final String SERVER_NAME = "OBEX Object Push";
private UserInteraction interaction;
private OBEXServer(UserInteraction interaction) {
this.interaction = interaction;
}
public static OBEXServer startServer(UserInteraction interaction) {
OBEXServer srv = new OBEXServer(interaction);
Thread thread = new Thread(srv);
thread.start();
while (!srv.isRunning && !srv.isStoped) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new Error(e);
}
}
if (!srv.isRunning) {
throw new Error("Can't start server");
}
return srv;
}
/*
* (non-Javadoc)
*
* #see java.lang.Runnable#run()
*/
public void run() {
isStoped = false;
LocalDevice localDevice;
try {
localDevice = LocalDevice.getLocalDevice();
if (!localDevice.setDiscoverable(DiscoveryAgent.GIAC)) {
Logger.error("Fail to set LocalDevice Discoverable");
}
serverConnection = (SessionNotifier) Connector.open("btgoep://localhost:" + OBEX_OBJECT_PUSH + ";name="
+ SERVER_NAME);
} catch (Throwable e) {
Logger.error("OBEX Server start error", e);
isStoped = true;
return;
}
try {
ServiceRecord record = localDevice.getRecord(serverConnection);
String url = record.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
Logger.debug("BT server url: " + url);
final int OBJECT_TRANSFER_SERVICE = 0x100000;
try {
record.setDeviceServiceClasses(OBJECT_TRANSFER_SERVICE);
} catch (Throwable e) {
Logger.debug("setDeviceServiceClasses", e);
}
DataElement bluetoothProfileDescriptorList = new DataElement(DataElement.DATSEQ);
DataElement obbexPushProfileDescriptor = new DataElement(DataElement.DATSEQ);
obbexPushProfileDescriptor.addElement(new DataElement(DataElement.UUID, OBEX_OBJECT_PUSH));
obbexPushProfileDescriptor.addElement(new DataElement(DataElement.U_INT_2, 0x100));
bluetoothProfileDescriptorList.addElement(obbexPushProfileDescriptor);
record.setAttributeValue(0x0009, bluetoothProfileDescriptorList);
final short ATTR_SUPPORTED_FORMAT_LIST_LIST = 0x0303;
DataElement supportedFormatList = new DataElement(DataElement.DATSEQ);
// any type of object.
supportedFormatList.addElement(new DataElement(DataElement.U_INT_1, 0xFF));
record.setAttributeValue(ATTR_SUPPORTED_FORMAT_LIST_LIST, supportedFormatList);
final short UUID_PUBLICBROWSE_GROUP = 0x1002;
final short ATTR_BROWSE_GRP_LIST = 0x0005;
DataElement browseClassIDList = new DataElement(DataElement.DATSEQ);
UUID browseClassUUID = new UUID(UUID_PUBLICBROWSE_GROUP);
browseClassIDList.addElement(new DataElement(DataElement.UUID, browseClassUUID));
record.setAttributeValue(ATTR_BROWSE_GRP_LIST, browseClassIDList);
localDevice.updateRecord(record);
} catch (Throwable e) {
Logger.error("Updating SDP", e);
}
try {
int errorCount = 0;
int count = 0;
isRunning = true;
while (!isStoped) {
RequestHandler handler = new RequestHandler();
try {
count++;
Logger.debug("Accepting OBEX connections");
handler.connectionAccepted(serverConnection.acceptAndOpen(handler));
} catch (InterruptedIOException e) {
isStoped = true;
break;
} catch (Throwable e) {
if ("Stack closed".equals(e.getMessage())) {
isStoped = true;
}
if (isStoped) {
return;
}
errorCount++;
Logger.error("acceptAndOpen ", e);
continue;
}
errorCount = 0;
}
} finally {
close();
Logger.debug("OBEX Server finished!");
isRunning = false;
}
}
public void close() {
isStoped = true;
try {
if (serverConnection != null) {
serverConnection.close();
}
Logger.debug("OBEX ServerConnection closed");
} catch (Throwable e) {
Logger.error("OBEX Server stop error", e);
}
}
private static File homePath() {
String path = "bluetooth";
boolean isWindows = false;
String sysName = System.getProperty("os.name");
if (sysName != null) {
sysName = sysName.toLowerCase();
if (sysName.indexOf("windows") != -1) {
isWindows = true;
path = "My Documents";
}
}
File dir;
try {
dir = new File(System.getProperty("user.home"), path);
if (!dir.exists()) {
if (!dir.mkdirs()) {
throw new SecurityException();
}
}
} catch (SecurityException e) {
dir = new File(new File(System.getProperty("java.io.tmpdir"), System.getProperty("user.name")), path);
}
if (isWindows) {
dir = new File(dir, "Bluetooth Exchange Folder");
}
if (!dir.exists()) {
if (!dir.mkdirs()) {
return null;
}
} else if (!dir.isDirectory()) {
dir.delete();
if (!dir.mkdirs()) {
return null;
}
}
return dir;
}
private void showStatus(final String message) {
interaction.showStatus(message);
}
private class RequestHandler extends ServerRequestHandler {
Timer notConnectedTimer = new Timer();
boolean isConnected = false;
boolean receivedOk = false;
Connection cconn;
void connectionAccepted(Connection cconn) {
Logger.debug("Received OBEX connection");
showStatus("Client connected");
this.cconn = cconn;
if (!isConnected) {
notConnectedTimer.schedule(new TimerTask() {
public void run() {
notConnectedClose();
}
}, 1000 * 30);
}
}
void notConnectedClose() {
if (!isConnected) {
Logger.debug("OBEX connection timeout");
try {
cconn.close();
} catch (IOException e) {
}
if (!receivedOk) {
showStatus("Disconnected");
}
}
}
public int onConnect(HeaderSet request, HeaderSet reply) {
isConnected = true;
notConnectedTimer.cancel();
Logger.debug("OBEX onConnect");
return ResponseCodes.OBEX_HTTP_OK;
}
public void onDisconnect(HeaderSet request, HeaderSet reply) {
Logger.debug("OBEX onDisconnect");
if (!receivedOk) {
showStatus("Disconnected");
}
}
public int onSetPath(HeaderSet request, HeaderSet reply, boolean backup, boolean create) {
Logger.debug("OBEX onSetPath");
return super.onSetPath(request, reply, backup, create);
}
public int onDelete(HeaderSet request, HeaderSet reply) {
Logger.debug("OBEX onDelete");
return super.onDelete(request, reply);
}
public int onPut(Operation op) {
Logger.debug("OBEX onPut");
try {
HeaderSet hs = op.getReceivedHeaders();
String name = (String) hs.getHeader(HeaderSet.NAME);
if (name != null) {
Logger.debug("name:" + name);
showStatus("Receiving " + name);
} else {
name = "xxx.xx";
showStatus("Receiving file");
}
Long len = (Long) hs.getHeader(HeaderSet.LENGTH);
if (len != null) {
Logger.debug("file lenght:" + len);
interaction.setProgressValue(0);
interaction.setProgressMaximum(len.intValue());
}
File f = new File(homePath(), name);
FileOutputStream out = new FileOutputStream(f);
InputStream is = op.openInputStream();
int received = 0;
while (!isStoped) {
int data = is.read();
if (data == -1) {
Logger.debug("EOS received");
break;
}
out.write(data);
received++;
if ((len != null) && (received % 100 == 0)) {
interaction.setProgressValue(received);
}
}
op.close();
out.close();
Logger.debug("file saved:" + f.getAbsolutePath());
showStatus("Received " + name);
receivedOk = true;
return ResponseCodes.OBEX_HTTP_OK;
} catch (IOException e) {
Logger.error("OBEX Server onPut error", e);
return ResponseCodes.OBEX_HTTP_UNAVAILABLE;
} finally {
Logger.debug("OBEX onPut ends");
interaction.setProgressDone();
}
}
public int onGet(Operation op) {
Logger.debug("OBEX onGet");
try {
HeaderSet hs = op.getReceivedHeaders();
String name = (String) hs.getHeader(HeaderSet.NAME);
return ResponseCodes.OBEX_HTTP_NOT_IMPLEMENTED;
} catch (IOException e) {
Logger.error("OBEX Server onGet error", e);
return ResponseCodes.OBEX_HTTP_UNAVAILABLE;
} finally {
Logger.debug("OBEX onGet ends");
}
}
public void onAuthenticationFailure(byte[] userName) {
Logger.debug("OBEX AuthFailure " + new String(userName));
}
}
}

Categories

Resources