开发者

How to create InetAddress object in android?

开发者 https://www.devze.com 2023-02-17 19:13 出处:网络
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 cabl开

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 cabl开发者_运维知识库e 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


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消