Get public IP Address of the current machine using

2019-06-09 13:26发布

This question already has an answer here:

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)

}

1条回答
淡お忘
2楼-- · 2019-06-09 14:13

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()));
    return in.readLine()
} 
查看更多
登录 后发表回答