- Взаимодействие Android-устройств в локальной сети
- О чем это и для кого это?
- Какие возможные способы решения существуют?
- How to Share Internet from Windows, Mac or Linux to Android device
- Windows:
- Mac:
- Linux:
- How to Use Your Android Phone as a Portable Wi-Fi Hotspot
- Share your phone’s internet connection with up to 5 other devices
- On Your Samsung Smartphone
- On Your Pixel or Stock Android Smartphone
- Find and Connect to the New Wi-Fi Hotspot
- Enable Wi-Fi Hotspot for Free on Carrier-Restricted Plans
- Tips and Considerations
- How to share Internet from Android via Ethernet
- 3 Answers 3
- Android setting
- PDA.net APP
- Gnirehtet
Взаимодействие Android-устройств в локальной сети
Предположим, мы пишем игру для Android, которая подразумевает некое сетевое взаимодействие между устройствами. Причем наши устройства находятся в одной сети и мы хотим, чтобы взаимодействие между ними осуществлялось быстро, а значит вариант с обменом данными через интернет нам не подходит. Ах да, еще одна маленькая ложка дегтя — мы хотим охватить максимально возможную аудиторию, для чего нам необходимо поддерживать Android 2.3.
Что же нам делать? Давайте поговорим об этом, а заодно рассмотрим относительно новые возможности Android SDK для соединения двух и более устройств.
О чем это и для кого это?
Как-то раз, уйдя с предыдущего места работы и погрузившись в заслуженный отдых, я принялся писать сетевую игру, в которую могут играть люди, находящиеся в одной локальной сети. И сразу же столкнулся с тем, что для нормального функционирования подобной игры нам мало соорудить сетевое взаимодействие — нам нужно сделать нормальное и быстрое обнаружение устройств в сети. Собственно, в данной статье я поделюсь своим опытом в реализации решения для данной задачи.
Сразу оговорюсь, что статья предназначена в большей мере для тех, кто имеет опыт Android-разработки, написал несколько приложений и хочет расширить свой кругозор, а также улучшить профессиональные навыки.
Какие возможные способы решения существуют?
- Android Network Service Discovery. Простой и эффективный способ обнаружения устройств. На Android Developer есть пошаговое руководство по подключению NSD, есть пример NsdChat, который можно скачать там же. Но есть один существенный минус — данный метод поддерживается только начиная с API Level 16, то есть с Android 4.1 Jelly Bean;
- Второе решение, предлагаемое нам на сайте Android Developer — Wi-Fi Peer-to-Peer. Проблема этого метода та же самая — поддерживается он только начиная с API Level 16;
- Есть странное решение, которое предлагается некоторыми программистами на Stack Overflow — самостоятельно сканировать локальную сеть на предмет наличия сервера. То есть проходить по всем адресам сети. Это уже сейчас звучит как странный велосипед, а теперь представьте, что порт нашего сервера назначается автоматически. Таким образом, сканирование даже самую небольшой сети становится достаточно долгой и трудоемкой задачей;
- Наконец, мы можем обратить внимание на Java-библиотеки и написать что-нибудь с их использованием. Например, JmDNS.
Последний способ выглядит вполне адекватным и, кажется, может обеспечить нас требуемой скоростью и удобством обнаружения устройств в сети для конечного пользователя.
Я вооружился JmDNS и решил попробовать соорудить несколько классов, которые по максимуму упростят написание описанных выше приложений. Но для начала пришлось немного повырезать дубликаты .class-файлов из jar-пакета JmDNS (проблема описана здесь):
Далее я взял исходный код NsdChat с Android Developer и изменил его служебный класс, который отвечает за инициализацию сокетов и организацию сетевого взаимодействия. Также я написал wrapper для JmDNS
Здесь размещены 4 основные функции для работы Network Discovery:
- startServer для создания сервера и регистрации соответствующего сервиса в локальной сети;
- findServers для поиска серверов;
- reset для окончания работы с Network Discovery и последующего освобождения ресурсов;
- wifiLock для запроса блокировки Wi-Fi.
В завершении я написал универсальный класс ConnectionWrapper для полноценной организации обнаружения, а также обмена сообщениями в локальной сети. Таким образом, создание сервера в конечном приложении выглядит следующим образом:
А вот и mServerHandler, использующийся для приема и обработки сообщений:
Отправка сообщений еще проще:
И, наконец, метод для обнаружения и подключения к серверу:
Как видите, все очень просто. А главное, все это работает в любой версии Android для максимум двух устройств. Но сделать так, чтобы это работало для условно неограниченного числа устройств очень легко, и очевидное решение придет к вам почти сразу после детального изучения класса Connection. Пусть это будет в качестве домашнего задания.
Ах, да, весь код доступен для изучения и использования всеми желающими в моем репозитории на GitHub.. И, конечно, не исключаю то, что некоторые вещи можно сделать лучше и проще, поэтому не стесняйтесь форкать и делать pull request’ы.
Источник
How to Share Internet from Windows, Mac or Linux to Android device
Most people are aware that Android devices can be used as a USB tether for sharing mobile data to a computer, but a nifty trick is the same procedure in reverse – that is, sharing a computer’s internet connection with the Android device. It’s known as “reverse tethering”, and it’s a fairly easy thing to setup.
There are different ways to achieve this depending on your operating system, so I will share methods for Windows, Mac, and Linux systems.
Windows:
- Download and install the Connectify Hotspot software on your computer, and proceed with the instructions on screen. Connectify Hotspot essentially creates a hotspot network through your computer’s WiFi antenna – of course, there’s a native Windows method of achieving this, but Connectify Hotspot is far less technical and more user-friendly.
- To configure Connectify Hotspot, you simply create a network by entering the desired name in the SSID field, and a password. Then you choose the connection you want to share, such as the Wi-Fi network your computer is connected to.
- In SSID type the connection name you want to give, this will be the wi-fi network name that you will see on your Android. Give your network a password if you want to use a secured network. Now select from the connection you want to share. i.e. This is the adapter which has the internet. Select the Wi-Fi network using which you will connect your Android Phone.
- Now enable your Android device’s WiFi, and click “Start Hotspot” in Connectify. You should be able to see the network on your phone’s list of available WiFi networks, so simply choose the SSID from Connectify, provide the password, and you’re all set.
Mac:
- First go to System Preferences > Sharing.
- Click on Internet Sharing, and under the dropdown box for “Share your connection from:”, choose the network your Mac is connected to, such as Ethernet or WiFi.
- Now in the box for “To computers using”, choose either Bluetooth PAN or AirPort, depending on your Mac OS/X version. However, if you’re sharing a Mac’s internet to a non-Apple device through AirPort, Mac absolutely requires a 5 or 13 letter WEP key. No more, no less.
- After you’re broadcasting the SSID from your Mac, go ahead and connect to it under your Android device’s WiFi settings.
Linux:
Please note this requires a rooted Android phone – you can search Appuals for Android root guides for your device.
You’ll also need ADB and Fastboot installed, which is easily obtained with:
sudo apt-get install android-tools-adb android-tools-fastboot
Finally, you should have a Terminal Emulator installed on your phone.
- If you meet those prerequisites, go ahead and connect your Android device to your PC over USB.
- Now launch a Linux terminal, and type the following commands:
Ifconfig
- This should display the network interface from the connected Android device, typically usb0 but in some cases it can be something else. In the commands I am giving, make sure to change usb0 to the actual network interface being used.
- So now type in the terminal:sudo ifconfig usb0 10.42.0.1 netmask 255.255.255.0
echo 1 | sudo tee /proc/sys/net/ipv4/ip_forward
sudo iptables -t nat -F
sudo iptables -t nat -A POSTROUTING -j MASQUERADE
- Now we have to type the next command on your Android’s terminal emulator :
adb shell busybox ifconfig
- After that last command, it should display a different network interface being used, for example So again, change the commands I am sharing to whatever is your actual network interface.
adb shell ifconfig rndis0 10.42.0.2 netmask 255.255.255.0
adb shell route add default gw 10.42.0.1 dev rndis0
- Now we can test the internet sharing by trying to send a ping from your phone’s Terminal Emulator, so type on your phone:
adb shell ping 8.8.8.8
If you get a successful ping, then you’re all set to go.
Источник
How to Use Your Android Phone as a Portable Wi-Fi Hotspot
Share your phone’s internet connection with up to 5 other devices
Many Android smartphones and tablets offer the ability to set up a Wi-Fi hotspot so that other devices can use your phone’s internet connection. This guide shows how to enable and use this feature on a Samsung smartphone and a Google Pixel as examples. The instructions should apply to most current Android phones and software versions.
On Your Samsung Smartphone
To turn on the Wi-Fi hotspot, follow these steps:
Go to Settings > Wireless & networks. Then, tap Connections > Mobile Hotspot and Tethering.
Turn on the Mobile Hotspot toggle switch. The phone becomes a wireless access point and displays a message in the notification bar when it’s activated.
To find the password and instructions for the hotspot, tap Mobile Hotspot. Use this password to connect your other devices to the hotspot, just as you would connect them to any other Wi-Fi network.
To change the default password, tap Password and enter a new password.
Be selective when sharing your Wi-Fi hotspot with other people. Also, data processed through this Wi-Fi feature counts against your monthly allotment of mobile data.
On Your Pixel or Stock Android Smartphone
Follow these steps to enable a hotspot on a Pixel or stock Android:
Go to Settings > Network & Internet.
Tap Hotspot & tethering > Wi-Fi hotspot.
Turn on the Wi-Fi hotspot toggle switch.
Optionally, change the hotspot name, password, and other advanced settings such as automatic shutoff and the AP Band.
Find and Connect to the New Wi-Fi Hotspot
When the hotspot is activated, connect your other devices to it as you would any other Wi-Fi network:
On your device, find the Wi-Fi hotspot. It might notify you that new wireless networks are available.
To find the wireless networks, use your Android phone and go to Settings > Wireless & networks > Wi-Fi settings. Then, follow the general Wi-Fi connection instructions for most computers.
Establish the connection by entering the password for the Wi-Fi hotspot.
Enable Wi-Fi Hotspot for Free on Carrier-Restricted Plans
You might not get internet access on your laptop or tablet after you connect because some wireless carriers restrict Wi-Fi hotspot access only to those who pay for the feature.
In this case, use an app such as Elixir 2, which toggles the Wi-Fi hotspot on or off on your home screen. This makes it possible to access the hotspot feature directly and without adding extra charges from your wireless provider. If Elixir 2 doesn’t work, FoxFi does the same thing.
Be aware that, in many cases, bypassing carrier limitations constitutes a terms-of-service violation in your contract. Use these apps at your discretion.
Tips and Considerations
When using the Wi-Fi hotspot, follow these recommendations:
Источник
How to share Internet from Android via Ethernet
The Situation: I’ve got Android running on my Cubietruck. Now I want to share the existing Internet Connection (Wifi) with my Win8 Desktop PC over Ethernet, so the stream would be
Internet –wifi→ Cubie –ethernet→ PC
I just found a thousend tutorials about making this the other way round. Is there any way to make this possible?
3 Answers 3
I’d suggest using iptables . You can find more about theme here — definitely take a look into simple usage example . https://help.ubuntu.com/community/Internet/ConnectionSharing
The only one problem is that iptables binary isn’t really built-in into Android. But hey, they came up with solution already http://forum.xda-developers.com/showthread.php?t=444004
So you can even use the example from Ubuntu help now!
Ok this is what I «THINK» you can do because I was thinking the same thing.
You need an wifi extender with ethernet port connection.
send your phone’s hotpot data to the wifi extender then connect to your router than you can do anything you want. Hope this work!!
There are a couple of ways to use your Android device as a wifi receiver.
Android setting
Some Android roms have a setting that allows for sharing the internet via USB. This setting doesn’t care where the internet is coming from, even though the setting is usually in the «tethering» menu, if you are connected to WiFi, it will share the wifi with whatever is connected to the «USB» port, even if it is an Ethernet dongle.
PDA.net APP
PDA.net (Also known as the companion app foxfi which still works on legacy devices) is a good choice. But that requires an app to be installed on your other device before you can use it. I use it all the time to give my PC internet from my android phone.
Your other option is to use software that shares the internet across the USB port via ADB.
Gnirehtet
This free open source project called (gnirehtet) will allow you to do all kinds of tethering of your android phone to a Mac, Linux or Windows computer! The minimum version of android is 5.0 (Lollipop)
Источник