Ip address wifi hotspot

Android get IP-Address of a hotspot providing device

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

6 Answers 6

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).

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 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 .

Источник

Устройства не подключаются к точке доступа в Windows 10. Получение IP-адреса

Уже где-то на протяжении недели, к статьям по настройке точки доступа в Windows 10 народ оставляет очень много комментариев по проблеме, когда устройства не подключаются к запущенной на ноутбуке точке доступа. Идет просто бесконечное получение IP-адреса, аутентификация, или ошибка, что невозможно подключится к этой Wi-Fi сети. Такая проблема, это конечно же не новость, но насколько я понял, после последнего обновления Windows 10, очень много пользователей столкнулись с этой ошибкой. Многие пишут, что до обновления все работало отлично.

Что интересно, проблема с подключением устройств появляется как при раздаче Wi-Fi через командную строку, так и через «Мобильный хот-спот», который появился в Windows 10 после установки большого обновления.

В любом случае, если у вас Windows 10, вы раздали интернет по Wi-Fi с ноутбука, и устройства не подключаются к точке доступа (невозможно подключится, или получение IP-адреса) , то вы зашли по адресу. Сейчас мы попытаемся выяснить, в чем может быть проблема. В комментариях к другим статьям, уже оставили несколько советов, которые я так же добавлю в эту статью. Сам я с этой проблемой не сталкивался. Сейчас сидел, пробовал разные варианты с запуском мобильной точки доступа, но устройства у меня подключались без проблем. Ошибки я не увидел. Пробовал на двух разных компьютерах с последней версией Windows 10. Wi-Fi адаптеры разные.

Читайте также:  Талакан вай фай личный кабинет войти

Решение проблем с подключением к Wi-Fi, который раздает ноутбук

И так, если вы запустили точку доступа на своем ноутбуке (Windows 10), и при попытке подключить к ней телефон, планшет, другой ноутбук, видите ошибку «Получение IP-адреса. «, «аутентификация», «Невозможно подключится к сети» и т. д., то попробуйте выполнить следующие рекомендации.

1 Да, знаю что вряд ли, но антивирус, если он есть, лучше отключить. Будет достаточно отключения встроенного в антивирус брандмауэра. Так же можно отключить брандмауэр встроенный в Windows 10. Посмотрите и подумайте, может у вас есть еще какие-то программы, которые могли бы блокировать подключение устройств.

2 Убедитесь, что вы открыли общий доступ к интернету, в свойствах вашего подключения к интернету. Это очень важный момент, о котором я подробно писал в статьях по настройке точки доступа. О проблемах, с которыми можно столкнутся при открытии общего доступа, я писал здесь.

Если общий доступ к интернету не открыт, то в свойствах запущенного подключения, будет «IPv4-подключение» – «Без доступа к сети», или «Без доступа к интернету».

IPv4-подключение – Без доступа к сети

Так что обязательно проверьте настройки общего доступа, и убедитесь, что возле подключения, через которое вы получаете интернет, написано «Общедоступно».

3 Проверьте настройки IP для «Подключение по локальной сети*». Нажмите правой кнопкой мыши на подключение, которое появилось после запуска точки доступа (оно со звездочкой и цифрой) , и выдерите «Свойства». Затем, выделите «IP версии 4 (TCP/IPv4)», и нажмите на кнопку «Свойства». Если там уже заданы какие-то IP, и устройства к запущенной Wi-Fi сети не подключаются, то выставьте автоматическое получение IP и DNS. Перезагрузите ноутбук, запустите сеть, проверьте настройки общего доступа, и пробуйте подключится.

Не подключаются устройства к точке доступа Windows 10

Или наоборот, если там будет автоматическое получение адресов, а проблема с подключением наблюдается, то попробуйте прописать адреса вручную. Как на скриншоте ниже. DNS можете попробовать не прописывать. Главное IP-адрес и Маска подсети.

Статические настройки IP при раздаче Wi-Fi с ноутбука

