【问题标题】:Getting IP inside activity causes crash [duplicate]在活动中获取IP会导致崩溃[重复]
【发布时间】:2017-05-03 16:52:56
【问题描述】:

我正在创建一个 android 应用程序,通过 wifi 链接和传输套接字数据包到服务器。为此,必须定义所连接服务器的 IP 地址。我使用下面的函数来获取 IP 地址。当我硬编码 SERVER_IP = "0";该应用程序正常运行。请帮忙!

    private final String SERVER_IP = getIpAddr();

    public String getIpAddr() {
    WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    int ip = wifiInfo.getIpAddress();

    String ipString = String.format(
            "%d.%d.%d.%d",
            (ip & 0xff),
            (ip >> 8 & 0xff),
            (ip >> 16 & 0xff),
            (ip >> 24 & 0xff));

    return ipString;
}

以上设置完成后,我在 OnCreate 函数上运行了以下代码。

class ClientThread implements Runnable {

    @Override
    public void run() {
        try {
            InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
            socket = new Socket(serverAddr, SERVERPORT);
        } catch (UnknownHostException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}

一旦发生这种情况,我的 android 应用程序将停止工作。

这是出现的错误:

Java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“android.content.Context android.content.Context.getApplicationContext()”

【问题讨论】:

  • 尝试使用 ActivityName.this.getApplicationContext() 获取上下文
  • 谢谢。加 1。

标签: java android sockets tcp tcpclient


【解决方案1】:

使用此函数在活动中获取 IP(v4 或 v6):

// Get IP address from first non-localhost interface
// @param ipv4  true returns ipv4
//              false returns ipv6
// @return address or empty string
public static String getLocalIpAddress(boolean useIPv4) {
    try {
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface intf : interfaces) {
            List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
            for (InetAddress addr : addrs) {
                if (!addr.isLoopbackAddress()) {
                    String sAddr = addr.getHostAddress();
                    //boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                    boolean isIPv4 = sAddr.indexOf(':')<0;
                    if (useIPv4) {
                        if (isIPv4)
                            return sAddr;
                    } else {
                        if (!isIPv4) {
                            int delim = sAddr.indexOf('%'); // drop ip6 zone suffix
                            return delim<0 ? sAddr.toUpperCase() : sAddr.substring(0, delim).toUpperCase();
                        }
                    }
                }
            }
        }
    } catch (Exception ex) { } // for now eat exceptions
    return "";
}

当您需要它时,只需这样称呼它:getLocalIpAddress(true)。您将获得 IP 作为字符串供您使用。

【讨论】:

  • 太棒了!我不再收到错误了!谢谢
  • 谢谢马库斯,继续努力。
  • socket = new Socket(serverAddr, SERVERPORT);只是想知道,如果我使用此功能正确连接到我的服务器?我的 serverAddr 将是我用来连接我的 android 手机和我的硬件的 wifi 的 IP 地址。
  • 我认为你是对的。只有在常规数据连接(如 3G、4G 等)之后才会显示您手机的“真实”IP。
  • 感谢您的回复!我明白了,看来我的 TCP 客户端设置是正确的。但是,我当前的服务器连接失败可能是由于我的硬件没有正确设置套接字服务器。我会调查的!非常感谢! :) 我对所有这些都很陌生
【解决方案2】:

您必须检查以下几点

  • 应用是否有权限访问WiFi?
  • 如果您在不同的类中使用 getApplicationContext(),请从父 Activity 传递上下文。
  • 在移动设备上而不是在模拟器上进行测试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-14
    • 1970-01-01
    • 1970-01-01
    • 2013-06-08
    相关资源
    最近更新 更多