How to get a list of IP connected in same network (subnet) using Java
this should work when the hosts on your network react to ICMP packages (ping) (>JDK 5):
public void checkHosts(String subnet){
int timeout=1000;
for (int i=1;i<255;i++){
String host=subnet + "." + i;
if (InetAddress.getByName(host).isReachable(timeout)){
System.out.println(host + " is reachable");
}
}
}
invoke the method for a subnet (192.168.0.1-254) like this:
checkHosts("192.168.0");
didnt test it but should work kinda like this. Obviously this only checks the 254 hosts in the last byte of the ip address...
check:
http://download-llnw.oracle.com/javase/6/docs/api/java/net/InetAddress.html#isReachable%28int%29
http://blog.taragana.com/index.php/archive/how-to-do-icmp-ping-in-java-jdk-15-and-above/
hope that helped
Get All IP and Mac Address in lan
I've been working on a project to do the same thing. I think the best way to go about this is to execute another process at run time and read the results. As already suggested, you could read the system ARP table and parse results, but this is platform dependent. The windows command in command prompt is: arp -a.
I chose to make a remote call to nmap and parse those results. It requires installing nmap on your machine, but the solutions "should" be cross-platform as long as the appropriate version of nmap is installed:
Available here: https://nmap.org/download.html
Here's a quick example. You'd of course need to make some changes to dynamically choose the network to scan and parse the results instead of print them.
try {
Process proc = Runtime.getRuntime().exec("nmap -PR -sn 192.168.1.0/24");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
// read the output from the command
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
// read any errors from the attempted command
while ((s = stdError.readLine()) != null) {
System.err.println(s);
}
} catch (IOException ex) {
System.err.println(ex);
}
Get all IP addresses from a given IP address and subnet mask
Answering my own question, solution is to use Apache commons.net library
import org.apache.commons.net.util.*;
SubnetUtils utils = new SubnetUtils("192.168.1.0/24");
String[] allIps = utils.getInfo().getAllAddresses();
//appIps will contain all the ip address in the subnet
Read more: Class SubnetUtils.SubnetInfo
Get all the Up ip in the local network -java
I tried this program to find all the up ip in the subnet of the system connected.
package com.Server;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
public class Subnet
{
public void Subnet() throws UnknownHostException, SocketException
{
Enumeration e = NetworkInterface.getNetworkInterfaces();
while(e.hasMoreElements())
{
NetworkInterface n = (NetworkInterface) e.nextElement();
Enumeration ee = n.getInetAddresses();
while (ee.hasMoreElements())
{
InetAddress i = (InetAddress) ee.nextElement();
String ip = i.getHostAddress();
String sip = ip.substring(0, ip.indexOf('.',ip.indexOf('.',ip.indexOf('.')+1) + 1) + 1);
try {
for(int it=1;it<=255;it++)
{
String ipToTest = sip+it;
boolean online = InetAddress.getByName(itToTest).isReachable(100);
if (online) {
System.out.println(ipToTest+" is online");
}
}
} catch (IOException e1) {
System.out.println(sip);
}
}
}
}
}
How to list all computers in network?
With the linked answers, you should be able to filter the available interfaces down to a few possible options (i.e. interfaces that are up, no loopback, have an IPv4 address, etc.).
To discover game hosts, you can do something like the following.
- Let the game hosts listen for UDP broadcasts on a specific port.
- Let the clients send out a UDP broadcast to the broadcast address of each of the remaining interfaces from above. The broadcast address can be determined by
getBroadcast()
in classInterfaceAddress
. - The host replies, to let the client know it is waiting. When using UDP, the hosts IP is in the received
DatagramPacket
. When using TCP, the hosts IP can be determined from theSocket
. - Then the client can use the address of the host to establish a direct connection and/or set up RMI.
Edit: I found this blog post, which includes code that does more or less what I described.
Find out IP of all active machines on network
You should send out a ICMP echo message to all hosts in the subnet. For example, if you subnet is 192.168.1.0/24 send a ICMP ping to 192.168.1.255 and all hosts would respond.
[06:43:11 :~]$ ping 192.168.0.255
PING 192.168.0.255 (192.168.0.255): 56 data bytes
64 bytes from 192.168.0.12: icmp_seq=0 ttl=64 time=0.159 ms
64 bytes from 192.168.0.1: icmp_seq=0 ttl=64 time=5.581 ms
64 bytes from 192.168.0.12: icmp_seq=1 ttl=64 time=0.135 ms
64 bytes from 192.168.0.1: icmp_seq=1 ttl=64 time=5.540 ms
^C
--- 192.168.0.255 ping statistics ---
2 packets transmitted, 2 packets received, +2 duplicates, 0.0% packet loss
round-trip min/avg/max/stddev = 0.135/2.854/5.581/2.707 ms
[06:43:21 :~]$
How to get IP address and names of all devices in local network on Android
The main problem is that you're grabbing the wrong IP address. InetAddress.getLocalHost() is returning 127.0.0.1 and that's just your device.
Use the Wifi IP address in instead:
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
WifiManager wm = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
WifiInfo connectionInfo = wm.getConnectionInfo();
int ipAddress = connectionInfo.getIpAddress();
String ipString = Formatter.formatIpAddress(ipAddress);
Here is a quick and dirty AsyncTask that does that:
static class NetworkSniffTask extends AsyncTask<Void, Void, Void> {
private static final String TAG = Constants.TAG + "nstask";
private WeakReference<Context> mContextRef;
public NetworkSniffTask(Context context) {
mContextRef = new WeakReference<Context>(context);
}
@Override
protected Void doInBackground(Void... voids) {
Log.d(TAG, "Let's sniff the network");
try {
Context context = mContextRef.get();
if (context != null) {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
WifiManager wm = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
WifiInfo connectionInfo = wm.getConnectionInfo();
int ipAddress = connectionInfo.getIpAddress();
String ipString = Formatter.formatIpAddress(ipAddress);
Log.d(TAG, "activeNetwork: " + String.valueOf(activeNetwork));
Log.d(TAG, "ipString: " + String.valueOf(ipString));
String prefix = ipString.substring(0, ipString.lastIndexOf(".") + 1);
Log.d(TAG, "prefix: " + prefix);
for (int i = 0; i < 255; i++) {
String testIp = prefix + String.valueOf(i);
InetAddress address = InetAddress.getByName(testIp);
boolean reachable = address.isReachable(1000);
String hostName = address.getCanonicalHostName();
if (reachable)
Log.i(TAG, "Host: " + String.valueOf(hostName) + "(" + String.valueOf(testIp) + ") is reachable!");
}
}
} catch (Throwable t) {
Log.e(TAG, "Well that's not good.", t);
}
return null;
}
Here are the permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Not all routers allow this, so to get the names in a other way is to send the mac adress to an api and get the brand name back in return.
String macAdress = "5caafd1b0019";
String dataUrl = "http://api.macvendors.com/" + macAdress;
HttpURLConnection connection = null;
try {
URL url = new URL(dataUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.flush();
wr.close();
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuffer response = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {response.append(line);response.append('\r');}
rd.close();
String responseStr = response.toString();
Log.d("Server response", responseStr);
} catch (Exception e) {e.printStackTrace();} finally {if (connection != null) {connection.disconnect();}}
Related Topics
How to Get the File Name from a String Containing the Absolute File Path
Java Enum and Additional Class Files
Declaring and Initializing Variables Within Java Switches
Jschexception: Algorithm Negotiation Fail
How to Have a Textfield Inside a Label
How to Set the Jdk Netbeans Runs On
How to Create a File in a Directory in Java
How to Connect to a SQL Server 2008 Database Using Jdbc
How to Convert a String to Another Locale
Calculating Difference in Dates in Java
Functional Style of Java 8's Optional.Ifpresent and If-Not-Present
In Java, Is It More Efficient to Use Byte or Short Instead of Int and Float Instead of Double
How to Connect to Postgres Db Due to the Authentication Type 10 Is Not Supported
Selenium Ie Webdriver Only Works While Debugging