How to detect devices logging into a network? [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I was attempting to detect any device (desktop, mobile, tablet, etc.,) that logs into an enterprise network. This is a very dirty code I wrote. The code continuously checks for the connected devices and prints the new ones by checking against a set.
public class DeviceDetectAgent {
private static Set<String> connectedDevicesPast = new HashSet<String>();
private static void detectNewDevices() {
private Set<String> connectedDevicesPresent = new HashSet<String>(); // saves all devices detected in the previous poll
InetAddress localhost = InetAddress.getLocalHost();
byte[] iPAddress = localhost.getAddress();
for (int i=1; i<=254; i++) {
iPAddress[3] = (byte) i;
InetAddress inetAddress = InetAddress.getByAddress(iPAddress);
if (inetAddress.isReachable(1000)) {
String device = inetAddress.toString();
if (!connectedDevicesPast.contains(device)) {
System.out.println("New device " + device + "found.");
}
connectedDevicesPresent.add(device);
}
}
connectedDevicesPast = connectedDevicesPresent;
}
public static void main(String[] args) {
while (true) {
detectNewDevices();
Thread.sleep(1000);
}
}
}
My objective is to create an agent that detects a device logging into the network. Are there any improvements I can do in my code? I believe my code is too trivial.

Your solution has the following limitations.
First, device can close ICMP using its personal firewall. In this case it will not respond on ping and you will not see it.
Second, your solution is very slow. Ping may take a second, so you will spend ~4 minutes to complete your loop. Fortunately this problem can be fixed using NIO. Take a look on this code as an example or check other examples of asynchronous ping.
Fixing the first problem is not trivial. Generally you can think about 2 strategies:
try to discover device using other ports and protocols
try to catch device when it performs some kind of network activity.
Using other protocols is a bit complicated. Take a look on nmap - tool that already does this.
Catching other network activity can be done using PCAP or if you are implementing this in java JPCAP. You should however locate your spy in "correct" location in the network. The best is to use network mirroring.

Related

How to programmatically connect internet via datacard with AT commands?

I have a datacard ZTE MF190. I want to use AT commands to register in 2G or 3G and access internet via datacard. Found this article about how to make data call:
AT+cgatt=1
AT+CGDCONT=1,”IP”,”epc.tmobile.com” //I used my operator PDP context
AT+CGACT=1,1
But ping from OS terminal shows 100% package loss.
I've tried on Ubuntu 14 and Windows 7.
How can I connect internet with AT commands using datacard on Ubuntu?
UPDATE
I gave bounty to #tripleee's answer because it's more full than first one and answered all my questions. But I'm not satisfied with answers, so I'll answer my own question in a week.
In my answer I'll show how to handle this process with Java. So, please do not move this question to other Stack Exchange websites.
Creating a connection between the card and your provider is not sufficient. You need some mechanism for creating a network interface out of this connection, and set up your network stack to route packets over this interface.
Traditionally, the pppd daemon has been a popular choice for this task. You would create a "chat script" with the commands for establishing a data call (these days, pppd might come packaged with a suitable canned script) and the daemon would handle the entire process of placing the call, authenticating, setting up a network interface over the circuit, and configuring the system to route packets over it, as well as configuring DNS etc to use it for resolver queries, etc.
I tried to sniff USB port but on this case dashboard can not connect because of busy port
It is certainly possible. See this question
Found this article about how to make data call
What that article is about is how to set up the call, not how to make it.
After you made correct setup, connect to internet with this command:
ATD*99***1#
UPDATE1: After a bit of research I believe that article was written only to promote their software and has no practical use. In reality dialing is made with pppd or wvdial
UPDATE2: We discussed ways to solve the problem in a chat room (in Russian). It turned out cnetworkmanager will be the way to go
As far as I know wvdial uses ppp daemon to connect to the internet using modem. wvdial is preinstalled on desktop version of Ubuntu.
wvdial uses a config file located /etc/wvdial.conf. Let's edit this file. Type in your terminal
sudo nano /etc/wvdial.conf
and you will see something like this
[Dialer Defaults]
Init1 = ATZ
Init2 = ATQ0 V1 E1 S0=0 &C1 &D2
Stupid Mode = yes
ISDN = 0
Modem Type = Analog Modem
New PPPD = yes
Phone = *99#
Modem = /dev/ttyUSB2
Username = ''
Password = ''
Baud = 9600
Dial Timeout = 30
Dial Attempts = 3
Explanation of all keys you can find in wvdial.conf(5) - Linux man page. If you need to change your provider dial number, username, password or any other information about connection and device you can change file content and save it.
There are 3 serial ports for ZTE MF190. Normally it's ttyUSB0, ttyUSB1 and ttyUSB2. And in my case ttyUSB2 is for internet connection. It would not work on other ports. So you need to find the right serial port for your modem.
There is an automatic configurator which edits wvdial.conf file, sets serial port baud rate etc. Since it is not always configure correctly I would not recommend to use it:
sudo wvdialconf /etc/wvdial.conf
It would be better if you configure wvdial manually.
Now, when your device connected and wvdial configured to work with device, you can execute this line from terminal:
wvdial
You will see a lot of lines. But if you see those lines - you have succeeded.
local IP address XX.XX.XX.XX
remote IP address XX.XX.XX.XX
primary DNS address XX.XX.XX.XX
secondary DNS address XX.XX.XX.XX
Now, how we can use it in programming? I'll provide some code to work with it on Java. You can use this code to dial.
public int dialer() {
// status for debug. If status == 4 then you connected successfully
int status;
// create process of wvdial
ProcessBuilder builder = new ProcessBuilder("wvdial");
try {
// start wvdial
final Process process = builder.start();
// wvdial listener thread
final Thread ioThread = new Thread() {
#Override
public void run() {
try {
final BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getErrorStream()));
// wvdial output line
String line;
while ((line = reader.readLine()) != null) {
// if "local IP address" line detected set status 1
if (line.contains("local IP address")) {
status = 1;
}
if (line.contains("remote IP address")) {
status = 2;
}
if (line.contains("primary DNS address")) {
status = 3;
}
if (line.contains("secondary DNS address")) {
status = 4;
}
}
reader.close();
} catch (final Exception e) {
}
}
};
// start listener
ioThread.start();
// wait 6 secs and return status. Some kind of timeout
Thread.sleep(6000);
} catch (Exception e) {
}
return status;
}
And here is a disconnector method. All you need is to kill wvdial process and thread will be destroyed:
public boolean disconnect() {
ProcessBuilder builder = new ProcessBuilder("pkill", "wvdial");
try {
builder.start();
return true;
} catch (IOException e) {
return false;
}
}

