joesan
joesan

Reputation: 15435

Scan and Get Hostname for all devices using Scala

I have the following snippet which attempts to print all available devices in the given IP range and I want it to also print the hostname:

import java.net.{InetAddress, NetworkInterface}
import scala.collection.JavaConverters._

object GetIpMac {
  def main(args: Array[String]): Unit = {
    try {
      val network = "192.168.0"
      val range = (1 to 255)
      for (i <- range) {
        val ip = network + "." + i.toString
        val inet = InetAddress.getByName(ip)
        if (!inet.isLinkLocalAddress) {
          val ni = NetworkInterface.getByInetAddress(inet)
          if (ni != null) {
            val mac = ni.getHardwareAddress
            if (mac != null) {
              println(s"printing hostname ${inet.getHostName()}")
              println(ip + " " + mac.map("%02x".format(_)).mkString(":"))
            }
          }
        }
      }
    } catch {
      case ex: Exception => ex.printStackTrace()
    }
  }
}

When I ran that on my local machine, I get to see the following:

me@my-mac:~/Desktop$ sh scan.sh 
printing hostname 192.168.0.101
192.168.0.101 40:d2:53:99:78:67

As you can see, it is not printing the expected hostname which is

my-mac

Any ideas as to why is this? How can I have the hostname printed?

Upvotes: 2

Views: 209

Answers (0)

Related Questions