Fahad Ali
Fahad Ali

Reputation: 21

How to create InetAddress object in android?

HI!

I am writing code that will run in android. I want to get the IP address of my pc i.e connected to the same network. i.e My Phone is connected via wifi and the pc is connected via ethernet cable to the same router. I am able to ping my pc from my phone and vice versa but I am not able to get the ip address or hostname of my pc via code.

I am using this

InetAddress inet = InetAddress.getByName( "192.168.0.102");

I get network unreachable error.

Kindly help as I am stuck in it for very long. Thanks and regards

Fas

Upvotes: 1

Views: 3320

Answers (1)

Vadym Stetsiak
Vadym Stetsiak

Reputation: 1970

You can try converting string IP into integer and then construct InetAddress object from bytes containing IP address. Here's the code

InetAddress inet = intToInetAddress(ipStringToInt( "192.168.0.102"));

public static int ipStringToInt(String str) {
     int result = 0;
     String[] array = str.split("\\.");
     if (array.length != 4) return 0;
     try {
         result = Integer.parseInt(array[3]);
         result = (result << 8) + Integer.parseInt(array[2]);
         result = (result << 8) + Integer.parseInt(array[1]);
         result = (result << 8) + Integer.parseInt(array[0]);
     } catch (NumberFormatException e) {
         return 0;
     }
     return result;
 }

public static InetAddress intToInetAddress(int hostAddress) {
    InetAddress inetAddress;
    byte[] addressBytes = { (byte)(0xff & hostAddress),
                            (byte)(0xff & (hostAddress >> 8)),
                            (byte)(0xff & (hostAddress >> 16)),
                            (byte)(0xff & (hostAddress >> 24)) };

    try {
       inetAddress = InetAddress.getByAddress(addressBytes);
    } catch(UnknownHostException e) {
       return null;
    }
    return inetAddress;
}

Upvotes: 3

Related Questions