-2

im creating an android app, to link and transfer socket packets to the server through wifi. In order for this, the IP address of the connected server has to be defined. I used the below function to get the IP address. When i hardcode the SERVER_IP = "0"; the app runs normally. Please help!

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

After Setting up the above, I ran the below codes on the OnCreate function.

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();
        }
    }
}

As soon as that happens, my android application will stop working.

This is the error that appears:

Java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference

mctjl_1997
  • 163
  • 1
  • 3
  • 17

2 Answers2

3

Use this function to get IP (v4 or v6) inside an activity:

// 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 "";
}

When you need it, just call it this way: getLocalIpAddress(true). You will get the IP as a string for you to use.

statosdotcom
  • 3,109
  • 2
  • 17
  • 40
  • 1
    Awesome! I'm not getting the error anymore! Thanks – mctjl_1997 May 03 '17 at 04:48
  • Thank you Marcus, keep it up. – statosdotcom May 04 '17 at 03:10
  • socket = new Socket(serverAddr, SERVERPORT); Just wondering, if I am connecting to my server correctly with this function? My serverAddr will be the ip address of my wifi i used to connect between my android phone and my hardware. – mctjl_1997 May 04 '17 at 10:10
  • I think you are right. The "real" IP of your phone is revealed only when behind a regular data conn, like 3G, 4G and so on. – statosdotcom May 04 '17 at 10:30
  • Thanks for the reply! I see, so it looks like my TCP client set up is correct. However, my current server connection failure might be due to my hardware not setting up the socket server correctly. I will look into this! Thank you very much! :) I am pretty new to all of these – mctjl_1997 May 04 '17 at 11:47
1

Here are a few things that you have to check

  • Does the Application has the permission to access the WiFi ?
  • If you are using the getApplicationContext() in a different class , pass a context from the Parent Activity.
  • Test in on a mobile device not on the emulator.
jsam
  • 116
  • 2
  • 4