0

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)

}
user2613399
  • 715
  • 1
  • 6
  • 14
  • This is not a scala question. And it's not answerable just from a list of IPs. What is the "right" address will depend on the network routing around your machine. It's possible there is no externally-reachable address (for instance this is true for the machine I'm typing this on). So please explain more about your scenario and what you're trying to do. – The Archetypal Paul Jul 15 '16 at 10:02
  • 3
    There are several other questions that address this. See, for example http://stackoverflow.com/questions/1145899/how-do-i-find-out-what-my-external-ip-address-is – The Archetypal Paul Jul 15 '16 at 10:04
  • 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. – user2613399 Jul 15 '16 at 11:06
  • There is no single "IP of the machine" if it has multiple interfaces. And any IP it has isn't necessarily the one that an external use would use - if there's a web proxy or port forwarding, for instance. So you need to explain where the web client is and understand how traffic will go from client to server. Then you can work out which IP address might be relevant. – The Archetypal Paul Jul 15 '16 at 12:02

1 Answers1

2

You have to use an external service like whatismyip as mentioned here

An equivalent scala code will be ,

def ipAddress(): String = {
  val whatismyip = new URL("http://checkip.amazonaws.com")
  val in:BufferedReader = new BufferedReader(new InputStreamReader(
                whatismyip.openStream()))
  in.readLine()
} 
Lee James
  • 91
  • 1
  • 5
Rjk
  • 1,356
  • 3
  • 15
  • 25
  • Do note that just tells you what IP address traffic **from** your machine comes from. It does not necessarily mean your machine is reachable on that address. – The Archetypal Paul Jul 15 '16 at 10:23