4 Попробуйте удалить ваше подключение к интернету (если у вас PPPoE, высокоскоростное) , и создать его заново. Затем, в свойствах этого подключения заново открыть общий доступ к интернету для запущенного подключения. Никакие адреса вручную прописывать не нужно.

5 Проверьте, запущены ли у вас службы: «Служба автонастройки WLAN», «Маршрутизация» и «Общий доступ к подключению к Интернет (ICS)». По умолчанию, эти службы запускаются автоматически. Но, может быть такое, что по какой-то причине они остановлены. Проверить их можно в «Панель управления» — «Администрирование» — «Службы».

6 Сброс параметров протокола TCP/IP и DNS. Честно, не знаю поможет ли это, но думаю, что в крайнем случае попробовать можно. Запустите командную строку от имени администратора (нажав правой кнопкой мыши на меню пуск) . Выполните по очереди две команды:

netsh winsock reset

netsh int ip reset c:\resetlog.txt

После этого перезагрузите компьютер, и запустите раздачу Wi-Fi сети заново, откройте общий доступ.

Читайте также:  Возле знака вай фай восклицательный знак

Заметил, что в некоторых случаях помогает сброс сети. Как его сделать, писал в статье: сброс настроек сети в Windows 10.

7 Глеб в комментариях к другой статье поделился своим решением. Он просто переустановил Windows 10. После чего, и Wi-Fi, и точка доступа отлично и стабильно работают через «Мобильный Хот-Спот». Если для вас переустановка Windows не сложная процедура, то почему бы не попробовать.

Статья будет обновляться.

Просьба. Если вы знаете какие-то другие решения, или смогли избавится от проблемы с подключением каким-то из описанных выше способов, то напишите об этом в комментариях. Информация будет полезна многим. Спасибо!

209

198922

Сергей

Настройка виртуальной Wi-Fi сети

Источник

how to get the IP of the wifi hotspot in Android?

As the title says. I’m trying to be able to get the IP of the wifi iface when it is configured as hotspot. Ideally, I would like to find something that works for all the phones. Of course, the WifiManager is useless when it comes to get info from the AP. Luckily, I’ve been able to get the IPs of all the interfaces by doing this:

public String getLocalIpAddress() < try < for (Enumerationen = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) < NetworkInterface intf = en.nextElement(); for (EnumerationenumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) < InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) < Log.d("IPs", inetAddress.getHostAddress() ); >> > > catch (SocketException ex) < Log.e(LOG_TAG, ex.toString()); >return null; > 
  • Filtering by the wifi iface display name: it’s not a good approach because the display name changes from one device to another (wlan0, eth0, wl0.1, etc).
  • Filtering by its mac address: almost work, but on some devices the hotspot iface does not have a MAC address ( iface.getHardwareAddress() returns null). so not a valid solution.

7 Answers 7

Here’s what I did to get the wifi hotspot ip:

public String getWifiApIpAddress() < try < for (Enumerationen = NetworkInterface.getNetworkInterfaces(); en .hasMoreElements();) < NetworkInterface intf = en.nextElement(); if (intf.getName().contains("wlan")) < for (EnumerationenumIpAddr = intf.getInetAddresses(); enumIpAddr .hasMoreElements();) < InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress() && (inetAddress.getAddress().length == 4)) < Log.d(TAG, inetAddress.getHostAddress()); return inetAddress.getHostAddress(); >> > > > catch (SocketException ex) < Log.e(TAG, ex.toString()); >return null; > 

This will give you the IP address of any wifi device, which means it’s not just for the hotspot. If you’re connected to another wifi network (meaning you’re not in hotspot mode), it’ll return an IP.

You should check if you are in AP mode first or not. You can use this class for that: http://www.whitebyte.info/android/android-wifi-hotspot-manager-class

Hi @ajma, Thanks for sharing this valuable code, this is working and give me ip address for both «WiFi simple router network» & » WiFi Tethering or hotspot».

This is not 100% correct. I’ve found out that the network interface name varies a lot. HTC Desire Z: wl0.1; Prestigio 3540: ap0; Nexus 5/Samsung DUOS: wlan0. On the other hand, in all cases there has been only one device listed (no loopback etc).

