Dart/Flutter sockets connects on random port - android

Modern programming is turning more and more frustrating. Trying to do a simple socket test app on Flutter (tested on Android). Code is simple and self explanatory:
void Connect()
{
print("connecting...");
Socket.connect("localhost", 80).then((Socket sock) {
socket = sock;
socket?.listen(dataHandler,
onError: errorHandler,
onDone: doneHandler,
cancelOnError: false);
socket?.write("GET / HTTP/1.1");
}).catchError((Object e) {
print("Unable to connect: $e");
});
}
Code throws exception. Output:
I/flutter (15930): connecting...
I/flutter (15930): Unable to connect: SocketException: OS Error: Connection refused, errno = 111, address = localhost, port = 47244
The port is always different, why TF is that happening?

The port number in the error message is the local port and not the remote port. There are an issue about this problem here: https://github.com/dart-lang/sdk/issues/12693
In short, when connecting using TCP, you need two ports. One local which is open on your device and one remote which is the port open on the system you are trying to call. After a connection is established, the communication is going between this two port numbers.
So the error indicates that your server running on localhost:80 is refusing the connection from your application. The local port number in the error message can often just be ignored since it is not really relevant to debug most issues.

Related

Error sending socket [WinError 10061]No connection could be made because the target machine actively refused it for Socket from Python to Android

I am sending a socket from a python script to my android phone and vice versa. When my android sends a packet to my python script it works but sending packets from python script to android gives this error:
Error sending socket [WinError 10061]
No connection could be made because the target machine actively refused it
Note: When sending from android to python the function uses a different socket and different port. The error occurs here s.connect((host, port))
Here is my python code to send the packet:
try:
s = socket.socket()
host = "ip_address_of_android"
port = 7801
s.connect((host, port))
print("connected")
s.listen(5)
print("sending")
text = "hello"
s.sendall(text.encode())
s.close()
except Exception as e:
print("Error sending socket ", e)
And here is my android studio code to receive the packet:
public String receives() {
Socket socket;
DataInputStream ds;
try {
socket = new Socket("ip_address_of_android", 7801);
ds = new DataInputStream(socket.getInputStream());
boolean done = false;
while (!done) {
result = ds.readUTF();
}
} catch (Exception e) {
System.out.print("error");
}
return result;
}
I am assuming it is an android firewall error but I have no idea how to fix this. Thanks in advance.
It is not an Android firewall error.
Your code has mixed together the client & server logic in a nonsensical way.
The server (Android) should listen() and accept().
The client (Python) should connect(). It should not listen().
"Target machine actively refused it" indicates that the client successfully reached the server's network interface, but the server OS said, "no-one has port 7801 open, so there's nothing for me to connect you to." The Android side never opened 7801, because it never listen()-ed.

Android to bluetooth connection only works in android debugger but not in release/run mode

As stated in the title, the my bluetooth socket will only make a connection if it is ran in the debugger. When i put a breakpoint on the connect(), it connects when i step over taking about a second to connect. When I try running in release it immediately throws an IOexception stating that read from the socket failed. I am running on android 5.1.1
Code that attempts connection
BtCommThread(BluetoothDevice btDevice, BluetoothInterface btInterface) throws IOException {//let caller handle Exception with constructor
callbacks = btInterface;
device = btDevice;
socket = device.createRfcommSocketToServiceRecord(BluetoothService.uuid);
socket.connect();//attempt connection
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));//get input
output = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));//get output
}
What could cause the bluetooth socket to work in only the debugger? I have implemented a service that retries constructing my BtCommThread and connecting the socket if it fails up to ten times. I have also tried adding a simple thread sleep before the connect thinking it could possibly be a timing issue. I am really at a loss.
Does anyone have an idea what might help?
Hardware Information
Android Phone: Google Nexus 5
Linux System: Udoo MCU running debian armhf

Connection refused 10061 socket error on connect API

I have connected a mobile Android device to a PC and trying to make a communication with it via Socket communication over TCP.I use the connect API to make the connection. My PC here acts as a client and the Android device as a server.
The connect passes the very first time but it fails when I try to reconnect, the error is 10061 - connection refused actively by host.
if(connect((SOCKET)sock,(struct sockaddr*)&addr,sizeof(addr)) == SOCKET_ERROR)
{
fprintf(stderr, "Error = %d",errno);
return;
}
This happens intermittently so the point of firewall blocking the particular port is ruled out, Also I read in some forums that this may be a issue with limited backlog, however I increased the backlog in the listen call on the server to 100 but still this issue persists.
if(listen(socket,100) == -1)
{
fprintf(stderr, "Error = %d",errno);
return;
}
Could someone throw some light on this?
Note: This occurs on a particular set of PC's and in others this doesnt occur at all. Is it dependent on any hardware configuration?

