【问题标题】:How to create InetAddress object in android?如何在 android 中创建 InetAddress 对象?
【发布时间】:2011-03-20 13:44:01
【问题描述】:

嗨!

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

我正在使用这个

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

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

请帮助我,因为我被困了很长时间。 谢谢和问候

Fas

【问题讨论】:

    标签: android network-programming inetaddress


    【解决方案1】:

    您可以尝试将字符串 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-08-08
      • 1970-01-01
      • 1970-01-01
      • 2019-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多