How to check Internet Access is Available in Android [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I want make a application that work with Internet and a Server and Web service, I create a method to check network available, I use bellow method:
private boolean isNetworkConnect() {
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netinfo = cm.getActiveNetworkInfo();
if (netinfo != null && netinfo.isConnected()) {
netType = netinfo.getTypeName();
return true;
} else {
return false;
}
}
This method just specify that WiFi of Mobile network in Android is Enable or Disable, But this is not sufficient to Internet Access, because if I disable my Laptop WiFi, but my android app in Emulator said Internet in Access because WiFi or Mobile Network is Enable, But if open browser and search any sites is not Access.!
I How to check internet access, that I search on browser, read from server and others. What is best solution ?
Your code is looking good. I already using this code on my own app.
This problem comes because you are using emulator for test your app.
If you test your app on real device isConnected() method work correctly.
If you want to get false return for your isNetworkConnect() method on emulator go to
Settings > Wireless & network > Mobile network And uncheck "Data enabled"
Your approach is generally what is used for isOnline method. It does not work by sending packets, thereby verifying connectivity. Its based on the state i.e., whether you are connected to WiFi or Mobile network. Now, as in your case, there may not be any actual connectivity.
To specifically answer your question, this is the best you could do. However, it does not ensure real connectivity.
Try This(edit as you want)
public void testURL() throws Exception {
String strUrl = "http://stackoverflow.com/about";
try {
URL url = new URL(strUrl);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.connect();
assertEquals(HttpURLConnection.HTTP_OK, urlConn.getResponseCode());
} catch (IOException e) {
System.err.println("Error creating HTTP connection");
e.printStackTrace();
throw e;
}
}

Getting IP in Java [duplicate]

This question already has answers here:
Getting the IP address of the current machine using Java
(19 answers)
Closed 9 years ago.
What is the best way to get IP address in Java? I was trying getLocalHost(), but it returns my computer IP addrees. I want something like this.
Also I was trying to get IP by HTML from services like that, but I think it's not good idea.
The following uses Amazon web services and works for me.
import java.net.*;
import java.io.*;
public class IPTest{
public static void main(String args[]) throws Exception{
URL whatismyip = new URL("http://checkip.amazonaws.com/");
BufferedReader in = new BufferedReader(new InputStreamReader(
whatismyip.openStream()));
String ip = in.readLine(); //you get the IP as a String
System.out.println("My IP address:"+ip);
}
}
You want to get your internet (someone will call public, I don't totally agree on that term) ip address. Basically you have two options, or call an external service (it does not need to be a site like that, it can be a STUN, or anything made for that), or you can get it from your modem/router/NAT.
You could use UPnP if enabled in the device, this is a good approach.
Other option is instead of trying to parse or get the results from an external service,
you get it from your device web page, some devices even not need admin rights to get that information, so you only need to parse the page for the information.
Most of the answers just say you to use an external service, like you said its not a good idea. In my opniation its not the best one, because you be dependent on an external service provider. If it changes anything you need to change too, as if they get the service broken.
So, if you can implement in your own LAN its better, just not easier.

How to control the handset using AT commands in java

I know that by using AT commands we can control the handset.As example unlocking screen we can give a specific AT command or moving right to the menu or left or bottom or up we can give specific AT commands. What all are the AT commands for doing this kind of control.
Thank you.
From what I understand, the AT commands are more used for phone-type functions (making calls, or sending SMS, etc), rather than menu navigation, etc.
I'm not entirely sure if that was your end-goal after menu navigation, but you can find more details here: http://en.wikipedia.org/wiki/Hayes_command_set (the original +AT command set)
If you wanted to send SMS from a handset connected to your computer you might want to take a peek at this page: http://www.developershome.com/sms/atCommandsIntro.asp
If you wanted more control when performing functions, like sending SMS, etc, you might want to investigate "PDU Mode."
It is entirely possible that some handset manufacturers may have implemented additional +AT commands to allow other functions to be performed, so you might do better by specifically searching for the commands related to the handset you are using.
(Of course, if you're having issues connecting to the handset hardware itself, you need to ensure you have either the javax.comm extension or some favoured Java USB API installed)
If post doesn't help, perhaps you could provide more details in your question? (eg. what you are ultimately trying to do, if you think it would help)
List of AT commands
sample java code to use AT command
public void servicesDiscovered(int transID, ServiceRecord serviceRecord[])
{
String url = serviceRecord[0].getConnectionURL(1, false);
try
{
//ClientSession conn= (ClientSession)Connector.open(url);
StreamConnection meineVerbindung = (StreamConnection) Connector.open(url);
if(conn== null)
System.out.println("Kann Service URL nicht oeffnen\n");
else
{
OutputStream out = conn.openOutputStream();
InputStream in = conn.openInputStream();
String message = "AT+CGMI\r\n";
// send AT-command
System.out.println("send AT Comand request: "+message);
out.write(message.getBytes());
out.flush();
out.close();
byte buffer[] = new byte[10000];
// read the response from mobile phone
in.read(buffer);
System.out.println("AT Comand response: "+buffer.toString());}
}
catch(IOException e)
{
System.out.println("Service Error(3): "+e.getMessage());
}
}

How can I emulate a COM port, write data to it and read data from it?

I'm trying to test my code that reads from a USB port (COM25 when the device is connected) that is created when a device is connected to my computer and to a boat. I cannot power the USB device when not on the boat so testing is difficult. Can someone let me know how to simulate a COM port and write data to it so my test program is able to connect to that simulated COM port and read that data?
I'm reading this from a Java program but the simulation doesn't need to be in Java or any specific language. Just a program that will simulate the COM port and allow me to connect to it. I downloaded a COM port emulator from AGG Software and it appears that it's writing to what I deem COM25 but I'm not able to connect to it from my Java test.
The general answer for this kind of problem is to wrap the code that talks to the COM port in a class that implements an interface. If you do this as a Facade (pattern) then you can also make the COM methods you call sensible from your end.
The interface can then be mocked or faked for the test. (There is a great article on test objects, but I haven't been able to find it yet.) One advantage here is that you can create a fake version that throws exceptions or otherwise does things that are possible for the port to do but hard to get it to do in practice.
Where I work, we solved a similar issue by having our emulator not spoof a COM port at all. Here's how you can do it:
Define an interface for talking with your COM port, something like IUsbCommService
Implement your real COM-communcation service, using the standard Java Comm API
For your emulator, simply kick of a thread that spits out the same sort of data you can expect from your USB device at regular intervals.
Use your IOC framework of choice (e.g., Spring) to wire up either the emulator or the real service.
As long as you hide your implementation logic appropriately, and as long as you code to your interface, your service-consumer code won't care whether it's talking to the real USB device or to the emulator.
For example:
import yourpackage.InaccessibleDeviceException;
import yourpackage.NoDataAvailableException;
public interface IUsbProviderService {
public void initDevice() throws InaccessibleDeviceException;
public UsbData getUsbData()
throws InaccessibleDeviceException, NoDataAvailableException;
}
// The real service
import javax.comm.SerialPort; //....and the rest of the java comm API
public class UsbService implements IUsbProviderService {
.
.
.
}
// The emulator
public class UsbServiceEmulator implements IUsbProviderService {
private Thread listenerThread;
private static final Long WAITTIMEMS = 10L;
private String usbData;
public UsbServiceEmulator(long maxWaitTime) throws InaccessibleDeviceException{
initialize();
boolean success = false;
long slept = 0;
while (!success && slept < maxWaitTime) {
Thread.sleep(WAITTIMEMS);
slept += WAITTIMEMS;
}
}
private void initialize() throws InaccessibleDeviceException{
listenerThread = new Thread();
listenerThread.start();
}
private class UsbRunner implements Runnable {
private String[] lines = {"Data line 1", "Data line 2", "Data line 3"};
public void run() {
int line = 0;
while(true) {
serialEvent(lines[line]);
if(line == 3) {
line = 0;
} else {
line++;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
//handle the error
}
}
private void serialEvent(String line) {
if(/*you have detected you have enough data */) {
synchronized(this) {
usbData = parser.getUsbData();
}
}
}
}
Hope this helps!
Thanks to all the answers so far! Here's what I ended up doing as a result of recommendations from someone at work.
Downloaded the COM Port Data Emulator (CPDE) from AGG Software
Downloaded the Virtual Serial Port Driver (VSPD) from Eltima Software
(I just randomly picked a free data emulator and virtual serial port package. There are plenty of alternatives out there)
Using VSPD, created virtual serial ports 24 and 25 and connected them via a virtual null modem cable. This effectively creates a write port at 24 and a read port at 25.
Ran the CPDE, connected to 24 and started writing my test data.
Ran my test program, connected to 25 and was able to read the test data from it
There are plenty of relevant answers in this section. But as for me, I personally use Virtual Serial Port Driver, which works perfect for me. But I must admit that there are plenty alternatives when it comes to creating virtual ports: freevirtualserialports.com; comOcom to name a few. But I haven't got a chance to use them, so my recommendation for solving this problem is Virtual Serial Port Driver.
I recommend fabulatech's virtual modem.
Get it at http://www.virtual-modem.com
You might also want to get a COM port monitor for your tests - You can find it at
http://www.serial-port-monitor.com
Good luck with the boat! :)
I use com0com and it works great for what I need.
In addition all others, I would like to added this nice, free emulator https://sites.google.com/site/terminalbpp/ I do use. I do also use AGG Com port data emulator.

Categories

Resources