你好,我是一名新手安卓程序员。我的目标是连接到一个接入点并发送一些命令。在通过wifi连接到它之后,是否可以编程方式获取它的IP地址,以便我可以与它建立http连接?
到目前为止,我知道我们可以获取设备IP地址,但不确定是否可以获取接入点的IP地址。请帮忙解答。谢谢。
你好,我是一名新手安卓程序员。我的目标是连接到一个接入点并发送一些命令。在通过wifi连接到它之后,是否可以编程方式获取它的IP地址,以便我可以与它建立http连接?
到目前为止,我知道我们可以获取设备IP地址,但不确定是否可以获取接入点的IP地址。请帮忙解答。谢谢。
public static String getApIpAddr(Context context) {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
DhcpInfo dhcpInfo = wifiManager.getDhcpInfo();
byte[] ipAddress = convert2Bytes(dhcpInfo.serverAddress);
try {
String apIpAddr = InetAddress.getByAddress(ipAddress).getHostAddress();
return apIpAddr;
} catch (UnknownHostException e) {
e.printStackTrace();
}
return null;
}
private static byte[] convert2Bytes(int hostAddress) {
byte[] addressBytes = { (byte)(0xff & hostAddress),
(byte)(0xff & (hostAddress >> 8)),
(byte)(0xff & (hostAddress >> 16)),
(byte)(0xff & (hostAddress >> 24)) };
return addressBytes;
}
try {
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())
{
//My IP address
String Ip= inetAddress.getHostAddress().toString();
}
}
}
}
catch (SocketException e)
{
Log.e("Error occurred ", e.toString());
}
我猜你指的是设备连接的接入点的外部(公共)IP地址。 如果是这样,确实有一种简单的方法可以获取设备所连接的接入点的公共IP地址。只需在Web服务器上设置一个脚本,该脚本将回显连接到它的任何客户端的IP地址(类似于www.whatismyip.com)。 然后,您的设备只需要向脚本发送GET请求,就会返回设备连接的接入点的外部IP。