2012-02-24 74 views
0

我想要一個android應用程序來ping我的服務器,並且服務器返回它的IP地址。UDP廣播 - Android應用程序請求Java服務器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語句

+2

http://www.vogella.de/articles/Eclipse/article.html#classpath_jarjavadoc – mre 2012-02-24 20:44:48

+0

該類是Java發行版的一部分,所以我真的不確定擁有源碼會對你有多好。你是什​​麼意思,班上有錯誤?你是否遇到異常?你可以發佈打電話的代碼,以及你得到的錯誤嗎? – 2012-02-24 20:46:46

+0

源未找到 源附件不包含文件DatagramPacket.class的源 您可以通過單擊更改附件源來更改源附件,其格式爲 'IPAddress2 = new String(packet.getAddress()。getAddress()) ;' – Krath 2012-02-24 21:01:28

回答

0

假設你不是指一些非標準的JDK DatagramPacket,OpenJDK應該有你正在尋找的東西。雖然我必須說,如果你在那裏發生任何錯誤,我會很驚訝。