java获取接口访问ip
时间: 2023-08-14 20:05:34 浏览: 107
要获取接口访问IP,可以通过Java代码中的InetAddress类来实现。以下是一个获取本机IP地址的示例代码:
```
import java.net.InetAddress;
import java.net.UnknownHostException;
public class GetIPAddress {
public static void main(String[] args) throws UnknownHostException {
InetAddress ip = InetAddress.getLocalHost();
System.out.println("IP地址为:" + ip.getHostAddress());
}
}
```
如果要获取远程服务器的IP地址,可以通过调用InetAddress类的getByName()方法并传递服务器的主机名或IP地址来实现,如下所示:
```
import java.net.InetAddress;
import java.net.UnknownHostException;
public class GetIPAddress {
public static void main(String[] args) throws UnknownHostException {
String hostname = "www.example.com"; // 远程服务器主机名或IP地址
InetAddress ip = InetAddress.getByName(hostname);
System.out.println("IP地址为:" + ip.getHostAddress());
}
}
```
注意,在使用getByName()方法时,需要注意处理UnknownHostException异常。
阅读全文