在这个例子中,我们将看到如何获得系统的 IP 地址。步骤如下:
1)通过调用InetAddress
类的getLocalHost()
方法获取本地主机地址。
2)通过调用getHostAddress()
方法获取 IP 地址。
import java.net.InetAddress;
class GetMyIPAddress
{
public static void main(String args[]) throws Exception
{
/* public static InetAddress getLocalHost()
* throws UnknownHostException: Returns the address
* of the local host. This is achieved by retrieving
* the name of the host from the system, then resolving
* that name into an InetAddress. Note: The resolved
* address may be cached for a short period of time.
*/
InetAddress myIP=InetAddress.getLocalHost();
/* public String getHostAddress(): Returns the IP
* address string in textual presentation.
*/
System.out.println("My IP Address is:");
System.out.println(myIP.getHostAddress());
}
}
输出:
My IP Address is:
115.242.7.243
参考: