1

你好!

我正在编写将在 android 中运行的代码。我想获取我的电脑的 IP 地址,即连接到同一个网络。即我的手机是通过wifi连接的,而电脑是通过以太网电缆连接到同一个路由器的。我可以从我的手机 ping 我的电脑,反之亦然,但我无法通过代码获取我的电脑的 IP 地址或主机名。

我正在使用这个

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

我收到网络无法访问的错误。

请提供帮助,因为我被困了很长时间。谢谢并恭祝安康

法斯

4

1 回答 1

3

您可以尝试将字符串 IP 转换为整数,然后从包含 IP 地址的字节构造 InetAddress 对象。这是代码

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;
}
于 2011-06-28T08:57:09.700 回答