在应用调试过程中,对接的技术人员要求提供一下机顶盒 的外网IP地址,于是打开了盒子上的设置,将IP地址发了过去,对面回复说这是私网IP,要公网IP才可以。
一般情况下,电脑的公网IP地址很好查:打开百度:
但是有些机顶盒上是没有浏览器的,所以就需要通过代码的层面来获取。
通过百度,先找到了如下的方法:
/**
* 获取IP地址
* @return
* @throws SocketException
*/
public static String getLocalIPAddress() throws SocketException {
for(Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();){
NetworkInterface intf = en.nextElement();
for(Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();){
InetAddress inetAddress = enumIpAddr.nextElement();
if(!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address)){
return inetAddress.getHostAddress().toString();
}
}
}
return "null";
}
但是获取到的结果和机顶盒设置里的ip一致的,也就是说还是一个私网IP。
后经过查询,可通过如下方式获取公网IP:
/**
* 获取外网IP地址
* @return
*/
public static String GetNetIp(){
String IP = "";
try {
String address = "http://ip.taobao.com/service/getIpInfo2.php?ip=myip";
URL url = new URL(address);
//URLConnection htpurl=url.openConnection();
HttpURLConnecti