Android UDP socket unable to send data - android

I'm newbie in Android programing, and I wanted to write a piece of code which simply send a string on 127.0.0.1 and I will be able to watch it on netcat but the problem is when I try it on my android project nothing happen, so I've tried in a usual java project and everything work well.
So after a lot of research I've find... nothing
My android code :
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import java.net.*;
import java.io.*;
public class MainActivity extends Activity {
public static final int MON_PORT = 5001;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bouton2 = (Button)findViewById(R.id.envoi);
bouton2.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
int port=MON_PORT;
InetAddress adresse = InetAddress.getByName("localhost");
DatagramSocket socket;
String leMessage = "test";
int longueur = leMessage.length();
byte[] message= new byte [longueur];
message = leMessage.getBytes();
socket = new DatagramSocket();
DatagramPacket packet = new DatagramPacket(message,longueur,adresse,port);
socket.send(packet);
System.out.println("test d'execution");
socket.close();
} catch (UnknownHostException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SocketException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
And I've checked my AndroidManifest.xml and the permission :
<uses-permission android:name="android.permission.INTERNET"> </uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"> </uses-permission>
are not between the applications tag
I use an AVD based on Android API 7 but I've tried on an another AVD with API 16 but results are the same, could someone help me to find what's wrong ?
Thanks

The actual problem is that your PC has no access to the UDP packet you are sending because that packet is being sent on a different IP address that device "emulator" uses through the Loopback mechanism.
Here is the thing. You can safely assume that the Android emulator is a remote machine that is remotely connected to your PC through an IP network, it has its own IP address and can communicate with your PC. You can't just use loopback IP to communicate with your PC over IP. Please use 10.0.2.2 instead as specified in this documentation page Emulator.
Using that IP you will be able to see the packets in netcat.

Related

can't connect my android app to the net, only through my home wifi it work fine

I am building an app in Android Studio, and using a sql server, the app works great on my home WIFI network. I manage to connect to the server and do enter / read / update the data.
But the problem is that outside the home network the app does not work, why?
(its work fine in the home wifi, but when i'm going out of range of my wifi, its not working\connecting)
The SQL SERVER is on my home computer (meaning the same IP)
how to make it work on any android phone app and Everywhere ?
import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionClass {
String ip = "192.168.1.15";
String classes = "net.sourceforge.jtds.jdbc.Driver";
String db = "myDB";
String un = "mtun";
String password = "mypw";
#SuppressLint("NewApi")
public Connection CONN() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn = null;
String ConnURL;
try {
Class.forName(classes);
ConnURL = "jdbc:jtds:sqlserver://" + ip + ";"+db+";user=" + un+ ";password=" + password + ";";
conn = DriverManager.getConnection(ConnURL);
} catch (SQLException se) {
Log.e("ERROR-1", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("ERROR-2", e.getMessage());
} catch (Exception e) {
Log.e("ERROR-3", e.getMessage());
}
return conn;
}
}```

Cannot start VPN using Toyvpn

I'll try to be as descriptive as possible
I'm new to android and i'm making an android application
In that application i'd like to be able to see the address of the HTTP requests going OUT from the mobile (On what website they are heading).
So i've looked around and i found out that to do that , I need to use a VPN and android 4.0+ has a VPNService supplied from google implemented using ToyVPNService
So i got this service and started changing in it so i can use it without the need of using a server
I'd like to work the VPN as follows:
1-Capture the HTTP requests
2-Read their destination
3-Resend them back to their way
So i took the VPNService and i started modifying it so that i don't need an actual server
Here's the code i'm using
package com.example.testingservice;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.net.VpnService;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.Enumeration;
public class SO1 extends VpnService implements Handler.Callback, Runnable {
private static final String TAG = "ToyVpnService";
private Handler mHandler;
private Thread mThread;
private ParcelFileDescriptor mInterface;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// The handler is only used to show messages.
if (mHandler == null) {
mHandler = new Handler(this);
}
// Stop the previous session by interrupting the thread.
if (mThread != null) {
mThread.interrupt();
}
// Start a new session by creating a new thread.
mThread = new Thread(this, "ToyVpnThread");
mThread.start();
return START_STICKY;
}
#Override
public void onDestroy() {
if (mThread != null) {
mThread.interrupt();
}
}
#Override
public boolean handleMessage(Message message) {
if (message != null) {
Toast.makeText(this, message.what, Toast.LENGTH_SHORT).show();
}
return true;
}
#Override
public synchronized void run() {
Log.i(TAG,"running vpnService");
try {
runVpnConnection();
} catch (Exception e) {
e.printStackTrace();
//Log.e(TAG, "Got " + e.toString());
} finally {
try {
mInterface.close();
} catch (Exception e) {
// ignore
}
mInterface = null;
mHandler.sendEmptyMessage(R.string.disconnected);
Log.i(TAG, "Exiting");
}
}
private boolean runVpnConnection() throws Exception {
configure();
FileInputStream in = new FileInputStream(mInterface.getFileDescriptor());
// Allocate the buffer for a single packet.
ByteBuffer packet = ByteBuffer.allocate(32767);
// We keep forwarding packets till something goes wrong.
while (true) {
// Assume that we did not make any progress in this iteration.
boolean idle = true;
// Read the outgoing packet from the input stream.
int length = in.read(packet.array());
if (length > 0) {
Log.i(TAG,"************new packet");
System.exit(-1);
while (packet.hasRemaining()) {
Log.i(TAG,""+packet.get());
//System.out.print((char) packet.get());
}
packet.limit(length);
// tunnel.write(packet);
packet.clear();
// There might be more outgoing packets.
idle = false;
}
Thread.sleep(50);
}
}
public String getLocalIpAddress()
{
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();
Log.i(TAG,"****** INET ADDRESS ******");
Log.i(TAG,"address: "+inetAddress.getHostAddress());
Log.i(TAG,"hostname: "+inetAddress.getHostName());
Log.i(TAG,"address.toString(): "+inetAddress.getHostAddress().toString());
if (!inetAddress.isLoopbackAddress()) {
//IPAddresses.setText(inetAddress.getHostAddress().toString());
Log.i(TAG,"IS NOT LOOPBACK ADDRESS: "+inetAddress.getHostAddress().toString());
return inetAddress.getHostAddress().toString();
} else{
Log.i(TAG,"It is a loopback address");
}
}
}
} catch (SocketException ex) {
String LOG_TAG = null;
Log.e(LOG_TAG, ex.toString());
}
return null;
}
private void configure() throws Exception {
// If the old interface has exactly the same parameters, use it!
if (mInterface != null) {
Log.i(TAG, "Using the previous interface");
return;
}
// Configure a builder while parsing the parameters.
Builder builder = new Builder();
String SS=getLocalIpAddress();
builder.setMtu(1500);
// builder.addAddress("10.0.0.2", 24);
builder.addAddress(SS, 24);
// builder.addAddress(SS,24);
builder.addRoute("0.0.0.0",0);
try {
mInterface.close();
} catch (Exception e) {
// ignore
}
mInterface = builder.establish();
}}
The problem is this line
mInterface = builder.setSession("GITVPN").setConfigureIntent(mConfigureIntent).establish();
the Establish returns NULL and i can't seem to get it working
I'm thinking there is a problem with the addresses
I'd like to work it that there's no server , and there would be a tunnel that reads the packets
I've seen some other post that said i should make the addresses to 10.0.0.2 instead of external ips ( 192.168.x.x) and i should add route (0.0.0.0,0)
However the descriptor file keeps returning null and i can't seem to fix it
Any help will be appreciated , and sorry if this sounded that it was repeated but i'm super stuck and you guys are my only hope
You can't run the VpnService and establish a VPN connection without having a server that you communicate with and forwards the traffic to the internet.
Check the IP address you assigned to the interface, it should not be the same as other adapters.
What the builder operated on is a TUN device, which is created for VPN service.
So, IP address of the TUN should be proper set.
Make the address conflict with others is not a good idea.
Also, Step 3 you mentioned is not quite easy as Android not support raw socket.
just to revive an old thread...
VpnService requires a users interaction to start and won't work without it
the ToyVpnClient puts a button on the screen that the user has to click and once that's done, the Builder method will return the interface
so, steps to make it work are;
1. build a button on your app
2. onclick of that button, call VpnService.prepare(this); (this = your app context)
3. Builder.establish() will now return a VPN interface

ReadInputDiscretesResponse error (Jamod,Android)

I'm using the library Jamod and I have trouble reading the record, what I want is to read only the record number 300 PLC I'm connected, but I get read error (enters the catch). Thanks for your help
package com.JR.scada;
import java.net.InetAddress;
import net.wimpi.modbus.Modbus;
import net.wimpi.modbus.io.ModbusTCPTransaction;
import net.wimpi.modbus.msg.ReadInputDiscretesRequest;
import net.wimpi.modbus.msg.ReadInputDiscretesResponse;
import net.wimpi.modbus.msg.ReadMultipleRegistersResponse;
import net.wimpi.modbus.net.TCPMasterConnection;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Main extends Activity{
TextView text, depurar;
EditText IP;
Button boton;
int i=0;
TCPMasterConnection con = null; //the TCP connection
ModbusTCPTransaction trans = null; //the Modbus transaction
InetAddress addr = null; //direccion del esclavo
int port = Modbus.DEFAULT_PORT;//puerto por defecto 502
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.lblRegistro);
IP = (EditText) findViewById(R.id.txtIp);
depurar = (TextView) findViewById(R.id.txtdepurar);
boton = (Button)findViewById(R.id.btnVerRegistro);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onStop() {
super.onStop();
//Close the TCP connection
con.close();
}
public class conectar extends AsyncTask<String,String,Integer>{
ReadInputDiscretesRequest req = null; //the request
ReadInputDiscretesResponse res = null; //the response
int startReg;
protected void onPreExecute() {
try {
//IP address;
addr = InetAddress.getByName("212.170.50.238");
} catch (Exception e) {
Log.d("MODBUS","IP error", e);
}
}
protected Integer doInBackground(String... urls) {
try {
// Open the connection
con = new TCPMasterConnection(addr);
con.setPort(port);
con.connect ();
try {
startReg = 300;
// Prepare the request
req = new ReadInputDiscretesRequest (startReg, 1);
// Prepare the transaction
trans = new ModbusTCPTransaction(con);
trans.setRequest(req);
// execute the transaction
trans.execute();
// get the response
res = (ReadInputDiscretesResponse) trans.getResponse ();
} catch (Exception e) {
Log.d("MODBUS", "Error in reading/writing");
return 1;
}
} catch (Exception e) {
Log.d("MODBUS","connection error", e);
return 1;
}
return 0;
}
protected void onPostExecute(Integer bytes) {
if(con.isConnected()){
depurar.setText("conecta");
}
text.setText("Digital Inputs Status=" + res.getDiscretes ().toString () );
}
}
public void onClick(View v) {
// int startReg;
conectar conectamos = new conectar();
conectamos.execute("hola");
}
error:
08-21 10:01:57.554: D/MODBUS(3322): Error in reading/writing
Without knowing more about the modbus configuration on your slave PLC, my first suggestion is to try a different value for startReg, and see if the error persists. This will rule out problems with your Java.
Some test numbers that should work: 0,1,7,8
They may not all work, but at least one of them should return successfully.
If none of them return successfully, there may be a problem on the PLC configuration, or a problem with your request code.
If one of the test numbers is successful, you should post your results. If so, this means that you are attempting to access a memory location that does not exist on the PLC. If you access undefined PLC memory locations, often the PLC will abort the request (it does not just send back '0').
Followup remarks:
If you find that your code works when using different values for startReg, but not for 300, the reason has to do with memory mapping on the PLC, and this can be different for each brand/model of PLC (post your PLC brand/model if available).
You say in your question 'record 300'. When working with PLC, you usually don't refer to memory as a record. Are you trying to access Bit 300, Byte 300, Word 300, DoubleWord 300?
The real question you need to be asking, is 300 the actual modbus address you want to read, or is 300 how the PLC address is mapped (such as the 300th I/O slot, not necessarily the 300th WORD). It may be required to convert between octal, decimal, and hexidecimal addresses. Or, you may need to re-index an address (some PLCs like to start counting at 1, but generally modbus starts counting at 0).
Perhaps you meant to read BIT 300 (not record 300), which would then be 12th BIT in the 18th WORD, so it would look like this:
//
startReg = 17;
// Prepare the request
// Your 300th bit should be the last value returned.
req = new ReadInputDiscretesRequest (startReg, 12);
The different values I suggested for startReg are meant to help you discover how your PLC Inputs are mapped into modbus addresses by your Java library. This might help with number conversions.
If you keep getting exceptions in your catch block, you might want to find out more about the error.
Try changing this line from your original code:
try {
//...
} catch (Exception e) {
Log.d("MODBUS", "Error in reading/writing");
return 1;
}
into this:
try {
//...
} catch (Exception e) {
Log.d("MODBUS", e.getMessage() );
return 1;
}
Hopefully the exception will tell you more about exactly why its failing. Post those results.
If you are getting a NULL message, you might try using a debugger to manually inspect your connection instance.

Android bluetooth exception

Ok, I will try one more time.
I have a device sdptool in ubuntu the following is stated from my device:
# sdptool browse C0:1B:DC:1F:E2:F1
Browsing C0:1B:DC:1F:E2:F1 ...
Service Name: OBEX Object Push
Service RecHandle: 0x10000
Service Class ID List:
"OBEX Object Push" (0x1105)
Protocol Descriptor List:
"L2CAP" (0x0100)
"RFCOMM" (0x0003)
Channel: 9
"OBEX" (0x0008)
Profile Descriptor List:
"OBEX Object Push" (0x1105)
Version: 0x0100
As you can se the device does support the RFCOMM protocol, and OBEX for file transfer. I have a simple code for my android app which tries to connect to this device over a insecure RFCOMM channel, just for no user interaction. I want to connect to this device, so Iam using the device mac-address for connection, and the socket is ready, logcat says so.
But I only get the error:
Connection refused
Have in mind that the mac-address in the java code is different from the following listed above.
So here is my code:
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class SimpleConnectAndroidActivity extends Activity {
final static String toast = "IAM HERE";
final static String TAG ="SimpleConnect";
UUID MY_UUID;
BluetoothDevice bd;
BluetoothAdapter ba;
Button connectButton;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//MY_UUID = new UUID(0x0100 , 0x1000);
// MY_UUID = UUID.fromString("8e1f0cf7-508f-4875-b62c-fbb67fd34812");
connectButton = (Button)findViewById(R.id.button1);
connectButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
BluetoothSocket tmp = null;
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("00:1B:DC:0F:EC:7E");
Method m = null;
try {
m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] {int.class});
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
tmp = (BluetoothSocket) m.invoke(device, 1);
} catch (IllegalArgumentException e) {
Toast.makeText(getApplicationContext(), "Exception: " + e.getMessage(), Toast.LENGTH_LONG).show();
} catch (IllegalAccessException e) {
Toast.makeText(getApplicationContext(), "Exception: " + e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (InvocationTargetException e) {
Toast.makeText(getApplicationContext(), "Exception: " + e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
try {
tmp.connect();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Exception: " + e.getMessage(), Toast.LENGTH_LONG).show();
try {
tmp.close();
} catch (IOException e1) {
Toast.makeText(getApplicationContext(), "Socket closed!" + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
boolean con = tmp.isConnected();
if(con)
Toast.makeText(getApplicationContext(), "Connection was made!", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(), "Connection was not made!", Toast.LENGTH_LONG).show();
}
});
}
}
I've read several places that it should work by un-pairing and pair again, but this doesn't solve my problem.
Well, your question is over a month old, but in case you're still looking for the answer, here's one:
sdptool indicates that your RFCOMM channel is 9, but in your code you have:
tmp = (BluetoothSocket) m.invoke(device, 1);
Instead of 1 as your last argument, try 9 (if that doesn't work, try other integers, like 2 through 15).
You may also want to check out this answer.
There seem to be many variations of this question on Stack, but not a lot of understanding of the "standard" recommended code (i.e., the bluetooth chat sample modified with the lines that define and invoke "Method m")--I know because I'm one of those people who struggled with this. I was trying to connect my phone to my MacBook, and got the "connection refused" message until I realized that I needed to use 5 in the line of code above.

Connect to a bluetooth device, exception: Service discovery failed

Iam trying to connect my android device with a bluetooth compatible device. I know the mac-address of this device, as you can see in my code below. I also made several Toasts just to verify the steps in the code. It seems that I manage to create tmp = device.createRfcommSocketToServiceRecord(MY_UUID); I assume this because the Toast raises a message saying some bluetooth object address, in this line of code:
String test = tmp.toString();
Toast.makeText(getApplicationContext(), "The bluetooth socket: " +test, Toast.LENGTH_LONG).show();
But the code failes semantically when I do a tmp.connect(); I am working on API level 15, android 4.0
This i my piece of code
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class SimpleConnectAndroidActivity extends Activity {
final static String toast = "IAM HERE";
final static String TAG ="SimpleConnect";
UUID MY_UUID;
BluetoothDevice bd;
BluetoothAdapter ba;
Button connectButton;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
ba = BluetoothAdapter.getDefaultAdapter();
connectButton = (Button)findViewById(R.id.button1);
connectButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
boolean b = ba.checkBluetoothAddress("00:1B:DC:0F:EC:7E");
BluetoothSocket tmp = null;
//If valid bluetoothAddress
if(b) {
final BluetoothDevice device = ba.getRemoteDevice("00:1B:DC:0F:EC:7E"); //Getting the Verifier Bluetooth
//Trying to create a RFCOMM socket to the device
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
}
try {
tmp.connect();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "No connection was made! Exception: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
//Print out the sockets name
String test = tmp.toString();
Toast.makeText(getApplicationContext(), "The bluetooth socket: " +test, Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "FALSE, No bluetooth device with this address", Toast.LENGTH_LONG).show();
}
}
});
}
}
I am aware of that this should be done in a separate thread, and yes, I read the Bluetooth Chat example provided by Google.
Can someone help me out?
EDIT
This is the only thing I got from LogCat:
07-06 10:10:22.085: V/BluetoothSocket.cpp(14019): ...fd 63 created (RFCOMM, lm = 26)
EDIT 2
Ok, now got a new error, but its a better error. When i press the connect button, the phone asks for the pin code for pair the devices, but its already paired! After I paired it for the second time, the error says: Connection refused and another exception says, timeout.
you can use this code:Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
mySocket = (BluetoothSocket) m.invoke(device, 1);

Categories

Resources