在Java编程中,如何获取本地计算机的IP地址和主机名?
以下示例显示如何使用InetAddress
类的getLocalAddress()
方法获取系统的本地IP地址和主机名。
package com.yiibai; import java.net.InetAddress; public class GetLocalIPAddress { public static void main(String[] args) throws Exception { InetAddress addr = InetAddress.getLocalHost(); System.out.println("Local HostAddress: " + addr.getHostAddress()); String hostname = addr.getHostName(); System.out.println("Local host name: " + hostname); } }
上述代码示例将产生以下结果 -
Local HostAddress: 192.168.1.50
Local host name: YB-PC