Can't use ServerSocket on Android - android

I'm trying to listen on a port using ServerSocket on an Android device. I want to be able to connect to this port over WiFi using a computer on the same network.
I get no exception when binding it to a port, however when I check netstat it says:
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 (null):4040 (null):* LISTEN
I've tried countless ways of binding it to localhost, 0.0.0.0, the WiFi LAN IP address of the device with SocketInetAddress and InetAddress.getByName. Nothing seems to work.
When I try to connect to the port from a computer in the same WiFi (I've tried both netcat and Java's Socket.connect()), all I can see in Wireshark is an ARP request:
Who has [phone's LAN address]? Tell [computer LAN address].
This request repeat itself until timed out.
I've tried the reverse way, by setting the ServerSocket on the computer and connecting to that port from the phone, that works very well.
My testing phone is an Samsung Spica i5700 with a custom ROM.
Any ideas?
Edit:
The code is simple as this:
ServerSocket server = new ServerSocket();
server.setReuseAddr(true);
server.setTimeout(0);
server.bind(new InetSocketAddress(4040));
Socket client = null;
while((client = server.accept()) == null);
// Connected
enter code here
enter code here

Instead of using server.bind, try initializing the server socket like this:
server = new ServerSocket(4040);
Also, server.accept() will actually block until a connection is made, so you don't need that while loop (see: http://download.oracle.com/javase/1.5.0/docs/api/java/net/ServerSocket.html#accept() )

I struggled with this too and was only able to connect to my Android server by using:
ServerSocket myServerSocket = new ServerSocket();
String hostname = getLocalIpAddress();
myServerSocket.bind(new InetSocketAddress(hostname, myPort));
Where hostname was the local IP, which I got using the getLocalIpAddress() function from this page:
https://github.com/Teaonly/android-eye/blob/master/src/teaonly/droideye/MainActivity.java

I was able to get this working by using
ServerSocket server = new ServerSocket( myTcpPort, 0, addr );
where addr = InetAddress of your phone. Otherwise, it only seems to bind to localhost (127.0.0.1). Also, I'm using port 8080.

Related

Debug a server for android on nodejs

I'm trying to create a node js server for android phones. How can I create it at home in a local network without outer internet connections? I have wifi at home so my phone can connect to local network. I use official socket.io tutorial and I don't know what to write here (instead of http://chat.socket.io):
private Socket mSocket;
{
try {
mSocket = IO.socket("http://chat.socket.io");
} catch (URISyntaxException e) {}
}
open command prompt on your PC and hit ipconfig. note down your wireless IP address. Let's assume it to be 192.168.1.10. you can also set a static IP for your PC on your router. Next from your socket io code check what port number you are using. for example
http.listen(3000, function(){
console.log('listening on *:3000');
says that you are using port 3000.
Hence in your Android code you need to use http://192.168.1.10:3000/

Android - get the ip of my hotspot host

I am trying to connect 2 devices through sockets, so that they can exchange data. They are also connected via wifi hotspot. I am using Services.
Device 1 is the hotspot (where the ServerSocket is implemented), Device 2 is the one who connects to it (where the Socket is implemented).
I did some research and i am able to get the ip of each one of them (but calculated on their own class). But in order for me to create the client socket, i need the IP Address of the host (the phone that is working as a hotspot) in the other class. I can not get it on the server side, because that part of the code wont be executed, since i am using one phone to create the hotspot network and another one to connect to it.
I know that usually the IP Address of a device that is tethering is generally the same, but i can not trust that, because i gotta make sure it works on all phones.
So, how can i get the ip address of the server (hotspot host) in the client (phone connected to that hotspot) service ?
In the client side you can use dhcp.gateway to get the server side(The one who created hotspot) ip address.
private final WifiManager manager;
private final DhcpInfo dhcp;
private InetAddress getServerIP() {
manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
dhcp = manager.getDhcpInfo();
final String address = Formatter.formatIpAddress(dhcp.gateway);// gateway -
default gateway IP address
InetAddress serverIP = null;
try {
serverIP = InetAddress.getByName(address);
if(mDebug)
Log.i("Server IP ","" + serverIP.toString());
} catch (Exception e) {
if(mDebug)
Log.e("Cannot find server's IP. Error ","" + e.toString());
}
return serverIP ;
}
Determine the ip of the gateway. Programmatically getting the gateway and subnet mask details. Use the WifiManager.getDhcpInfo().gateway
.

QTcpServer - Unsupported Socket Operation on Android

I am trying to start a server on Android using QTcpServer with Qt 5.3.1 but the server does not start and I get "Unsupported Socket Operation". It works fine on Windows.
Code below:
void StartListening()
{
QHostAddress hostAddress;
hostAddress.setAddress(QString("localhost"));
hostAddress.toIPv4Address();
quint16 portNumber = 9878;
server->setMaxPendingConnections(1);
server->setProxy(QNetworkProxy::NoProxy);
if (server->listen(hostAddress, portNumber))
{
// Ok
}
else
{
Debug("Server did not start. " + server->errorString());
}
}
server->errorString() returns "Unsupported Socket Operation when it runs on Android
Isn't this supported by Qt Android or am I doing something wrong?
Thx
OK! I worked it out.
The problem is with this line:
hostAddress.setAddress(QString("localhost"));
If I replace "localhost" with "127.0.0.1", the server starts fine but no one outside the "device the server is running on" can connect to it. This means, let's say your network is using 192.168.1.xx and your Android device has the following IP address: 192.168.1.2. If you start the server with "127.0.0.1" on your Android device which has an IP address: "192.168.1.2" and then using your PC with an IP address 192.168.1.3 you do telnet 192.168.1.2 9878 it will fail to connect!
So then I decided to start the server by specifying the IP address of the Android device: 192.168.1.2
hostAddress.setAddress(QString("192.168.1.2"));
Voila! That works too! The server starts and I can connect from outside the device! For example if I do telnet 192.168.1.2 9878 from my PC while the server is started on Android, it connects! So all I need to do now is replace the hard coded IP address with the actual IP address of the device! I think QNetworkInterface::allInterfaces() or something like that will give me the ability to get the default IP address.
So just use the actual IP address of the network card rather than localhost or 127.0.0.1 and all should be Ok. All working now.

How to get IP Address of Server (Socket) in Android?

I'm creating a simple chat program that connects two android devices and they can send simple message
I run the server with Socket on a port (1234 for example)
The problem is from the client i do not know the server IP Address. (and i dont want to enter it manually)
is there a way to find a server that is running on a specific port?or can i run the server on some specific static IP that i can give it to clients?
if not is there another way to communicate with android devices that works on Android 2.2+(don't want to use wifi direct) ?
Thanks in Advance
You can broadcast a udp message from the server specifying your ip in the message. Let the client receive the broadcast and use that msg as the ip address to connect to the socket. (PS : The broadcast receiver must b allowed to receive broadcasts). And you are done!
Assign one SERVER predominantly for getting details such as IP ADDRESS, PORT number,etc.. from all the clients.
Each client when activated will contact the SERVER to register itself first and will get the details(IP ADDRESS,etc) of other device to communicate.
Now they can start waiting for specific device.
On 4.1 you can use Mutlicast DNS for service discovery via the NsdManager (if you are on the same network). If you need this to work over the Internet/3G there is really no good way to do it. You could use Google Cloud Messaging (GCM) to notify clients about the server address, but in any case you will need one 'real' server on a stable address that all participants can reach.
http://developer.android.com/reference/android/net/nsd/NsdManager.html
InetAddress.getLocalHost(); doesnot work for me but ya below code work for me
DhcpInfo dhcp = mWifiManager.getDhcpInfo();
int dhc = dhcp.serverAddress;
String dhcS = ( dhc & 0xFF)+ "."+((dhc >> 8 ) & 0xFF)+"."+((dhc >> 16 ) & 0xFF)+"."+((dhc >> 24 ) & 0xFF);
dhcS contains IP address of server,I used for Wireless connection between multiple devices.
You can use this code
connectionSocket.getRemoteSocketAddress();
No the port can never be fixed with a IP. It is always provided by the user. To know the IP address of the server automatically, you can run this program associated with the chat program.
public class Net {
public Net() throws UnknownHostException {
InetAddress ia = InetAddress.getLocalHost();
System.out.println(ia);
ia = InetAddress.getByName("local host");
System.out.println(ia);
}
public static void main(String args[]) throws UnknownHostException {
Net a = new Net();
}
}
You run can this program by the help of a button which is associated with your chat program.

Problem with socket connection by using computer name?

I want to connect my cell-phone to PC by using socket connection.
But it's only successful when I use IP Address. I try to use Computer Name but it throws UnKnowHostException.
mySocket = new Socket("192.168.1.100", 10000); //it's ok!
mySocket = new Socket("My_PC_NAME", 10000); //it throw UnKnowHostException !
My cell phone is using WIFI and its IP is : 192.168.1.99
Please help me,
Thanks !
This is quite normal as your android device hasn't access to the DNS that assigns names to IP addresses. Since it isn't part of your PC network, you can't use computer names for the socket connection.

Categories

Resources