如何从正在收听广播的多播套接字中获取IP地址?

时间:2011-12-03 05:06:07

标签: java android sockets ip lan

我的服务器创建一个侦听UDP数据包的多播套接字。它正在接收发送到网络广播地址的数据包,但我无法获取发送方的IP地址:

multisocket.getInetAddress().getHostAddress();

返回

"::" 

(我猜它是因为null getInetAddress)。

如何获取发件人的IP地址?

提示:我想这与套接字没有绑定有关,基本上是整个广播,因为那些数据包不是专门发送给我而是发送给整个网络,但它们不应该保留发送方的IP地址吗?请赐教。

以下是代码:

public void run() {
    try {
        Thread.sleep(5000);
        Log.i("SERVERUDP", "Connecting...");
        MulticastSocket multisocket = new MulticastSocket(SERVERPORT);
        multisocket.setBroadcast(true);
        Log.i("SERVERUDP","Server's IP is: " + multisocket.getLocalAddress().getHostAddress());
        getLocalIpAddress();
        while(true){
            byte[] b = new byte[65535];
            ByteArrayInputStream b_in = new ByteArrayInputStream(b);
            DatagramPacket dgram = new DatagramPacket(b, b.length);
            multisocket.receive(dgram); // blocks
            ObjectInputStream o_in = new ObjectInputStream(b_in);
            Object o = o_in.readObject();
            dgram.setLength(b.length);
            b_in.reset();
            if(o.getClass().getSimpleName().equalsIgnoreCase("Request")){
                Request request = (Request)o;
                String inetaddress = multisocket.getInetAddress().getHostAddress();
                Log.i("SERVERUDP-if", "Sending request to IP: " + inetaddress);
                new Thread(new ClientTCP(inetaddress, createRequestFromBroadcast(request))).start();
            }else if(o.getClass().getSimpleName().equalsIgnoreCase("String")){
                Log.e("SERVERUDP-elseif-string", "WTF received a string: " + (String)o);
            }else{
                Log.e("SERVERUDP-else", "Unrecognized object of type: " + o.getClass().getSimpleName());
            }
            o_in.close();
            //iteration done only once for testing!
            break;
        }
        multisocket.close();
    } catch (Exception e) {
        Log.e("SERVERUDP", "Error", e);
    }
}

1 个答案:

答案 0 :(得分:6)

您收到的每个数据包可能具有不同的源地址。所以我不确定你为什么要查看multisocket来找出源地址。

我必须承认我没有试过这个,但dgram.getSocketAddress ()调用返回后multisocket.receive会给你你想要的东西吗?