在活动中获取IP会导致崩溃

时间:2017-05-03 03:40:01

标签: java android sockets tcp tcpclient

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

    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()'在空对象引用上

2 个答案:

答案 0 :(得分:3)

使用此功能在活动中获取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作为字符串供您使用。

答案 1 :(得分:1)

以下是您必须检查的一些事项

  • 应用程序是否有权访问WiFi?
  • 如果您在其他类中使用getApplicationContext(),请从Parent Activity传递上下文。
  • 在不在模拟器上的移动设备上测试。
相关问题