title: UDP broadcasts - Android app requesting Java server IP Address
body: <p>I'm trying to get an android app to ping my server, and the server to return its IP Address.</p>
  
  <p>So far, I've got it to communicate with the server and the server to send a packet back, however, I need to send the server IP Address back.</p>
  
  <p>UDPService.java (server)</p>
  
  <pre><code>package mySystem.server;
  
  
  import java.net.*;
  
  
  public class UDPService implements Runnable {
  
  
  
      public static void main(String args[]) {
  
      }
  
      @Override
      public void run() {
          System.out.println("Starting");
          try {
              int port = 1989;
  
              // Create a socket to listen on the port.
              DatagramSocket dsocket = new DatagramSocket(port);
  
              // Create a buffer to read datagrams into. If a
              // packet is larger than this buffer, the
              // excess will simply be discarded!
              byte[] receiveData = new byte[1024];
              byte[] sendData = new byte[1024];
  
              // Create a packet to receive data into the buffer
              DatagramPacket packet = new DatagramPacket(receiveData, receiveData.length);
  
              System.out.println("loop start");
              // Now loop forever, waiting to receive packets and printing them.
              while (true) {
                  // Wait to receive a datagram
  
                  System.out.println("receive packet");
                  dsocket.receive(packet);
  
                  System.out.println("populate sentence");
                  String sentence = new String(packet.getData());
                    System.out.println("RECEIVED: " + sentence);
  
                  // Convert the contents to a string, and display them
                  System.out.println("send packet");
                  dsocket.send(packet);
  
                  // Reset the length of the packet before reusing it.
                  System.out.println("setlength");
                  packet.setLength(receiveData.length);
  
  
              }
          } catch (Exception e) {
              System.err.println(e);
          }
      }
  
      }
  </code></pre>
  
  <p>Discoverer.java (Phone App)</p>
  
  <pre><code>package com.krathsilvercloud.app;
  
  import java.net.*;
  import java.io.IOException;
  import java.net.DatagramPacket;
  import java.net.DatagramSocket;
  import java.net.InetAddress;
  import java.net.SocketTimeoutException;
  import java.net.UnknownHostException;
  import java.security.MessageDigest;
  import java.security.NoSuchAlgorithmException;
  
  import android.net.DhcpInfo;
  import android.net.wifi.WifiManager;
  import android.util.Log;
  
  import android.util.Log;
  import android.widget.Toast;
  
  public class Discoverer extends Thread {
  private static final String TAG = "Discovery";
  private static final String REMOTE_KEY = "b0xeeRem0tE!";
  private static final int DISCOVERY_PORT = 1989;
  private static final int TIMEOUT_MS = 5000;
  private InetAddress addr;
  
  
  private static final String mChallenge = "wuffwuff";
  private WifiManager mWifi;
  
  interface DiscoveryReceiver {
  void addAnnouncedServers(InetAddress[] host, int port[]);
  }
  
  Discoverer(WifiManager wifi) {
  mWifi = wifi;
  try {
      addr = getBroadcastAddress();
  } catch (IOException e) {
      Log.e(TAG, "Could not get bind address", e);
  }
  }
  
  public String DiscoverRun() {
  try {
  
  
      DatagramSocket socket = new DatagramSocket(DISCOVERY_PORT);
    socket.setBroadcast(true);
    socket.setSoTimeout(TIMEOUT_MS);
  
  
    sendDiscoveryRequest(socket);
    return listenForResponses(socket);
  
  } catch (IOException e) {
    Log.e(TAG, "Could not send discovery request", e);
    return null;
  }
  }
  
  
  private void sendDiscoveryRequest(DatagramSocket socket) throws IOException {
  String data = String.format(mChallenge);
  Log.d(TAG, "Sending data " + data);
  
  DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length(),
      addr, DISCOVERY_PORT);
  socket.send(packet);
  }
  
  
  private InetAddress getBroadcastAddress() throws IOException {
  DhcpInfo dhcp = mWifi.getDhcpInfo();
  if (dhcp == null) {
    Log.d(TAG, "Could not get dhcp info");
    return null;
  }
  
  int broadcast = (dhcp.ipAddress &amp; dhcp.netmask) | ~dhcp.netmask;
  byte[] quads = new byte[4];
  for (int k = 0; k &lt; 4; k++)
    quads[k] = (byte) ((broadcast &gt;&gt; k * 8) &amp; 0xFF);
  return InetAddress.getByAddress(quads);
  }
  
  
  private String listenForResponses(DatagramSocket socket) throws IOException {
  byte[] buf = new byte[1024];
  try {
    while (true) {
      DatagramPacket packet = new DatagramPacket(buf, buf.length);
      socket.receive(packet);
      Log.d(TAG, packet.getAddress().getHostAddress());
      String s = new String(packet.getData(), 0, packet.getLength());
      Log.d(TAG, "Received response " + s);
  
  
       String IPAddress2 = new String(packet.getAddress().getHostAddress());
  
      return IPAddress2;
  
    }
  } catch (SocketTimeoutException e) {
    Log.d(TAG, "Receive timed out");
    return null;
  }
  }
  
  
  private String getSignature(String challenge) {
  MessageDigest digest;
  byte[] md5sum = null;
  try {
    digest = java.security.MessageDigest.getInstance("MD5");
    digest.update(challenge.getBytes());
    digest.update(REMOTE_KEY.getBytes());
    md5sum = digest.digest();
  } catch (NoSuchAlgorithmException e) {
    e.printStackTrace();
  }
  
  StringBuffer hexString = new StringBuffer();
  for (int k = 0; k &lt; md5sum.length; ++k) {
    String s = Integer.toHexString((int) md5sum[k] &amp; 0xFF);
    if (s.length() == 1)
      hexString.append('0');
    hexString.append(s);
  }
  return hexString.toString();
  }
  
  public static void main(String[] args) {
  new Discoverer(null).start();
  while (true) {
  }
  }
  }
  </code></pre>
  
  <p>search.java (Phone App)</p>
  
  <pre><code>Button Submit = (Button) findViewById(R.id.SearchBtn);
          Submit.setOnClickListener(new View.OnClickListener() {
          public void onClick(View arg0) {
  
              Socket socket;
              PrintWriter out;
              BufferedReader in;
              String Results;
  
              String SearchStr = ((EditText) findViewById(R.id.SearchEntryTxt)).getText().toString().trim();
  
              String AndroidID = Secure.getString(getBaseContext().getContentResolver(), Secure.ANDROID_ID);
  
              dis = new Discoverer((WifiManager)getSystemService(WIFI_SERVICE));
  
              IPAddress = dis.DiscoverRun();
  
              Toast toast = Toast.makeText(getApplicationContext(), "IP Address: &gt;" + IPAddress + "&lt;", 2000);
              toast.show();
  </code></pre>
  
  <p>there's a fair bit of code after this, but it's just an if statement based on what happens if IPAddress is null</p>