IP address of remote device in a LAN using Java

krishprateek

krishprateek

@krishprateek-vrpct6 Oct 23, 2024
i have written a code that should give me the ip addresses of all the devices connected in a wireless network.But it is just showing the ip address of the default gateway router and my own system. so plz can someone help me with this.

importjava.io.IOException;
importjava.net.InetAddress;
 
publicclass NetworkPing {
 
 
publicstaticvoid main(String[] args)throws IOException {
 
InetAddress localhost = InetAddress.getLocalHost();
// this code assumes IPv4 is used
byte[] ip = localhost.getAddress();
 
for(int i =1; i <=254; i++)
{
ip[3]=(byte)i;
InetAddress address = InetAddress.getByAddress(ip);
if(address.isReachable(1000))
{
System.out.println(address +" machine is turned on and can be pinged");
}
elseif(!address.getHostAddress().equals(address.getHostName()))
{
System.out.println(address +" machine is known in a DNS lookup");
}
else
{
System.out.println(address +" the host address and host name are equal, meaning the host name could not be resolved");
}
}
 
}
}

Replies

Welcome, guest

Join CrazyEngineers to reply, ask questions, and participate in conversations.

CrazyEngineers powered by Jatra Community Platform

  • Kaustubh Katdare

    Kaustubh Katdare

    @thebigk Jan 4, 2013

    I added code tags, and it seems to have messed up the entire formatting. Could please post your code again so that I can make it appear properly?

    Update: Fixed! 😀
  • durga ch

    durga ch

    @durga-TpX3gO Jan 5, 2013

    I am a java illeterate but as I read from your code, loks like you are trying to reach all IPs 1.1.1.1 to 255.255.255.255 and see whch ones are reachable and then returning the ip ??
    if your logic is different let me know.

    can I know the networj setup where you are using this script???
  • KenJackson

    KenJackson

    @kenjackson-mBf7HF Jan 7, 2013

    I think isReachable() uses raw sockets, which requires root (or Administrator) priviledge.

    BTW, if you just want the answer and aren't specifically trying to write a program, the <a href="https://nmap.org/" target="_blank" rel="nofollow noopener noreferrer">Nmap: the Network Mapper - Free Security Scanner</a> program does a very good job.