- Saved searches
- Use saved searches to filter your results more quickly
- sauravpradhan/UDP-Packet-Sender-and-Receiver
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- MarcoCiaramella / UDP.java
- Android java udp client
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
An android application which send UDP packets and receives it in another device.
sauravpradhan/UDP-Packet-Sender-and-Receiver
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
An android application which send UDP packets and receives it in another device.
- Download the source.
- In the server UDPClient project, File->MainActivity.java Line No->185, change with your wifi IP which is visible in Settings->Wifi.
- This application as of now doesnt work with GPRS.
- Build both the application UDPClient and UDPServer in android studio.
- Install APK’s in two different phones.
- In server App, Press Start server, and in client now press any of the button.
- A toast with the msg sent will be shown in server when pressed in client.
- The start server must be pressed everytime when sending a message from Client.
- Can be used to send and analyse single/multiple packets over UDP in android.
- Can also be used to take TCPDump and analyse pcap via Wireshark.
- Can be used as a study material for beginners in UDP and RTP protocals.
#Note You have to build the Client apk with your local wifi IP in android studio and press start server eveytime while sending a message.
About
An android application which send UDP packets and receives it in another device.
MarcoCiaramella / UDP.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
import java . io . ByteArrayInputStream ; |
import java . io . ByteArrayOutputStream ; |
import java . io . IOException ; |
import java . io . ObjectInputStream ; |
import java . io . ObjectOutputStream ; |
import java . net . DatagramPacket ; |
import java . net . DatagramSocket ; |
import java . net . InetAddress ; |
import java . net . SocketException ; |
import java . net . UnknownHostException ; |
/** |
* UDP sender and receiver. |
*/ |
public class UDP |
private String host ; |
private int port ; |
private DatagramSocket udpSocket ; |
private InetAddress serverAddr ; |
/** |
* UDP constructor. |
* @param host the ip address of remote host. |
* @param port the port of remote host. |
* @param timeoutMs the timeout for the socket in milliseconds. |
*/ |
public UDP ( String host , int port , int timeoutMs ) |
this . host = host ; |
this . port = port ; |
try |
udpSocket = new DatagramSocket ( port ); |
udpSocket . setSoTimeout ( timeoutMs ); |
> catch ( SocketException e ) |
e . printStackTrace (); |
> |
try |
serverAddr = InetAddress . getByName ( host ); |
> catch ( UnknownHostException e ) |
e . printStackTrace (); |
> |
> |
/** |
* Converts input Object to array of byte. |
* @param object the input object. |
* @return the array of byte. |
*/ |
public byte [] objectToBytes ( Object object ) |
try |
ByteArrayOutputStream bos = new ByteArrayOutputStream (); |
ObjectOutputStream oos = new ObjectOutputStream ( bos ); |
oos . writeObject ( object ); |
oos . flush (); |
return bos . toByteArray (); |
> catch ( IOException e ) |
e . printStackTrace (); |
> |
return null ; |
> |
/** |
* Converts the input array of byte in Object. |
* @param data the input array of byte. |
* @return the Object. |
*/ |
public Object bytesToObject ( byte [] data ) |
ByteArrayInputStream in = new ByteArrayInputStream ( data ); |
try |
ObjectInputStream is = new ObjectInputStream ( in ); |
return is . readObject (); |
> catch ( ClassNotFoundException e ) |
e . printStackTrace (); |
> catch ( IOException e ) |
e . printStackTrace (); |
> |
return null ; |
> |
/** |
* Send Object. |
* @param obj the Object to send. |
* @return true if sent, false otherwise. |
*/ |
public boolean send ( Object obj ) |
byte [] data = objectToBytes ( obj ); |
if ( data == null ) |
return false ; |
> |
DatagramPacket packet = new DatagramPacket ( data , data . length , serverAddr , port ); |
try |
udpSocket . send ( packet ); |
> catch ( IOException e ) |
e . printStackTrace (); |
return false ; |
> |
return true ; |
> |
/** |
* Send data as byte array. |
* @param data the byte array. |
* @return true if sent, false otherwise. |
*/ |
public boolean send ( byte [] data ) |
DatagramPacket packet = new DatagramPacket ( data , data . length , serverAddr , port ); |
try |
udpSocket . send ( packet ); |
> catch ( IOException e ) |
e . printStackTrace (); |
return false ; |
> |
return true ; |
> |
/** |
* Receive an Object. |
* @return the object received. |
*/ |
public Object receive () |
byte [] data = new byte [ 8000 ]; |
DatagramPacket packet = new DatagramPacket ( data , data . length ); |
try |
udpSocket . receive ( packet ); |
> catch ( IOException e ) |
e . printStackTrace (); |
return null ; |
> |
return bytesToObject ( data ); |
> |
/** |
* Receive data as byte array. |
* @param data the buffer where received data will be written. |
* @return the received data. |
*/ |
public byte [] receive ( byte [] data ) |
DatagramPacket packet = new DatagramPacket ( data , data . length ); |
try |
udpSocket . receive ( packet ); |
> catch ( IOException e ) |
e . printStackTrace (); |
return null ; |
> |
return data ; |
> |
/** |
* Close the socket. |
*/ |
public void close () |
udpSocket . close (); |
> |
> |
Android java udp client
Recently, I am developing an app with my classmates as a major homework for the course. Among them, it involves the sending and receiving of udp socket (multicast) and the sending and receiving of tcp socket. As a Java layman, after reading some theoretical materials briefly, I encountered many problems in actual programming. Then, I searched the blogs in this area on the Internet and looked around. In fact, everyone wrote basically the same, because the rules have been set. The code on the Internet was incomplete, and there were some errors and omissions. I took a lot of detours. I overturned code rewrites and debugs countless times, and finally brought out an actual working version. I hope that beginner children’s shoes can avoid some detours after seeing my blog.
Please indicate the source:
Before giving the code, let me briefly introduce what my code is doing. To
The machine starts the thread, monitors the udp broadcast from other machines, and displays information. Then, send a tcp connection to the udp source
Receive tcp connections from other machines and display information
(The udp broadcast here, I used udp multicast instead. Multicast has all the advantages of broadcasting, and has fewer disadvantages, and the implementation is relatively simple, so I won’t introduce too much here)
Specific ui operation:
The start button is used to start udp multicast, and the stop button stops sending (in fact, since the start button is pressed, only udp multicast is sent once, and the stop button is only used for setEnabled operation). There are two TextViews underneath, and the text view with the content is send --This machine sends tcp socket information; The content is received TextView display--This machine receives udp socket and tcp socket information from other machines.
A few things to note:
1. Android Manifest permission settings, sdk version information:
The functions involved in this article need to obtain some permissions for Android. Below are my permissions and version information
The information in the above entry uses-sdk needs to be synchronized in the build.gradle file.
2. Pay attention to udp broadcast, and udp broadcast monitoring needs to be bound to the same port
3. Other issues related to IDE ventilation, such as my Android Studio. Sometimes when you modify the code and re-burn the program into the phone, it will use the old version of the code in the cache to burn the program. . . Also, sometimes the project load is too slow, after the program crashes, logcat does not give out an error message for a long time, which seriously affects debugging.
4. It is recommended to use a mobile phone with a newer android sdk version for testing. When I tested it, it succeeded with a 4.4 and 5.1. Mixing with another 4.0.x is sometimes not very good.
Project link on github:
LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MyActivity"> LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="center_horizontal" > Button android:id="@+id/start" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="start" /> Button android:id="@+id/stop" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="150dp" android:text="stop" /> LinearLayout> LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="center_horizontal" > TextView android:id="@+id/send_information" android:layout_marginTop="50dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="send" android:layout_marginRight="110dp" /> TextView android:id="@+id/receive_information" android:layout_marginTop="50dp" android:text="receive" android:layout_width="wrap_content" android:layout_height="wrap_content" /> LinearLayout> LinearLayout>
(The code above on github has modularized the various internal communication classes. It is no longer like the following, all are defined in one Activity. But in order to display the functions of the app, a file is still used below.)
package com.example.user.anjay; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.example.user.anjay.R; import org.apache.http.conn.util.InetAddressUtils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.InetAddress; import java.net.MulticastSocket; import java.net.NetworkInterface; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.util.Enumeration; public class MyActivity extends Activity < private static String LOG_TAG = "WifiMulticastActivity"; Button startBroadCast; Button stopBroadCast; TextView send_label; TextView receive_label; /* 3 variables used for udpReceiveAndTcpSend */ Socket socket = null; MulticastSocket ms = null; DatagramPacket dp; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_my); startBroadCast = (Button) findViewById(R.id.start); stopBroadCast = (Button) findViewById(R.id.stop); send_label = (TextView) findViewById(R.id.send_information); receive_label = (TextView) findViewById(R.id.receive_information); send_label.append("\n\n"); receive_label.append("\n\n"); startBroadCast.setOnClickListener(listener); stopBroadCast.setOnClickListener(listener); /* Open a thread to receive tcp connection*/ new tcpReceive().start(); /* Open a thread to receive udp multicast and send tcp connection*/ new udpReceiveAndtcpSend().start(); >private View.OnClickListener listener = new View.OnClickListener() < @Override public void onClick(View v) < if (v == startBroadCast ) < startBroadCast.setEnabled(false); stopBroadCast.setEnabled(true); /* Open a new thread to send udp multicast */ new udpBroadCast("hi ~!").start(); >else < startBroadCast.setEnabled(true); stopBroadCast.setEnabled(false); >> >; /* Send udp multicast */ private class udpBroadCast extends Thread < MulticastSocket sender = null; DatagramPacket dj = null; InetAddress group = null; byte[] data = new byte[1024]; public udpBroadCast(String dataString) < data = dataString.getBytes(); >@Override public void run() < try < sender = new MulticastSocket(); group = InetAddress.getByName("224.0.0.1"); dj = new DatagramPacket(data,data.length,group,6789); sender.send(dj); sender.close(); >catch(IOException e) < e.printStackTrace(); >> > /*Receive udp multicast and send tcp connection*/ private class udpReceiveAndtcpSend extends Thread < @Override public void run() < byte[] data = new byte[1024]; try < InetAddress groupAddress = InetAddress.getByName("224.0.0.1"); ms = new MulticastSocket(6789); ms.joinGroup(groupAddress); >catch (Exception e) < e.printStackTrace(); >while (true) < try < dp = new DatagramPacket(data, data.length); if (ms != null) ms.receive(dp); >catch (Exception e) < e.printStackTrace(); >if (dp.getAddress() != null) < final String quest_ip = dp.getAddress().toString(); /* If the ip address of the udp packet is the ip address of the machine, discard the packet (not processed)*/ //String host_ip = getLocalIPAddress(); String host_ip = getLocalHostIp(); System.out.println("host_ip: -------------------- " + host_ip); System.out.println("quest_ip: -------------------- " + quest_ip.substring(1)); if( (!host_ip.equals("")) && host_ip.equals(quest_ip.substring(1)) ) < continue; >final String codeString = new String(data, 0, dp.getLength()); receive_label.post(new Runnable() < @Override public void run() < receive_label.append("Received udp request from: \n" + quest_ip.substring(1) + "\n" +"\n"); receive_label.append("Request content: "+ codeString + "\n\n"); >>); try < final String target_ip = dp.getAddress().toString().substring(1); send_label.post(new Runnable() < @Override public void run() < send_label.append("Send tcp request to: \n" + target_ip + "\n"); >>); socket = new Socket(target_ip, 8080); > catch (IOException e) < e.printStackTrace(); >finally < try < if (socket != null) socket.close(); >catch (IOException e) < e.printStackTrace(); >> > > > > /* Receive tcp connection */ private class tcpReceive extends Thread < ServerSocket serverSocket; Socket socket; BufferedReader in; String source_address; @Override public void run() < while(true) < serverSocket = null; socket = null; in = null; try < Log.i("Tcp Receive"," new ServerSocket ++++++++++"); serverSocket = new ServerSocket(8080); socket = serverSocket.accept(); Log.i("Tcp Receive"," get socket ++++++++++++++++"); if(socket != null) < in = new BufferedReader(new InputStreamReader(socket.getInputStream())); StringBuilder sb = new StringBuilder(); sb.append(socket.getInetAddress().getHostAddress()); String line = null; while ((line = in.readLine()) != null ) < sb.append(line); >source_address = sb.toString().trim(); receive_label.post(new Runnable() < @Override public void run() < receive_label.append("Receive a tcp request from: "+"\n" +source_address+"\n"+"\n\n"); >>); > > catch (IOException e1) < e1.printStackTrace(); >finally < try < if (in != null) in.close(); if (socket != null) socket.close(); if (serverSocket != null) serverSocket.close(); >catch (IOException e) < e.printStackTrace(); >> > > > public String getLocalHostIp() < String ipaddress = ""; try < Enumerationen = NetworkInterface .getNetworkInterfaces(); // Network interface used for traversal while (en.hasMoreElements()) < NetworkInterface nif = en.nextElement();// Get all the ip bound to each network interface Enumerationinet = nif.getInetAddresses(); // Traverse all ips bound to each interface while (inet.hasMoreElements()) < InetAddress ip = inet.nextElement(); if (!ip.isLoopbackAddress() && InetAddressUtils.isIPv4Address(ip .getHostAddress())) < return ip.getHostAddress(); >> > > catch(SocketException e) < Log.e("feige", "Failed to obtain local ip address"); e.printStackTrace(); >return ipaddress; > private String getLocalIPAddress() < try < for (Enumerationen = NetworkInterface .getNetworkInterfaces(); en.hasMoreElements();) < NetworkInterface intf = en.nextElement(); for (EnumerationenumIpAddr = intf .getInetAddresses(); enumIpAddr.hasMoreElements();) < InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) < return inetAddress.getHostAddress().toString(); >> > > catch (SocketException ex) < Log.e(LOG_TAG, ex.toString()); >return null; > // When the return key is pressed, close the multicast socket ms @Override public void onBackPressed() < ms.close(); super.onBackPressed(); >@Override public boolean onCreateOptionsMenu(Menu menu) < // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.my, menu); return true; >@Override public boolean onOptionsItemSelected(MenuItem item) < // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int if (id == R.id.action_settings) < return true; >return super.onOptionsItemSelected(item); > >
If there are errors or omissions, please criticize and correct them. After all, it’s a beginner, it’s impossible not to make mistakes and not to be negligent.