使用scala获取当前计算机的公共IP地址 [英] Get public IP Address of the current machine using scala
问题描述
我希望获得一个可以使用scala在我的机器或局域网外部访问的IP地址。
I want to get an IP address which will be reachable outside of my machine or my LAN using scala.
用例场景:Web服务正在运行机。在其响应中,它应该返回其端点之一的URL。所以现在我必须提供运行Web服务的机器的IP
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
我使用NetworkInterface.getNetworkInterfaces()来获取所有已知的网络接口主机,然后迭代每个NI的地址。但在这种情况下,我得到了许多IP地址。如何从所有这些中找出正确的IP。
以下是scala中的代码段:
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)
}
推荐答案
你必须使用像whatismyip这样的外部服务这里
You have to use an external service like whatismyip as mentioned here
等效的scala代码将是,
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()
}
这篇关于使用scala获取当前计算机的公共IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!