Bluecove on PC cannot detect connected android (galaxy tab 7.0)

I use this code
luugiathuy.com/2011/02/android-java-bluetooth/
The server side is the PC
the client is the device, with the app based on bluetooth chat example
The device (galaxy tab 7.0) can establish connection with the PC.
However the PC server (written in java and bluecove) did nothing, as nothing is connected.
The loop for trying to find connected device is
while(true) {
try {
System.out.println("waiting for connection...");
connection = notifier.acceptAndOpen();
Thread processThread = new Thread(new ProcessConnectionThread(connection));
processThread.start();
} catch (Exception e) {
e.printStackTrace();
return;
}
Output on PC:
uuid: 0000110100001000800000805f9b34fb
waiting for connection...
EDIT: source downloadhttps://github.com/luugiathuy/Remote-Bluetooth-Android
Same issue I got when I was trying in linux. But the reason (still not sure) when you run the bluetooth android application without turning on the Java server using bluecove, It will try to connect with the already installed bluetooth software. You may see the bluetooth icon asking for granting access to the mobile device.
To solve this, I just changed the uuid in the server and application (say from 1103 to 1101 and vice versa) and then started the server first and then the android application. Java server part started listening.
The reason I think may be the uuid when it did not found the bluecove stack service server, it got connected to the device server listening on same uuid. So after changing the uuid and making sure that the server is running before launching the android application should solve the issue.
If you are getting connected to the bluetooth system application and not to the Java bluecove server,
1) First change the uuid both server and android application.
2) Second make sure your server is running and listening on same uuid.
3) Launch the android application which try to communicate on same rfcomm connection uuid.
Server part code I took from : http://www.jsr82.com/jsr-82-sample-spp-server-and-client/
Library : http://code.google.com/p/bluecove/downloads/list
Yes, it happens with me too, I suggest you to fire following commend on shell, when it shows waiting for connection.
hcitool cc 58:C3:8B:D7:FA:F4
here 58:C3:8B:D7:FA:F4 is my device's bluetooth address, which should be replaced by your device's bluetooth address.
To get your device's bluetooth address, just start bluetooth in your device with discoverable mode and execute hcitool scan command, it will display all the active device with their name and bluetooth address.
Well you may run the above hcitool cc 58:C3:8B:D7:FA:F4 command via Java code as follows,
try
{
Process p=Runtime.getRuntime().exec("hcitool cc 58:C3:8B:D7:FA:F4");
}
catch ( Exception e )
{
}
The output from your program says it listens on UUID 0x1101. Is that true? The sample you reference shows it listening on a different UUID. Its Service Class Id is 0x04c6093b and is set as follows:
34 UUID uuid = new UUID(80087355); // "04c6093b-0000-1000-8000-00805f9b34fb"
35 String url = "btspp://localhost:" + uuid.toString() + ";name=RemoteBluetooth";
36 notifier = (StreamConnectionNotifier)Connector.open(url);
The two need to match on client and server.

address family not supproted by protocol error while connecting socket communication in android

in my app i want to receive some message form the server and based on that i want to display pop up message and for this i want to do socket communication in android.
When i am try to read response form the server using socket.getInputstream i will get error
"request time out :Address family not supported by the protocol"
Here is my code.
Socket socket = new Socket("localhost",62000));
boolean isconnect = socket.isConnected();
Log.e("Socket Connection ", String.valueOf(isconnect));
// Read and display the response message sent by server application
//
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
System.out.println("Message: " + message);
ois.close();
socket.close();
Unfortunately, this exception is caught and reported by Android, and your app doesn't get to see the stacktrace as far as I know (and it's reported at the debug level).
I'm pretty sure the cause of this exception is that an outside machine is trying to access Android and the port is closed (so the connection is refused).
Make sure:
You have a server running on the right port in Android
You turn on port forwarding for that port (e.g. you can have the service running on port 10000 in the Android emulator, and have your computer's port 20000 forward to that port)
Your client is accessing Android using 0.0.0.0 via the forwarded port (20000, not 10000)
You correctly specify TCP or UDP (might break things if it's the wrong one)
Hope this helps!

Categories

Resources