send data from android to a udp port in web server2008 - android

i want to send data(latitude and longitude )to a web server (windows server 2008) who"s ip and udp port is known from my android application .how to do so ?
here is a sample code which i m trying but data is not received to other end
public class UDPServer extends Activity {
WebView view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState) ;
setContentView(R.layout.main);
view=(WebView) findViewById(R.id.webView1);
try {
String serverHostname = new String ("ip and udp port");
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName(serverHostname);
System.out.println ("Attemping to connect to " + IPAddress +
") via UDP port 7777");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
System.out.print("Enter Message: ");
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
Log.i("send","send");
System.out.println ("Sending data to " + sendData.length +
" bytes to server.");
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress,7777);
clientSocket.send(sendPacket);
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
System.out.println ("Waiting for return packet");
clientSocket.setSoTimeout(10000);
try {
clientSocket.receive(receivePacket);
String modifiedSentence =
new String(receivePacket.getData());
InetAddress returnIPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
System.out.println ("From server at: " + returnIPAddress +
":" + port);
System.out.println("Message: " + modifiedSentence);
}
catch (SocketTimeoutException ste)
{
System.out.println ("Timeout Occurred: Packet assumed lost");
}
clientSocket.close();
}
catch (UnknownHostException ex) {
System.err.println(ex);
}
catch (IOException ex) {
System.err.println(ex);
}
}

In UDP, unlike TCP, there is no connection established. Every UDP packet travels on it's own.
My guess is that you can send a UDP packet to server, but you do not receive the return packet. The reason for this is NAT which is used on all home routers and cellular networks. NAT prevents delivery of inbound (internet to device) packets.
To test this assumption, try this with device and server on the same local network.

Related

Sending datagram - network unreachable

