I'm trying to make a project that must make me able to find local devices in same network and information regarding their IPs,mac addresses and vendors.Everything is good so far but question is I relaized that by this code ,it only discovers to mobile phones and somehow doesnt see my laptops ? I tested this code and it only shows my tablet and phones but no computers.If u have any suggestion pls let me now.Thanks in advance.And here is my code belove.
//This class is my pinger class
public class DiscoverRunner implements Runnable {
private List<InetAddress> results;
private String subnet;
private Integer startAdd;
private Integer numAdds;
public DiscoverRunner(String subnet, Integer start, Integer steps) {
this.subnet = subnet;
this.startAdd = start;
this.numAdds = steps;
results = new LinkedList<InetAddress>();
}
#Override
public void run() {
int timeout=4000;
for (int i=startAdd;i<startAdd+numAdds;i++){
String host=subnet +"." + i;
try {
InetAddress a = InetAddress.getByName(host);
if (a.isReachable(timeout)){
results.add(a);
//System.out.println(host + " is reachable");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public List<InetAddress> getResults(){
return results;
}
}
And here is my another class where i Handle threads to execute
public class Pinger {
private static final int NUMTHREADS = 254;
public static String myMacAddress = "";
public static ArrayList<Device> getDevicesOnNetwork(String subnet) throws IOException {
LinkedList<InetAddress> resAddresses = new LinkedList<InetAddress>();
DiscoverRunner[] tasks = new DiscoverRunner[NUMTHREADS];
Thread[] threads = new Thread[NUMTHREADS];
//Create Tasks and treads
for (int i = 0; i < NUMTHREADS; i++) {
tasks[i] = new DiscoverRunner(subnet,i,1);
threads[i] = new Thread(tasks[i]);
}
//Starts threads
for (int i = 0; i < NUMTHREADS; i++) {
threads[i].start();
}
for (int i = 0; i < NUMTHREADS; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < NUMTHREADS; i++) {
for (InetAddress a : tasks[i].getResults()) {
try {
a = InetAddress.getByName(a.getHostAddress());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
resAddresses.add(a);
}
}
ArrayList<Device> foundDev = new ArrayList<Device>(resAddresses.size());
for (InetAddress a : resAddresses) {
foundDev.add(new Device(a.getHostAddress(), getMacFromArpCache(a.getHostAddress()), a.getCanonicalHostName(), getVendorName(getMacFromArpCache(a.getHostAddress()))));
}
return foundDev;
}
/**
* Try to extract a hardware MAC address from a given IP address using the
* ARP cache (/proc/net/arp).<br>
* <br>
* We assume that the file has this structure:<br>
* <br>
* IP address HW type Flags HW address Mask Device
* 192.168.18.11 0x1 0x2 00:04:20:06:55:1a * eth0
* 192.168.18.36 0x1 0x2 00:22:43:ab:2a:5b * eth0
*
* #param ip
* #return the MAC from the ARP cache
*/
public static String getMacFromArpCache(String ip) {
if (ip == null) {
return null;
}
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("/proc/net/arp"));
String line;
while ((line = br.readLine()) != null) {
String[] splitted = line.split(" +");
if (splitted != null && splitted.length >= 4 && ip.equals(splitted[0])) {
// Basic sanity check
String mac = splitted[3];
if (mac.matches("..:..:..:..:..:..")) {
return mac;
} else {
return null;
}
}
}
return myMacAddress;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static String getVendorName(String MacAddress) throws IOException {
try {
URL url = new URL("http://api.macvendors.com/" + MacAddress);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
InputStream in = new BufferedInputStream(conn.getInputStream());
String vendorName = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
return vendorName;
} catch (MalformedURLException e) {
return null;
} catch (ProtocolException e) {
return null;
} catch (IOException e) {
return null;
}
}
}
this ping as you do on command line, maybe you can change your coding style.
try {
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("ping 192.168.0.142");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = input.readLine()) != null) {
System.out.println(line);
p.destroy();
break;
}
input.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Related
public class NewsServer {
Socket socket;
ArticleData ad;
DataType dt;
boolean isRecv = false;
DataOutputStream dos;
private static final int THREAD_CNT = 5;
private static ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_CNT, new ThreadFactory() {
#Override
public Thread newThread(Runnable r) {
Thread t = Executors.defaultThreadFactory().newThread(r);
t.setDaemon(true);
return t;
}
});
private static ExecutorService pollThreadPool = Executors.newSingleThreadExecutor();
public NewsServer() {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(7777);
while (true) {
socket = serverSocket.accept();
try {
threadPool.execute(new WriteThread(socket));
pollThreadPool.execute(new PollingThread(socket));
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException e) {
try {
serverSocket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
}
// polling
class PollingThread implements Runnable {
private Socket tsocket;
public PollingThread(Socket socket) {
this.tsocket = socket;
}
#Override
public void run() {
try {
DataOutputStream dos = new DataOutputStream(tsocket.getOutputStream());
ArticleData ads = new ArticleData(dos);
while (!tsocket.isClosed()) {
ads.sendPolling();
Thread.sleep(Constant.POLLING_INTERVAL);
}
} catch (SocketException e) {
try {
tsocket.close();
} catch (IOException ie) {
ie.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
try {
tsocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// send news
class WriteThread implements Runnable {
private Socket tsocket = null;
private boolean readySend = true;
private boolean doSend = true;
public WriteThread(Socket socket) {
this.tsocket = socket;
}
#Override
public void run() {
int dataTypeDiv = 0;
try {
DataOutputStream dos = new DataOutputStream(tsocket.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(tsocket.getInputStream()));
NewsDataFile newsDataFile = null;
StringBuffer bodyBuffer = new StringBuffer();
while (true) {
if (doSend) {
newsDataFile = sendNewsData(dos);
doSend = false;
}
try {
int readByteCount = br.read();
if (readByteCount == DataType.STX) {
doSend = false;
} else if (readByteCount == DataType.ETX) {
if (dataTypeDiv == DataType.ACK) {
doSend = true;
if (newsDataFile != null) {
newsDataFile.removeNewsData();
}
} else if (dataTypeDiv == DataType.NAK) {
doSend = true;
}
} else if (readByteCount == DataType.ACK) {
dataTypeDiv = readByteCount;
} else if (readByteCount == DataType.NAK) {
dataTypeDiv = readByteCount;
} else {
bodyBuffer.append(readByteCount);
doSend = false;
}
} catch (IOException e) {
readySend = true;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
tsocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* #param dos
* #throws Exception
* #throws ParseException
* #throws IOException
*/
private NewsDataFile sendNewsData(DataOutputStream dos) throws Exception, ParseException, IOException {
String jsonNewsData = null;
NewsDataFile newsDataFile = new NewsDataFile();
while (true) {
jsonNewsData = newsDataFile.getJsonNewsData();
if (jsonNewsData != null) {
JSONParser jsonParse = new JSONParser();
JSONObject articleObject = (JSONObject) jsonParse.parse(jsonNewsData);
String status = (String) articleObject.get("status");
String sn = (String) articleObject.get("sn");
String code = (String) articleObject.get("code");
String wdate = (String) articleObject.get("wdate");
String sdate = (String) articleObject.get("sdate");
String cate = (String) articleObject.get("cate");
String title = (String) articleObject.get("title");
String reporter = (String) articleObject.get("reporter");
String stockcd1 = (String) articleObject.get("stockcd1");
String stockcd2 = (String) articleObject.get("stockcd2");
String stockcd3 = (String) articleObject.get("stockcd3");
String stockcd4 = (String) articleObject.get("stockcd4");
String stockcd5 = (String) articleObject.get("stockcd5");
String stockcd6 = (String) articleObject.get("stockcd6");
String stockcd7 = (String) articleObject.get("stockcd7");
String stockcd8 = (String) articleObject.get("stockcd8");
String prepare1 = (String) articleObject.get("prepare1");
String prepare2 = (String) articleObject.get("prepare2");
String body = (String) articleObject.get("body");
ArticleData articleData = new ArticleData(dos);
articleData.setArticle(status, sn, code, wdate, sdate, cate, title, reporter, stockcd1, stockcd2,
stockcd3, stockcd4, stockcd5, stockcd6, stockcd7, stockcd8, prepare1, prepare2, body);
articleData.writeDataExternal();
dos.flush();
articleData = null;
articleObject = null;
jsonParse = null;
break;
}
}
return newsDataFile;
}
}
public static final byte[] getbytes(byte src[], int offset, int length) {
byte dest[] = new byte[length];
System.arraycopy(src, offset, dest, 0, length);
return dest;
}
public static void main(String[] args) {
new NewsServer();
}
}
When a client connects, the news server sends polling every 30 seconds to maintain the connection.
When a news file is created, the news content is converted into byte and transmitted to the waiting client.
I implemented it as described above, but the connection is frequently lost.
If you have any design problems or have any advice, please let me know. I'm embarrassed about the source of the server socket.
java.net.SocketException: Broken pipe (Write failed)
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:111)
at java.net.SocketOutputStream.write(SocketOutputStream.java:134)
at java.io.DataOutputStream.write(DataOutputStream.java:88)
at com.ns.data.ArticleData.sendPolling(ArticleData.java:272)
at com.ns.NewsServer$PollingThread.run(JNewsServer.java:89)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:750)
I have an API which pushes me JSON array which has at least 1000 JSON object. I am reading that array from the API and writing it's content into the Redis server. My code is the following;
app.java
public class App {
public static void main(String[] args) throws IOException, JSONException {
RedisOperations redis = new RedisOperations();
redis.connect();
long startTime = System.currentTimeMillis();
URLConnection url = new URLConnection("url");
HttpURLConnection conn = url.connect();
String responseBody = convertStreamToString(conn.getInputStream());
long endTime = System.currentTimeMillis();
System.out.println("That took " + (endTime - startTime) + " milliseconds");
JSONArray jsonArray = new JSONArray(responseBody);
redis.addHashSet(jsonArray);
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (IOException e) {
} finally {
try {
is.close();
} catch (IOException e) {
}
}
return sb.toString();
}
}
RedisOperations.java
public class RedisOperations {
Jedis jedis;
Map<String, String> userProperties;
public void connect() {
try {
jedis = new Jedis("localhost");
System.out.println("Connection to server sucessfully");
// check whether server is running or not
System.out.println("Server is running: " + jedis.ping());
} catch (Exception e) {
System.out.println("Can not connect to redis");
}
}
public void addHashSet(JSONArray jsonArray) throws JSONException {
userProperties = new HashMap<String, String>();
String no = "";
for (int y = 0; y < jsonArray.length(); y++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(y);
no = jsonArray.getJSONObject(y).getString("NO");
for (int i = 0; i < jsonObject.names().length(); i++) {
String key = jsonObject.names().getString(i);
String value = jsonObject.getString(jsonObject.names().getString(i));
userProperties.put(key, value);
}
} catch (Exception e) {
System.out.println("Json object problem!");
}
try {
jedis.hmset("user:" + no, userProperties);
} catch (Exception e) {
System.out.println("Cannot made redis operation");
}
}
}
public void deleteHashSet(JSONArray jsonArray) throws JSONException {
for (int y = 0; y < jsonArray.length(); y++) {
String no = jsonArray.getJSONObject(y).getString("NO");
String keys = "user:" + no;
System.out.println(keys);
jedis.del(keys);
}
}
}
After my research I found that I can read data from URL as inputstream. To use org.json.JSONArray package and it's methods I have to convert that inputstream to string and it's time consuming. Total execution time is 3300ms and converting inputstream to string takes 2700ms. It's huge time!
My problem is I am already taking data as JSON array. Is there a way that I can use that package and methods without converting inputstream to string?
Thanks for you suggestions!
I have a server to get a response headers through which I detect the type of device. Is there any way I can get the Internet speed through response headers or any other method ?
Server_X:
public class Server_X {
static int count = 0;
public static void main(String args[]) {
Socket s = null;
ServerSocket ss2 = null;
System.out.println("Server Listening......");
try {
// can also use static final PORT_NUM, when defined
ss2 = new ServerSocket(4445);
} catch (IOException e) {
e.printStackTrace();
System.out.println("Server error");
}
while (true) {
try {
s = ss2.accept();
System.out.println("connection Established");
ServerThread st = new ServerThread(s);
count++;
System.out.println("total connections :" + count);
st.start();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("Connection Error");
}
}
}
}
ServerThread:
class ServerThread extends Thread {
static String uagent, uaccept;
static String[] b;
static String[] c;
Server_X obj = new Server_X();
String line = null;
BufferedReader is = null;
PrintWriter os = null;
Socket s = null;
public ServerThread(Socket s) {
this.s = s;
}
public void run() {
try {
is = new BufferedReader(new InputStreamReader(s.getInputStream()));
os = new PrintWriter(s.getOutputStream());
} catch (IOException e) {
System.out.println("IO error in server thread");
}
try {
line = is.readLine();
while (line.compareTo("QUIT") != 0) {
os.println(line);
os.flush();
// System.out.println(line);
line = is.readLine();
b = line.split(":");
if (b[0].equals("User-Agent")) {
uagent = b[1];
// System.out.println(uagent);
}
c = line.split(":");
if (c[0].equals("Accept")) {
uaccept = c[1];
// System.out.println(uaccept);
}
UAgentInfo detect = new UAgentInfo(uagent, uaccept);
}
} catch (IOException e) {
line = this.getName(); // reused String line for getting thread name
// System.out.println("IO Error/ Client "+line+" terminated abruptly");
} catch (NullPointerException e) {
line = this.getName(); // reused String line for getting thread name
// System.out.println("Client "+line+" Closed");
} finally {
try {
System.out.println("Connection Closing..");
if (is != null) {
is.close();
// System.out.println(" Socket Input Stream Closed");
}
if (os != null) {
os.close();
// System.out.println("Socket Out Closed");
}
if (s != null) {
s.close();
// System.out.println("Socket Closed");
obj.count--;
System.out.println("Toatal connections (after closing):"
+ obj.count);
}
} catch (IOException ie) {
// System.out.println("Socket Close Error");
}
}// end finally
}
}
You didn't specify what protocol the server is using; I suppose is HTTP since you're catching "User-Agent" and "Accept". If I'm correct, there's no header with the information you're looking for, as you can check on https://en.wikipedia.org/wiki/List_of_HTTP_header_fields.
I have a problem with showing html page form localhost. Here is my method but I just get System.out.println("IN !") in loop (eclipse console). When I'm putting http://localhost:1600/myWebPage.html adress in my browser nothing happened. I'm wondering how to show web page or just some text in browser after typing http://localhost:1600/myWebPage.html. Is this path correct ?
public class ServerWWW {
//localhost:1600/
public static void main(String[] args) {
int portServerWww = 1600;
ServerSocket ss = null;
try {
ss = new ServerSocket(portServerWww);
System.out.println("Server WWW waiting .....");
while(true) {
Socket s = ss.accept(); // block
new ServiceWWW (s).start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
class ServiceWWW extends Thread {
private Socket s = null;
private int counter;
public ObslugaWWW(Socket s) {
this.s = s;
}
public void run(){
try {
System.out.println("IN !"); //Loop
URL url = new URL("http://localhost:1600/myWebPage.html");
HttpURLConnection yc = (HttpURLConnection)url.openConnection();
yc.setRequestMethod("GET");
yc.setDoOutput(true);
yc.connect();
BufferedReader rd = new BufferedReader(new InputStreamReader(yc.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = "OK";
while ((line = rd.readLine()) != null){
sb.append(line + '\n');
}
System.out.println(sb.toString());
yc.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I'm trying to get the remote device folder listing using OBEX; i'm trying to connect using
String btUrl=btgoep://"+mac_address+":10;authenticate=false;encrypt=false;master=false"
but i get Not supported yet error when i call
ClientSession conn = (ClientSession) Connector.open(btURL);
Can anyone help me?
The port may be incorrect. You should get connection addres via service search in DiscoveryListener. In jsr82 it looks like this:
private final UUID L2CAP_UUID = new UUID(0x1106);
public String getOBEXURL(RemoteDevice dev) {
DiscoveryAgent discoveryAgent = null;
try {
LocalDevice localDevice = LocalDevice.getLocalDevice();
discoveryAgent = localDevice.getDiscoveryAgent();
}
catch (Exception e) {
return null;
}
try {
discoveryAgent.searchServices(null, new UUID[]{L2CAP_UUID}, dev, this);
} catch (Exception e) {
return null;
}
synchronized (this) {
try { wait(); }
catch (Exception e) {}
}
switch (respCode) {
case SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
ps.println("Remote device could not be reached");
break;
case SERVICE_SEARCH_ERROR:
ps.println("The service search was terminated with error");
break;
case SERVICE_SEARCH_NO_RECORDS:
ps.println("No services found on device");
break;
case SERVICE_SEARCH_TERMINATED:
ps.println("The service search has been canceled by the application and did not complete");
break;
}
return obexURL;
}
public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
obexURL = servRecord[0].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
}
public void serviceSearchCompleted(int transID, int respCode) {
this.respCode = respCode;
synchronized (this) { notify(); }
}
Try this.
private void GetFileNamesViaBTFTP(UUID UUID3)
{
try
{
mBtSocket = mBtDevice.createInsecureRfcommSocketToServiceRecord(UUID3);
}
catch (Exception e)
{
//e.printStackTrace();
}
Thread thread=new Thread(new Runnable() {
public void run()
{
UUID uuid=UUID.fromString("F9EC7BC4-953C-11D2-984E-525400DC9E09");
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(uuid.getMostSignificantBits());
bb.putLong(uuid.getLeastSignificantBits());
byte [] bytes=bb.array();
Operation putOperation=null;
Operation getOperation=null;
//ArrayUtils.reverse(bytes);
try
{
// 소켓을 연결한다
mBtSocket.connect();
mSession = new ClientSession((ObexTransport)(mTransport = new BluetoothObexTransport(mBtSocket)));
HeaderSet headerset = new HeaderSet();
headerset.setHeader(HeaderSet.TARGET, bytes);
headerset = mSession.connect(headerset);
if (headerset.getResponseCode() == ResponseCodes.OBEX_HTTP_OK)
{
mConnected = true;
}
else
{
mSession.disconnect(headerset);
}
// Send a file with meta data to the server
final byte filebytes[] = "[CLIENT] Hello..".getBytes();
final HeaderSet hs = new HeaderSet();
hs.setHeader(HeaderSet.NAME, "test.txt");
hs.setHeader(HeaderSet.TYPE, "text/plain");
hs.setHeader(HeaderSet.LENGTH, new Long((long)filebytes.length));
putOperation = mSession.put(hs);
mOutput = putOperation.openOutputStream();
mOutput.write(filebytes);
mOutput.close();
putOperation.close();
//In order to go the desired folder the OBEX SETPATH command is
//being used
//Prepare the header for the SETPATH command
HeaderSet header = new HeaderSet();
//folder_name is set to the name of the desired folder
//if left blank the root folder will be used
//header.setHeader(HeaderSet.NAME, "");
//Send the SETPATH command
/*result =*/ mSession.setPath(header, false, false);
final HeaderSet geths = new HeaderSet();
//geths.setHeader(HeaderSet.NAME, null);
geths.setHeader(HeaderSet.TYPE, "x-obex/folder-listing");
//hs.setHeader(HeaderSet.LENGTH, new Long((long)filebytes.length));
getOperation = mSession.get(geths);
InputStreamReader din = new
InputStreamReader(getOperation.openInputStream(), "UTF-8");
BufferedReader bufferedReader = new BufferedReader(din);
String tmp2=new String();
String line = bufferedReader.readLine();
while (line != null)
{
tmp2 += line;//System.out.println(line);
line = bufferedReader.readLine();
}
bufferedReader.close();
getOperation.close();
/*
mInput=getOperation.openInputStream();
// Retrieve the length of the object being sent back
int length = (int) getOperation.getLength();
// Create space for the object
byte[] obj = new byte[length];
// Get the object from the input stream
DataInputStream in = getOperation.openDataInputStream();
in.read(obj);
// End the transaction
in.close();
*/
final String ftmp=tmp2;
runOnUiThread(new Runnable(){
#Override
public void run()
{
//String s=new String(ftmp, "UTF-16");
deviceTextEdit.setText(ftmp);
}
});
Xml xml;
}
catch (Exception e)
{
//e.printStackTrace();
}
finally
{
try
{
mOutput.close();
putOperation.close();
mSession.disconnect(null);
}
catch (IOException e)
{}
//updateStatus("[CLIENT] Connection Closed");
}
}
});
thread.start();
}
Now your work is to parse XML data of obexfolder listing.