Skip to content

Instantly share code, notes, and snippets.

@mathieugerard
Last active September 24, 2023 06:54
Show Gist options
  • Save mathieugerard/0de2b6f5852b6b0b37ed106cab41eba1 to your computer and use it in GitHub Desktop.
Save mathieugerard/0de2b6f5852b6b0b37ed106cab41eba1 to your computer and use it in GitHub Desktop.
Get Local Wifi IP address on iOS and Android
import android.net.wifi.WifiManager;
import android.content.Context;
import java.net.InetAddress;
import java.nio.ByteOrder;
private String getLocalWifiIpAddress() {
WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) {
ipAddress = Integer.reverseBytes(ipAddress);
}
byte[] ipByteArray = BigInteger.valueOf(ipAddress).toByteArray();
String ipAddressString;
try {
ipAddressString = InetAddress.getByAddress(ipByteArray).getHostAddress();
} catch (UnknownHostException ex) {
ipAddressString = null;
}
return ipAddressString;
}
#include <ifaddrs.h>
#include <arpa/inet.h>
- (NSString *)getLocalWifiIpAddress {
NSString *address = @"error";
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;
success = getifaddrs(&interfaces);
if (success == 0) {
temp_addr = interfaces;
while(temp_addr != NULL) {
if(temp_addr->ifa_addr->sa_family == AF_INET) {
if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
}
}
temp_addr = temp_addr->ifa_next;
}
}
// Free memory
freeifaddrs(interfaces);
return address;
}

Get Local Wifi IP address on iOS and Android

This Gist provide the function to retrieve the local IP address of the device when connected to the wifi.

iOS

No permission is required from the user to access the information. It uses the getifaddrs method that is not directly part of the public iOS API but it's still perfectly fine to use it and allowed by Apple.

Sources

https://web.archive.org/web/20160527165909/http://www.makebetterthings.com/iphone/how-to-find-ip-address-of-iphone/ https://stackoverflow.com/questions/6807788/how-to-get-ip-address-of-iphone-programmatically

Android

The following permission is required in your AndroidManifest.xml:

Sources

https://stackoverflow.com/questions/16730711/get-my-wifi-ip-address-android

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment