This question already has an answer here:
- How do I find out what my external IP address is? 13 answers
I want to get an IP address which will be reachable outside of my machine or my LAN using scala.
Use Case Scenario: A web service is running on a machine. And in of its responses it should return a url of one of its endpoint. So now I have to provide the IP of the machine on which the web service is running
I used NetworkInterface.getNetworkInterfaces() to get all of the known network interfaces on the host, and then iterated over each NI's addresses. But In this case I'm getting many Ip Addresses. How can I find out the right IP from all of them. Below is the code snippet in scala:
private def ipAddress: String = {
val enumeration = NetworkInterface.getNetworkInterfaces.asScala.toSeq
val ipAddresses = enumeration.flatMap(p =>
p.getInetAddresses.asScala.toSeq
)
val address = ipAddresses.find { address =>
val host = address.getHostAddress
host.contains(".") && !address.isLoopbackAddress && !address.isAnyLocalAddress && !address.isLinkLocalAddress
}.getOrElse(InetAddress.getLocalHost)
}