我正在尝试通过插座连接两个设备,以便它们可以交换数据。它们还可以通过wifi热点连接。我正在使用服务。
设备1是热点(实现ServerSocket的地方),设备2是连接到它的人(实现套接字的地方)。我做了一些研究,我能够得到他们每个人的ip (但计算在他们自己的类上)。但为了创建客户端套接字,我需要另一个类中主机(用作热点的电话)的IP地址。我不能在服务器端得到它,因为这部分代码不会被执行,因为我使用一部手机创建热点网络,而另一部手机连接到它。
我知道通常情况下,连接设备的IP地址通常是相同的,但我不能相信这一点,因为我必须确保它在所有电话上都能工作。
那么,如何在客户端(连接到该热点的手机)服务中获取服务器(热点主机)的ip地址?
发布于 2016-08-03 22:46:26
确定网关的ip。Programmatically getting the gateway and subnet mask details。使用WifiManager.getDhcpInfo().gateway
。
发布于 2018-10-03 19:48:34
在客户端,您可以使用dhcp.gateway获取服务器端(hotspot的创建者) ip地址。
private final WifiManager manager;
private final DhcpInfo dhcp;
private InetAddress getServerIP() {
manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
dhcp = manager.getDhcpInfo();
final String address = Formatter.formatIpAddress(dhcp.gateway);// gateway -
default gateway IP address
InetAddress serverIP = null;
try {
serverIP = InetAddress.getByName(address);
if(mDebug)
Log.i("Server IP ","" + serverIP.toString());
} catch (Exception e) {
if(mDebug)
Log.e("Cannot find server's IP. Error ","" + e.toString());
}
return serverIP ;
}
https://stackoverflow.com/questions/38743126
复制相似问题