I came across a few discussion about getting IPv4 and IPv6 addresses programmatically on Android. The problem with these other questions and answers is:
Is there someone who could tell me how to get it done in a short and neat way without a lengthy method (if that is possible)?
IPv4 and IPv6 must coexist for some number of years, and their coexistence must be transparent to end users. If an IPv4-to-IPv6 transition is successful, end users should not even notice it. A dual-stack device is a device with network interfaces that can originate and understand both IPv4 and IPv6 packets.
Do you need both IPv4 and IPv6? When possible, it is better to keep both IPv4 and IPv6 addresses enabled. For example, using only IPv6 can cause some accessibility issues, as only about one third of the internet supports IPv6 addresses.
Go to “Settings” > “Connections” > “Mobile networks” > “Access Point Names.” Select your mobile network operator. Scroll down to “APN protocol.” To disable IPv6, select “IPv4” in the menu.
native routing between IPv4 and IPv6 networks is not possible. You can have a NAT translation from IPv6 into IPv4. For it to be effective, you might also need DNS64, which is a translation of address in DNS query to return AAAA record instead of A record.
For ipv4,ipv6 You can use
public String getIpv4() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf
.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
System.out.println("ip1--:" + inetAddress);
System.out.println("ip2--:" + inetAddress.getHostAddress());
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
String ipaddress = inetAddress.getHostAddress().toString();
return ipaddress;
}
}
}
} catch (Exception ex) {
Log.e("IP Address", ex.toString());
}
return null;
}
//ipv6
public String getLocalIpV6() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf
.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
System.out.println("ip1--:" + inetAddress);
System.out.println("ip2--:" + inetAddress.getHostAddress());
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet6Address) {
String ipaddress = inetAddress.getHostAddress().toString();
return ipaddress;
}
}
}
} catch (Exception ex) {
Log.e("IP Address", ex.toString());
}
return null;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With