Читайте также:  Поделиться вай фай штрих код

this code doesn’t work on some devices where the interface is named ap0. i suggest the following correction: if ((intf.getName().contains(«wlan»)) ||(intf.getName().contains(«ap»))) < on my phone there is a interface wlan0 but it has no inet address because the ip address is on the ap0. I also have the loopback interface in my case. when It is connected to a wifi router it uses the wlan0.

((WifiManager) mContext.getSystemService(Context.WIFI_SERVICE)).getDhcpInfo().serverAddress 
private String getHotspotIPAddress() < int ipAddress = mContext.getSystemService(Context.WIFI_SERVICE)).getDhcpInfo().serverAddress; 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 = ""; >return ipAddressString; > 

Here is a possible solution that utilizes WiFiManager ConnectionInfo to find corresponding NetworkInterface .

If you just need the IP then you can use:

WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); int ipAddress = wifiInfo.getIpAddress(); 

I’m sorry but that’s not the solution. As I said before, WifiManager is useless when the iface is in AP mode. Android «thinks» that Wifi is disabled. On the other hand, I tried something similar to the solution you provide, but using the MAC address instead of the IP. But as I already pointed, it does not work. For some reason, the mac address of the wifi iface is null (in some devices).

hello, my solution is open hotspot with show «fake dialog» to notify user, then dismiss when got ipaddress 🙂

When the Wifi is not setup as a hotspot, it has a name android-xx7632x324x32423 home when hotspot is turned on, that name is gone. Also the ip address changes.

So if you are able to get the Wifi config before enabling the hotspot, first of all you can use intf.getName() to get a reference to it.

Second, the ip changed, so if you know which interface the wifi is in CONNECTED mode, you can use that info to identify it later on after enabling the hotspot.

Below is some code I used for debugging. I just spit out everything I can find, make a huge mess then clean it up when I figured my problem out. GL

import java.net.InetAddress; import java.net.NetworkInterface; import java.util.Collections; import android.net.ConnectivityManager; textStatus = (TextView) findViewById(R.id.textStatus); try < for (NetworkInterface intf : Collections.list(NetworkInterface.getNetworkInterfaces())) < for (InetAddress addr : Collections.list(intf.getInetAddresses())) < if (!addr.isLoopbackAddress())< textStatus.append("\n\n IP Address: " + addr.getHostAddress() ); textStatus.append("\n" + addr.getHostName() ); textStatus.append("\n" + addr.getCanonicalHostName() ); textStatus.append("\n\n" + intf.toString() ); textStatus.append("\n\n" + intf.getName() ); textStatus.append("\n\n" + intf.isUp() ); >> > > catch (Exception ex) < textStatus.append("\n\n Error getting IP address: " + ex.getLocalizedMessage() ); >connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); allInfo = connectivity.getAllNetworkInfo(); mobileInfo = connectivity.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); textStatus.append("\n\n TypeName: " + mobileInfo.getTypeName()); textStatus.append("\n State: " + mobileInfo.getState()); textStatus.append("\n Subtype: " + mobileInfo.getSubtype()); textStatus.append("\n SubtypeName: " + mobileInfo.getSubtypeName()); textStatus.append("\n Type: " + mobileInfo.getType()); textStatus.append("\n ConnectedOrConnecting: " + mobileInfo.isConnectedOrConnecting()); textStatus.append("\n DetailedState: " + mobileInfo.getDetailedState()); textStatus.append("\n ExtraInfo: " + mobileInfo.getExtraInfo()); textStatus.append("\n Reason: " + mobileInfo.getReason()); textStatus.append("\n Failover: " + mobileInfo.isFailover()); textStatus.append("\n Roaming: " + mobileInfo.isRoaming()); textStatus.append("\n\n 0: " + allInfo[0].toString()); textStatus.append("\n\n 1: " + allInfo[1].toString()); textStatus.append("\n\n 2: " + allInfo[2].toString()); 

Источник

Оцените статью
Adblock
detector