I'm trying to broadcast udp packets between two Android devices on a hotspot.
I have a client that set up the hotspot, and a server that is connected to the hotspot. Sending a package from the client and receiving that packet on the server is working. But when I try to reply from the server, I get a SocketException, saying network is unreachable. I've checked the IP address and port number and both should be correct (I'm assuming the port is correct because it was taken from the packet itself).
The code for the server and client is below. Can anyone see where the code is going wrong or if it's just a network connectivity issue?
Client:
try {
//Open a random port to send the package
c = new DatagramSocket();
c.setBroadcast(true);
byte[] sendData = "DISCOVER_MV_REQUEST".getBytes();
try {
InetAddress addr = getIpAddress();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, getBroadcast(addr), 8888);
c.send(sendPacket);
} catch (Exception e) {
c.close();
e.printStackTrace();
return null;
}
// Broadcast the message over all the network interfaces
Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface networkInterface = (NetworkInterface) interfaces.nextElement();
if (networkInterface.isLoopback() || !networkInterface.isUp()) {
continue; // Don't want to broadcast to the loopback interface
}
for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
InetAddress broadcast = interfaceAddress.getBroadcast();
if (broadcast == null) {
continue;
}
// Send the broadcast package!
try {
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, broadcast, 8888);
c.send(sendPacket);
} catch (Exception e) {
c.close();
e.printStackTrace();
return null;
}
}
}
//Wait for a response
byte[] recvBuf = new byte[15000];
DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
c.receive(receivePacket);
//Check if the message is correct
String message = new String(receivePacket.getData()).trim();
if (message.equals("DISCOVER_MV_RESPONSE")) {
//DO SOMETHING WITH THE SERVER'S IP (for example, store it in your controller)
Log.v("SOCKET", "got correct response");
c.close();
return "correct";
} else {
c.close();
Log.v("SOCKET", "wrong response");
return "wrong";
}
} catch (Exception e) {
c.close();
e.printStackTrace();
return null;
}
Server:
try {
//Keep a socket open to listen to all the UDP trafic that is destined for this port
socket = new DatagramSocket(8888, InetAddress.getByName("0.0.0.0"));
socket.setBroadcast(true);
while (true) {
//Receive a packet
byte[] recvBuf = new byte[15000];
DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
socket.receive(packet);
//See if the packet holds the right command (message)
String message = new String(packet.getData()).trim();
if (message.equals("DISCOVER_MV_REQUEST")) {
byte[] sendData = "DISCOVER_MV_RESPONSE".getBytes();
//Send a response
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, packet.getAddress(), packet.getPort());
socket.send(sendPacket); //where the error happens
socket.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}

Broadcasting an UDP packet from an Android app and detecting it from Node.js

My Android app needs to know the ip of the machine running the server on my local network. My plan is to broadcast an UDP packet in my app and to send a packet back from the server, so the app know the ip.
This is my code on Android:
...
new SendUDPTask().execute();
...
/************ getBroadcastAddress: know where to send the signal to find the server ***********/
private InetAddress getBroadcastAddress() {
//setup
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
DhcpInfo dhcp = wifiManager.getDhcpInfo();
//complicated stuff
int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++)
quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
//return result
InetAddress result = null;
try {
result = InetAddress.getByAddress(quads);
} catch (UnknownHostException e) {
e.printStackTrace();
}
return result;
}
/************ sendUDP: here e send the packet that will allow us to find the server ***********/
private DatagramPacket sendUDP(String req, int port) throws IOException {
DatagramSocket socket = new DatagramSocket(port);
socket.setBroadcast(true);
InetAddress broadcastAddress = getBroadcastAddress();
DatagramPacket packet = new DatagramPacket(req.getBytes(), req.length(), broadcastAddress, port);
socket.send(packet);
byte[] buf = new byte[1024];
packet = new DatagramPacket(buf, buf.length);
socket.setSoTimeout(3000);
//We wouldn't want to think our own message is the server's response
String myAddress = getMyAddress();
socket.receive(packet);
while (packet.getAddress().getHostAddress().contains(
myAddress))
{
socket.receive(packet);
}
socket.close();
return packet;
}
/***************************** getMyAddress: the device's address *****************************/
public String getMyAddress() {
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();
if (!inetAddress.isLoopbackAddress())
return inetAddress.getHostAddress();
}
}
}
catch (SocketException e) {
e.printStackTrace();
}
return null;
}
private class SendUDPTask extends AsyncTask<String, Void, DatagramPacket> {
private Exception exception;
protected DatagramPacket doInBackground(String... params) {
try {
DatagramPacket packet = sendUDP("Ping", 31415);
Log.d("GJ", packet.getAddress().getHostAddress().toString());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(DatagramPacket packet) {
}
}
This is my code on my computer (Node.js):
var PORT = 31415;
var HOST = '127.0.0.1';
var dgram = require('dgram');
var server = dgram.createSocket('udp4');
server.on('listening', function () {
var address = server.address();
console.log('UDP Server listening on ' + address.address + ':' + address.port);
});
server.on('message', function (message, remote) {
console.log(remote.address + ':' + remote.port + ' - ' + message);
});
server.bind(PORT, HOST);
I am not sending back anything yet, but I should see the console.log. I don't see anything, which must mean the packet didn't arrive.
Does anyone have an idea?
Thanks a lot
If you bind the socket to loopback (127.0.0.1) interface you won't receive messages broadcasted in the network (192.168.1.255 in this case). In the nodejs server bind the socket to INADDR_ANY.

TCP Socket connection not working on Android 4.4

Faced a weird problem when TCP connection via Socket is not established on Android 4.4 for some reason. It works fine on 4.1.1 and 5.0.
#Override
protected Void doInBackground(Void... params) {
try {
// Creating InetAddress object from ipNumber passed via constructor from IpGetter class.
InetAddress serverAddress = InetAddress.getByName(host);
// Create a new Socket instance and connect to host
socket = new Socket(serverAddress, port);
Log.i(TAG, "Socket created: " + host + ":" + port);
// Create PrintWriter object for sending messages to server.
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); //thread freezes here
//Create BufferedReader object for receiving messages from server.
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.d(TAG, "In/Out created");
} catch (UnknownHostException e) {
Log.e(TAG, "Don't know about host: " + host + ":" + port);
connected = false;
Log.e(TAG, e.getMessage());
} catch (IOException e) {
Log.e(TAG, "Couldn't get I/O for the connection to: " + host + ":" + port);
connected = false;
Log.e(TAG, e.getMessage());
}
connected = true;
return null;
}
For some reason Thread stops on I/O creation.
Any ideas what causes this? Maybe someone seen that problem before?

Android and DatagramSockets

Hi I am currently making a project in Android using DatagramSockets and I'm not really that good in programming. I am making a registration page. My android device connects to the pc with information like username and receiptcode. My pc can receive the data. When my pc receives the data I need to check if the receiptcode is valid and unused. Then I would send to the client if it is invalid, unused, used or valid. The problem is my android device can't receive the data the pc sent. I really need your help guys. Currently I'm using an emulator. I need experts help. Here is my code:
Android Device:
public class RegisterAsyncTask extends AsyncTask<String, Integer, String>{
private DatagramSocket socket;
private DatagramPacket p;
private byte[] receiveData = new byte[1024];
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
InetAddress local = InetAddress.getByName("10.0.2.2");
socket = new DatagramSocket();
p = new DatagramPacket(params[0].getBytes(), params[0].length(),local,12345);
socket.send(p);
Log.d ("asd", "Packet sent");
p = new DatagramPacket (receiveData, receiveData.length);
Log.d ("asd", "Receiving packet");
socket.receive(p);
Log.d ("asd", "Packet received");
String message = new String (p.getData(), 0 , p.getLength());
Log.d ("asd", message);
return message;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
PC:
public class HandleAClient {
private DatagramSocket socket;
private DatagramPacket packet;
private int server_port = 12345;
private byte[] receiveData = new byte[1024];
private String receiptCode;
private InetAddress clientAddress;
private String errorMessage;
public HandleAClient (DatagramSocket socket, DatagramPacket packet) {
//Initializes instance variables
this.socket = socket;
this.packet = packet;
}
public void registerClient () {
try {
String message = new String (packet.getData(),0,packet.getLength());
Parser parser = new Parser();
receiptCode = parser.getReceiptCode(message);
System.out.println (receiptCode);
System.out.println ("Message: " + message + " on " + packet.getAddress() + " on port " + server_port);
String cadd = packet.getAddress().toString();
String newcadd = cadd.substring(1, cadd.length());
System.out.println (newcadd);
clientAddress = InetAddress.getByName(newcadd);
if (!ControlVariables.db.checkReceiptCode(receiptCode)) {
errorMessage = "Invalid Code";
System.out.println (errorMessage);
packet = new DatagramPacket(errorMessage.getBytes(), errorMessage.length(),clientAddress,12345);
socket.send(packet);
System.out.println ("error message send" + " to " +newcadd);
}
else {
ReceiptCode rc = new ReceiptCode();
rc = ControlVariables.db.getReceiptCode(receiptCode);
if (rc.getStatus().equals("used")) {
errorMessage = "Used Code";
packet = new DatagramPacket(errorMessage.getBytes(), errorMessage.length(),clientAddress,12345);
socket.send(packet);
}
else {
System.out.println (receiptCode);
System.out.println ("Message: " + message + " on " + packet.getAddress() + " on port " + server_port);
errorMessage = "Successful";
packet = new DatagramPacket(errorMessage.getBytes(), errorMessage.length(),clientAddress,12345);
socket.send(packet);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
Since I can't add a comment to your post, I'll try this way.
I've read that emulator can't use real internet connection. So I do not realize how you send data to PC.
Please provide more information on errors or info you have about not receiving packets.

A UDP receiver on android

I want to execute a udp receiver on eclipse. But its not working. The udp sender works properly and the packets are sent through the specific port. But emulator is not able to receive any packets through a udp sender. Help needed.
i don't know what your scenario is but according to my scenario i just setup a UDP server on my system(Windows 7) using php script and successfully sended and received UDP packets from android emulator with the following code.
String receivedString="";
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
sendData = stringToBeSended.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, IPAddress, port);
DatagramSocket clientSocket;
try {
clientSocket = new DatagramSocket();
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
clientSocket.receive(receivePacket);
receivedString = new String(receivePacket.getData());
clientSocket.close();
} catch (SocketException e) {
Log.v("SocketExceptionOccured", e.toString())
e.printStackTrace();
} catch (IOException e) {
Log.v("IOExceptionOccured", e.toString())
e.printStackTrace();
}
Toast.makeText(getBaseContext(), receivedString, Toast.LENGTH_LONG).show();

Categories

Resources