UDP广播 - 请求Java服务器IP地址的Android应用程序

时间:2012-02-24 20:41:51

标签: java eclipse networking udp datagram

我正在尝试使用Android应用程序ping我的服务器,并且服务器返回其IP地址。

到目前为止,我已经与服务器和服务器进行通信以发回数据包,但是,我需要重新发送服务器IP地址。

UDPService.java(服务器)

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);
        }
    }

    }

Discoverer.java(电话应用)

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 & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++)
  quads[k] = (byte) ((broadcast >> k * 8) & 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 < md5sum.length; ++k) {
  String s = Integer.toHexString((int) md5sum[k] & 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) {
}
}
}

search.java(电话应用)

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: >" + IPAddress + "<", 2000);
            toast.show();

此后有相当多的代码,但它只是基于IPAddress为空时会发生什么的if语句

1 个答案:

答案 0 :(得分:0)

假设您不是指一些非标准的JDK DatagramPacket,OpenJDK应该具有您正在寻找的内容。虽然我必须说如果你在那里遇到任何错误我会感到惊讶。