0

I am trying to connect 2 devices through sockets, so that they can exchange data. They are also connected via wifi hotspot. I am using Services.

Device 1 is the hotspot (where the ServerSocket is implemented), Device 2 is the one who connects to it (where the Socket is implemented). I did some research and i am able to get the ip of each one of them (but calculated on their own class). But in order for me to create the client socket, i need the IP Address of the host (the phone that is working as a hotspot) in the other class. I can not get it on the server side, because that part of the code wont be executed, since i am using one phone to create the hotspot network and another one to connect to it.

I know that usually the IP Address of a device that is tethering is generally the same, but i can not trust that, because i gotta make sure it works on all phones.

So, how can i get the ip address of the server (hotspot host) in the client (phone connected to that hotspot) service ?

  • How do you determine the ip of the client on the client? – greenapps Aug 03 '16 at 14:01
  • http://stackoverflow.com/questions/5387036/programmatically-getting-the-gateway-and-subnet-mask-details – greenapps Aug 03 '16 at 14:39
  • To get the ip of the client on the client i was using the getHostAddress() from the inetAddress. I would get a list of networkinfo's and then i would get the inetaddress for each of those network configurations and then call the getHostAddress(), for the object that wasn't a loopbackaddress. Something similar to this : http://stackoverflow.com/a/10199498/6634292 – Filipe Gonçalves Aug 03 '16 at 17:18

2 Answers2

2

In the client side you can use dhcp.gateway to get the server side(The one who created hotspot) ip address.

 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 ;
}
Raza
  • 791
  • 7
  • 22
-1

Determine the ip of the gateway. Programmatically getting the gateway and subnet mask details. Use the WifiManager.getDhcpInfo().gateway .

Community
  • 1
  • 1
greenapps
  • 11,154
  • 2
  • 16
  • 19