Default location for data packets sent over UDP to SQL Express - android

I have created an Android application that has two input fields and a verify button. I want to send information to a SQL Express server that is on my Windows desktop over UDP connection. I have tested the connection with a utility and it works perfect but when I connect to the server, I don't know where the default location is for the information to be stored. Can anyone please help me? Below is the UDP connection code.
int port = 48569;
try {
DatagramSocket s = new DatagramSocket();
InetAddress local = InetAddress.getByName("10.3.22.218");
int msg_length = msg.length();
byte[] message = msg.getBytes();
DatagramPacket p = new DatagramPacket(message, msg_length, local, port);
s.send(p);
}catch (SocketException e) {
e.printStackTrace();
}catch (UnknownHostException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}

SQL Server on your desktop does not listen for UDP packets. Information sent with these packages will not be stored anywhere. To connect to SQL Server you will need a client (ADO.NET). Sending packages over the wire will not work. And why UDP? How you will get back the result from the "verification"?
And I believe connecting directly from your mobile app to the SQL Server is not the best option. You should either create some service layer over your database (for example WCF service) and use this API from your mobile app, or go further and look for Azure Mobile App Service or something similar.

Related

Android UDP peer to peer networking communication (without server)

I am new in Android networking and working on project p2p without server.
Initially I have to do communication between 2 devices. I achieved successful communication between two wifi networks within and behind different NATS via DataGramSocket with port forwarding via Upnp using library.
The problem i am facing is while communication between Mobile network and my wifi network or between 2 mobile network. When i send message from mobile network I am unable to receive it in my app but can listen on same port in NetCat app.
Anyone can help me in this regard?
Sending
try {
socket = new DatagramSocket(dstPort);
address = InetAddress.getByName(dstAddress);
socket.connect(address,dstPort);
socket.setBroadcast(false);
socket.setReuseAddress(true);
//sendState("Socket Status "+socket.isConnected());
String sendString = msg;
byte[] sendData = sendString.getBytes("UTF-8");
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
address, dstPort);
socket.send(sendPacket);
//sendState("Sent = "+sendData);
} catch (SocketException e) {
//sendState(e.getLocalizedMessage());
sendState("SocketException");
}
Receiving
try {
socket = new DatagramSocket(dstPort);
address = InetAddress.getByName(dstAddress);
// send request
byte[] buf = new byte[4096];
DatagramPacket packet =
new DatagramPacket(buf, buf.length, address, dstPort);
socket.connect(address,dstPort);
socket.setBroadcast(false);
socket.setReuseAddress(true);
socket.receive(packet);
String line = new String(packet.getData(), 0, packet.getLength());
sendState(line);
//sendState("Reached3");
} catch (SocketException e) {
//sendState(e.getLocalizedMessage());
sendState("SocketException");
}
Port Forwarding via UpNp
protected void setUpnp(int port_)
{
if(Connectivity.isConnectedWifi(this)) {
String myIp = getIpAddress();
int port = port_;
//creates a port mapping configuration with the external/internal port, an internal host IP, the protocol and an optional description
PortMapping[] desiredMapping = new PortMapping[2];
desiredMapping[0] = new PortMapping(port, myIp, PortMapping.Protocol.TCP);
desiredMapping[1] = new PortMapping(port, myIp, PortMapping.Protocol.UDP);
//starting the UPnP service
UpnpService upnpService = new UpnpServiceImpl(new AndroidUpnpServiceConfiguration());
RegistryListener registryListener = new PortMappingListener(desiredMapping);
upnpService.getRegistry().addListener(registryListener);
upnpService.getControlPoint().search();
}
else if(Connectivity.isConnectedMobile(this))
{
}
}
While the code here seems fine there are a couple problems with your approach.
Most mobile networks do not support UPnP port forwarding.
Depending on your network topology (which you can't always control) there might be two or more layers of NAT routing behind your public-facing address. The closest layer might support UPnP, but other layers might not.
Instead of UPnP, you might want to try the UDP hole punching technique for NAT traversal explained here and here.
While it requires a publicly available server to coordinate 'peer introduction', this technique is far more widely supported (92-96% of peers) in today's highly fragmented internet than other techniques such as UPnP port forwarding, particularly when dealing with mobile networks or multiple layers of NAT routing.
It basically boils down to UDP being a connectionless protocol (unlike TCP), so when two peers (behind NAT routers) send a UDP message to each other simultaneously, their respective NAT routers are 'tricked' into believing the inbound request from the other peer is a response to the original outgoing packet.
Besides, if you are concerned about the cost of running a server, these days you can get many years of free cloud VM server usage if you rotate membership among the main cloud vendors (AWS, Microsoft, Google, AliCloud..).

Java server socket not accepting connection over tethered connection

I've written a small file transfer program for android using standard Java sockets. The program works fine except for the following case:
I connect two android devices A and B over WiFi tethering connection. Device A is sharing the connection (enabled as wireless hotspot). When I run java server on A and client on B, the program works okay but when I run the server on device B, it can't accept any socket binding request from A. It doesn't throw any exception. Seems like the request is not reaching the server! However, both the devices are connected (ping test is okay in both directions). Can't I run socket server on a device connected as hotspot client? I thought once the networking is setup correctly, the application would work in any direction.
Also, Wireshark traces reveal nothing. What am I missing here? Please help! Here are my code snippets:
Server side (waiting for client connection):
while (true) {
try {
socket = serversocket.accept();
Runnable connectionHandler = new ConnectionHandler(
socket, fileArray, filepathNameArray,
SenderActivity.this, userID, handler);
new Thread(connectionHandler).start();
userID = userID + 1;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I would appreciate any kind of help! Thanks in advance.

Android FTP error - 425 Can't open data connection

I'm using this to upload some file. It works if I in a local connection, but if I use a external connection, i get this message: 425 Can't open data connection. from the ftp server.
I use the org.apache.commons.net.ftp.FTPClient and org.apache.commons.net.ftp.FTPFile libs.
public static String gravaImagem(String photoFile) {
FTPClient mFtp = new FTPClient();
try {
mFtp.connect(FTPHOST, PORTA);
mFtp.login(USUARIO, SENHA);
mFtp.setFileTransferMode(FTPClient.BINARY_FILE_TYPE);
mFtp.setFileType(FTPClient.BINARY_FILE_TYPE);
String origem = Environment.getExternalStorageDirectory().getPath()+File.separator+"Pictures"+File.separator+"ImageSec"+File.separator+photoFile;
FileInputStream fis = new FileInputStream(origem);
mFtp.storeFile(photoFile, fis);
mFtp.logout();
mFtp.disconnect();
} catch (SocketException e) {
e.printStackTrace();
return "Fail. (ERR#CON3)";
} catch (IOException e) {
e.printStackTrace();
return "Fail. (ERR#CON4)";
}
return "Imagem enviada ao servidor.";
}
Debug shows no exceptions.
From the internet:
First - the most common solution: change the active/passive mode
settings. But that might not work, and if it does its only a band-aid
covering up the real problem.
As I've mentioned in the past, one of the most common reasons that
this error occurs is a misconfiguration of the FTP server software
itself, related to SSL connections and firewalls, in which the
connection tries to establish itself on a bogus ip address. Read more
about FTP SSL through a NAT firewall here, some potential solutions
are included.
There are other less likely causes, such as:
The server is configured to always use the same port for passive mode connections, or the client is configured to always use the
same port for active mode connections, although in this case
usually the software in question should raise a different error
first, but I've seen this happen.
In passive mode, the firewall in front of the FTP server doesn't have the correct ports open. So the server tells the client to
connect to ipaddress 1.2.3.4 on port x, but the firewall doesn't
allow incoming connections on port x. Most firewalls are smart
enough to open up the port when it sees the PASV response. Vice
versa for active mode and the firewall in front of the FTP client.
From me:
I've used this library on andoird and it worked well, so see my copy/paste section.

Sending XMPP packets to Openfire plugin on Android

I am trying to implement a simple Android application that sends and recieves packets to and from a plugin written for Openfire server. The plugin is meant to recieve packets from a client for further processing. So it is not a chat. The following code snippet shows my way of sending packets to the server:
ConnectionConfiguration configuration = new ConnectionConfiguration(
HOST, PORT);
Connection connection = new XMPPConnection(configuration);
try {
connection.connect();
} catch (XMPPException e) {
e.printStackTrace();
}
if (connection.isConnected()) {
Packet packet = new Message();
packet.setFrom("123456789#localhost");
packet.setTo("987654321#component.localhost");
connection.sendPacket(packet);
connection.disconnect();
}
HOST and PORT are predefined constants.
I tried to use code in if clause inside the plugin and it worked perfectlly - component recieves packets and works with them. However, in my Android application this code does not work - packets do not reach the component.
So, guys, if you have any suggestions I will be greatful for your help. Maybe I use wrong technique somewhere - I am new to XMPP and Openfire.
Update
There are all needed permissions in application's manifest. And HOST is equal to a static IP address of the PC running Openfire server.
private static final String HOST = "192.168.1.100";
private static final int PORT = 5222;
In order to send packets to a server you should login to it using login() or loginAnonymously() methods of org.jivesoftware.smack.Connection class.
Thanks mr. Flow for the hint.
Connect and Disconnect
// Create the configuration for this new connection
ConnectionConfiguration config = new ConnectionConfiguration("jabber.org", 5222);
config.setCompressionEnabled(true);
config.setSASLAuthenticationEnabled(true);
Connection connection = new XMPPConnection(config);
// Connect to the server
connection.connect();
// Log into the server
connection.login("username", "password", "SomeResource");
....
// Disconnect from the server
connection.disconnect();
</code>
you should login first, here is the guide to manage connections http://www.igniterealtime.org/builds/smack/docs/latest/documentation/connections.html

Android - Server Socket

I have few question regarding Socket Communication in Android.
1)I have developed server socket app for android that listens to port 8888.
a) When i host my server on the emulator I'm unable to communicate to it through Client application that I have on my PC since both (Emulator & Client) app are on my laptop & on the same network i think that they should be able to communicate with each other.
b) When i deploy the same server app on my android mobile device and try to communicate it through the same Client Application that I have on my PC, the client application gives a timeout exception as its unable to communicate to it.
My first question is How can i test server/client socket app with Emulator & 1 android device? Can i even use my PC's client socket application to test my server socket?
**I have Client Socket Application for my other application so theres no problem with the client application.
2) My second question is to test my server app on the android device do I have to forward the desired port?
a) For Emulator: How can I forward port?
b) For Device: How can i forward port?
c) Can i forward port programmatically?
**Just for Information:
I'm using Eclipse as android developement tool.
** MY Server Code as there can also be problem with my server socket code too.
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
ServerSocket serverSocket = null;
try
{
serverSocket = new ServerSocket(SERVERPORT);
System.out.println("Listening :" + SERVERPORT);
System.out.println("Server IP:" + SERVERIP);
}
catch (Exception e)
{
e.printStackTrace();
}
while(true)
{
try
{
socket = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("ip: " + socket.getInetAddress());
String str = in.readLine();
System.out.println("message Received: " + str);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if( socket!= null)
{
try
{
socket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
if( dataInputStream!= null)
{
try
{
dataInputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
if( dataOutputStream!= null)
{
try
{
dataOutputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
Edited:
A very interesting part is that if i set port to 8080 PC's Client Socket App do connect to Android App on my android device but i don't receive socket on my server nor the data I send. Nothing happens after the link => socket = serversocket.accept();
Also I have set the permission in the manifest.
have you set the right permission inside your Manifest.xml?
<uses-permission android:name="android.permission.INTERNET" />
is needet to setup sockets
For your first question, on how to access the network from the emulator: the emulator runs on its own network address space, isolated from your PC. You have to configure network redirection to access devices on your network.
See more details in https://developer.android.com/studio/run/emulator-networking.html
Thanks to the question and answers. It helps me figure out the narrow path towards my working combination.
The procedure turned out to be trickier than we expected. The socket client side has to use "127.0.0.1", instead of "192.168.0.15" or "10.0.2.15", to connect to the Android emulator on the same computer. The following are 6 steps I tried and works.
Step 0: Go to terminal
Step 1: find out port of Android emulator console using adb, Android Debug Bridge (in my case the port is 5554)
/Users/zhijunsheng/Library/Android/sdk/platform-tools/adb devices
List of devices attached
9357cefb device
emulator-5554 device
Step 2: retrieve auth_token of Android emulator console
cat /Users/<my_home_dir>/.emulator_console_auth_token
sncfmfC+Lg9OtAT4
Step 3: connect to Android emulator console
telnet localhost 5554
Trying ::1...
Connected to localhost.
OK
Step 4: authenticate
auth sncfmfC+Lg9OtAT4
Step 5: add the redirection instruction
redir add tcp:50000:50001
I also have a video in YouTube recording what I tried.

Categories

Resources