API for configuring static IP addresses in an Android application
Asked Answered
S

1

12

Is it possible to set the IP address of an interface in Android within an application?

I can query the available interfaces and their current addresses using java.net.NetworkInterface, but this doesn't provide a facility to change these. Did I just miss something somewhere, or is it not allowed?

I was hoping to be able to make my application either change or add an alias to one or more of the existing interfaces at runtime on an "off the shelf" device. (2.1/2.2). Ideally I'd like to do this for both IPv4 and IPv6 addresses.

Solemn answered 27/5, 2010 at 15:26 Comment(0)
W
16

Settings.System includes several flags you can use for this:

  • WIFI_USE_STATIC_IP
  • WIFI_STATIC_IP
  • WIFI_STATIC_NETMASK
  • WIFI_STATIC_GATEWAY
  • WIFI_STATIC_DNS1 and WIFI_STATIC_DNS2

You'll also need the android.permission.WRITE_SETTINGS permission declared for your application.

Then in your activity:

final ContentResolver cr = getContentResolver();
Settings.System.putInt(cr, Settings.System.WIFI_USE_STATIC_IP, 1);
Settings.System.putString(cr, Settings.System.WIFI_STATIC_IP, "you.re.ip.addr");
// call putString() for each value to set for your interface

If you want to change the IP address of the carrier's 3G/4G,etc interface, I do not believe this is possible - as it is connected to the carrier and uses their DHCP/security for enabling you to connect and use their services (sort of like changing the external IP of your cable modem without the consent of your ISP).

Welterweight answered 29/8, 2011 at 15:24 Comment(4)
Great answer, thanks. I take it there's no IPv6 access through this and no way to add as an alias instead of replacing?Solemn
I haven't seen any API for setting IPv6 address, and the only examples use IPv4. However, Android does support IPv6 (Inet6Address since API 1). Could always try setting an IPv6 address using WIFI_STATIC_IP and see what happens :) Not sure about setting alias either, sorry.Welterweight
This is exactly what I wanted, however Android says that "Settings.System.WIFI_STATIC_IP" is deprecated (as of API17) and I should use WifiManager, any new code for this or a link for how to?Relic
This no longer works on Android 3.0 or later. The underlying Android implementation has changed.Aargau

© 2022 - 2024 — McMap. All rights reserved.