I'm currently using
public static String getLocalIPAddress(WifiManager wm){
return Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
}
to get the IP-Address of the executing devices. That works fine if the device is connected to a "common" wlan-network as well as the device is connected to a wifi network which is hosted by an other android device via hotspot. If the device is not connected to any wifi network "0.0.0.0" is returned (correct). But if the device is hosting a wifi network by providing a hotspot the methode is still returning "0.0.0.0". How can I get the real IP-Address of a hotspot providing device "in its own wifi-network"?
thx & regards
You're almost right, the default IP address of hotspot is 192.168.43.1 (If device maker didn't change.)
You can check the source code of Android framework (AOSP).
/frameworks/base/services/java/com/android/server/connectivity/Tethering.java
/frameworks/base/wifi/java/android/net/wifi/WifiStateMachine.java
In the Tethering.java,
private static final String USB_NEAR_IFACE_ADDR = "192.168.42.129";
private static final int USB_PREFIX_LENGTH = 24;
// USB is 192.168.42.1 and 255.255.255.0
// Wifi is 192.168.43.1 and 255.255.255.0
// BT is limited to max default of 5 connections. 192.168.44.1 to 192.168.48.1
// with 255.255.255.0
private String[] mDhcpRange;
private static final String[] DHCP_DEFAULT_RANGE = {
"192.168.42.2", "192.168.42.254", "192.168.43.2", "192.168.43.254",
"192.168.44.2", "192.168.44.254", "192.168.45.2", "192.168.45.254",
"192.168.46.2", "192.168.46.254", "192.168.47.2", "192.168.47.254",
"192.168.48.2", "192.168.48.254",
};
Also, in the WifiStateMachine.java
private boolean startTethering(ArrayList<String> available) {
boolean wifiAvailable = false;
checkAndSetConnectivityInstance();
String[] wifiRegexs = mCm.getTetherableWifiRegexs();
for (String intf : available) {
for (String regex : wifiRegexs) {
if (intf.matches(regex)) {
InterfaceConfiguration ifcg = null;
try {
ifcg = mNwService.getInterfaceConfig(intf);
if (ifcg != null) {
/* IP/netmask: 192.168.43.1/255.255.255.0 */
ifcg.setLinkAddress(new LinkAddress(
NetworkUtils.numericToInetAddress("192.168.43.1"), 24));
ifcg.setInterfaceUp();
mNwService.setInterfaceConfig(intf, ifcg);
}
} catch (Exception e) {
loge("Error configuring interface " + intf + ", :" + e);
return false;
}
if(mCm.tether(intf) != ConnectivityManager.TETHER_ERROR_NO_ERROR) {
loge("Error tethering on " + intf);
return false;
}
mTetherInterfaceName = intf;
return true;
}
}
}
// We found no interfaces to tether
return false;
}
Therefore, the default value is 192.168.43.1 .
I tested a small couple of different devices and it seems that the hotspot providing device has always the IP 192.168.43.1 on its network. Can somebody please check/confirm this assumption?
Though this is an old question, but this might help someone. This will return the ip address of your device, as long as you've turned on the hotspot.
private String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces
.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += "SiteLocalAddress: "
+ inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
The Hotspot likely acts as a DHCP server. so,
To get IP address (server) of wifi hotspot after getting connected to it call method from remote (client)
intToInetAddress(wifiManager.getDhcpInfo().serverAddress);// get hotspot ip
then
public InetAddress intToInetAddress(int hostAddress)
{
byte[] addressBytes = {(byte) (0xff & hostAddress),
(byte) (0xff & (hostAddress >> 8)),
(byte) (0xff & (hostAddress >> 16)),
(byte) (0xff & (hostAddress >> 24))};
try
{
return InetAddress.getByAddress(addressBytes);
}
catch (UnknownHostException e)
{
throw new AssertionError();
}
}
will return ip address of connected hotspot, and yes most default IP address of hotspot is 192.168.43.1
open termux and run
ip -4 route get 8.8.8.8 | grep via
You'll something like this:
8.8.8.8 via 192.168.43.248 dev wlan0 table 1030 src 192.168.43.20 uid 12345
I was also checked several number of devices all the devices have same ip that is 192.168.43.1
you can try this address
but in android pie it becomes 192.168.43.68
Related
I have an HTC One and i root it. I connect usb-Ethernet adapter with OTG cable to my phone and set ip address on it (eth0 192.168.9.1/24).
Then i connect it to my laptop with ethernet cable and set ip address from that subnet on my laptop(192.168.9.2/24). I can ping from both side(phone --> laptop and laptop --> phone)
then i write an android program to listen to port (33333):
private class SocketServerThread extends Thread {
static final int SocketServerPORT = 33333;
int count = 0;
#Override
public void run() {
try{
serverSocket = new ServerSocket(SocketServerPORT,50,deviceAddress);
socket = serverSocket.accept();
}
}
}
private String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += "SiteLocalAddress: "+ inetAddress.getHostAddress() + "\n";
try {
deviceAddress=inetAddress.getByName(inetAddress.getHostAddress());
// deviceAddrgroup=inetAddress.getAllByName(inetAddress.getHostAddress());
}catch (UnknownHostException e){
e.printStackTrace();
}
}
}
}
When i want to connect to that port with (telnet 192.168.9.1 33333) from my laptop to my phone, it is not possible and telnet wait until timeout.
I start troubleshooting :
1 - use telnet 192.168.9.1 33333 on Terminal Emulator on my phone and i can connect to that port.
2 - i connect my phone to laptop with Wifi and i can connect to port 33333 without problem.
3 - i want to capture packet on android eth0 with Tcpdump. I copy Tcpdump on system/bin and system/xbin. When i want to execute tcpdump on Terminal Emulator, i have permission dined error! (my phone is root, and i use "su" before run that command)
4 - i use netstat on Terminal Emulator it show protocol tcp6 (::ffff:192.168.9.1)
!!!!
my question :
1 - any body had this problem before that can not connect to port on Ethernet-usb adapter?
2 - because protocol on android is tcp6, is it possible that cause the problem?
3 - any body known what is the problem of tcpdump on phone with root permission?
Objective-I need to detect my Brother QL-720NW label printer on wifi, in order to print from my application.
I have gone through various similar questions on SO like Get the IP address of printer , How to connect a network printer over Android? ,How to get IP adress of other hosts in same wifi network in android? etc
But none of the above solve my problem completely.
Using this
How to get IP address of the device from code?
I'm able to get list of all ip addresses on my wifi network .
CODE:
String myIpAdd= getIPAddress(true);
ArrayList<InetAddress> inetAddresses=getConnectedDevices(myIpAdd);
public ArrayList<InetAddress> getConnectedDevices(String YourPhoneIPAddress) {
ArrayList<InetAddress> ret = new ArrayList<InetAddress>();
LoopCurrentIP = 0;
String IPAddress = "";
String[] myIPArray = YourPhoneIPAddress.split("\\.");
InetAddress currentPingAddr;
for (int i = 0; i <= 255; i++) {
try {
// build the next IP address
currentPingAddr = InetAddress.getByName(myIPArray[0] + "." +
myIPArray[1] + "." +
myIPArray[2] + "." +
Integer.toString(LoopCurrentIP));
// 50ms Timeout for the "ping"
if (currentPingAddr.isReachable(50)) {
ret.add(currentPingAddr);
}
} catch (UnknownHostException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
LoopCurrentIP++;
}
return ret;
}
/**
* Get IP address from first non-localhost interface
* #param ipv4 true=return ipv4, false=return ipv6
* #return address or empty string
*/
public static String getIPAddress(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().toUpperCase();
boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
if (useIPv4) {
if (isIPv4)
return sAddr;
} else {
if (!isIPv4) {
int delim = sAddr.indexOf('%'); // drop ip6 port suffix
return delim<0 ? sAddr : sAddr.substring(0, delim);
}
}
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
} // for now eat exceptions
return "";
}
How can I detect which Ip address is of my printer from the list of Ip addresses??
Please help.
You might want to set it up in the printer if you are wanting to maintain a static ip address. There's a chance after turning it off and back on that it would be assigned a new IP if you are on DHCP. Once it's static you could just code it in the app or put it in a setting. That way you never need to search through the ip addresses.
Well Rachita, I would add (just before adding to the list) a code to connect via Socket and test on port 9100 looking for a printer.
Here is an example. Hope that helps
Hi I am new to android programming. I am basically trying to connect to an access point and send it come commands. After connecting to it over wifi, is it possible to programatically obtain it's IP address so that I can establish a http connection with it?
So far I know that we can obtain the device IP, but not sure if the access point IP can be obtained. Please help. Thanks in advance.
public static String getApIpAddr(Context context) {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
DhcpInfo dhcpInfo = wifiManager.getDhcpInfo();
byte[] ipAddress = convert2Bytes(dhcpInfo.serverAddress);
try {
String apIpAddr = InetAddress.getByAddress(ipAddress).getHostAddress();
return apIpAddr;
} catch (UnknownHostException e) {
e.printStackTrace();
}
return null;
}
private static byte[] convert2Bytes(int hostAddress) {
byte[] addressBytes = { (byte)(0xff & hostAddress),
(byte)(0xff & (hostAddress >> 8)),
(byte)(0xff & (hostAddress >> 16)),
(byte)(0xff & (hostAddress >> 24)) };
return addressBytes;
}
I assume you mean the outside (public) IP address of the access point that the device is connected to. If so, yes there is a simple way to get the public IP address of the access point that a device is connected to. Simply setup a script on a web server that will echo back the IP address of any client that connects to it (similar to www.whatismyip.com). Then, your device just needs to do a GET request to the script, and this will return the outside IP of the access point that the device is connected to.
I am using this to get the IP address
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();
if (!inetAddress.isLoopbackAddress())
{
//My IP address
String Ip= inetAddress.getHostAddress().toString();
}
}
}
}
catch (SocketException e)
{
Log.e("Error occurred ", e.toString());
}
I'm developing a mobile application in android.
Here I want to detect the IP address of the computer,system,etc after the usb tethering of the any android phone
I cannot find the solution.
If I put the following code then it takes the only the IP address of phone ,I need IP address of system
The following are code
ArrayList<InetAddress> arrayList=new ArrayList<InetAddress>();
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();
arrayList.add(inetAddress);
inetAddress=null;
}
}
} catch (SocketException ex) {
Log.e("SALMAN", ex.toString());
}
return arrayList;
Please help me to get the system's IP address,If we cannot able to get means so please mention me. Because I'm new to android.
I'm using android 1.6 .
There is server side application in the windows xp system. That application is a windows service which is developed by C# .net.
That windows service listen to some port such like 234,etc.If some data comes to port then it will process the data and send response through that port.
In android the android application is send the data to the windows service via socket.
The android phone is USB tethered to the system in which windows service is running.Then system assume android phone is modem and additional IP address is generated for the system.This ip address is dynamically generated when the android phone is tethered.
For data transfer form mobile to system via socket .I will need to give the ip address of the system (after tethered) in my android coding.
If there is any method in android coding to get this IP address.
All are please give your ideas on regarding this.
Its not possible to find IP address created in PC from android after tethering. There is no API or other way to find it.
If you use InetAddress , it will return 192.168.42.129 - which is a DHCP address created by USB Tethering. It wont help you to communicate.
The other way is to scan the list of IP. USB Tethering will create ip ranging for 192.168.42.1 to 192.168.42.255 . You can write a simple scanner to find which one is active. But it will take some time.
Thanks to 'Swim N Swim' above. I found a code at
Retrieve IP and MAC addresses from /proc/net/arp (Android)
and modified a bit to get first IP having valid mac address. Works great when developing as a single user on your PC with tethered. You may follow above link for further selective IPs based on company name etc.
public static String getUSBThetheredIP() {
BufferedReader bufferedReader = null;
String ips="";
try {
bufferedReader = new BufferedReader(new FileReader("/proc/net/arp"));
String line;
while ((line = bufferedReader.readLine()) != null) {
String[] splitted = line.split(" +");
if (splitted != null && splitted.length >= 4) {
String ip = splitted[0];
String mac = splitted[3];
if (mac.matches("..:..:..:..:..:..")) {
if (mac.matches("00:00:00:00:00:00")) {
//Log.d("DEBUG", "Wrong:" + mac + ":" + ip);
} else {
//Log.d("DEBUG", "Correct:" + mac + ":" + ip);
ips = ip;
break;
}
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return ips;
}
Note that each time you tether after untether, you must start your apache or other processes on PC to take new IP effective. THis is what I experienced.
My application uses multicast to send a beacon in periods along with protocol message and ip of the host joining the multicast group. In android device it is returning 127.0.0.1. I have looked around and found that many people suggested changing a host file. But, in case of android it is not possible in my context. How do I get real IP of the device, not the loopback address..
private void getLocalAddress()
{
try {
String localHost = InetAddress.getLocalHost().getHostAddress();
servers.add(localHost);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
Modified few bits and this one is working as desired for getting IPv4 addresses. !inetAddress.isLoopbackAddress() removes all the loopback address. !inetAddress.isLinkLocalAddress() and inetAddress.isSiteLocalAddress()) removes all IPv6 addresses. I hope this will help someone in here.
StringBuilder IFCONFIG=new StringBuilder();
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();
if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress() && inetAddress.isSiteLocalAddress()) {
IFCONFIG.append(inetAddress.getHostAddress().toString()+"\n");
}
}
}
} catch (SocketException ex) {
Log.e("LOG_TAG", ex.toString());
}
servers.add(IFCONFIG.toString());
Try this:-
String hostname = args[0];
try
{
InetAddress ipaddress = InetAddress.getByName(hostname);
System.out.println("IP address: " + ipaddress.getHostAddress());
}
catch ( UnknownHostException e )
{
System.out.println("Could not find IP address for: " + hostname);
}
From my tries, the maximum I could get was the wifi network address.
I don't know any other way rather than actually calling a webserver that returns the ip address. Obviously, the problem with this is that it uses the phone data.