IP Autodiscovery

旧时模样 提交于 2019-12-03 09:07:21

The most appropriate way to do it, if they are in the same LAN is:

  • Client sends a UDP broadcast to a specific port and matching the network class (A,B,C)
  • Server is listening on this port, receives the broadcast packet and connect or send his IP to the client.

With just two network packets you know the IP address.

--EDITED--

To broadcast:

InetAddress broadcastAddr = SharedFunctions.getNetworkLocalBroadcastAddressdAsInetAddress();

    DatagramSocket socket = null;
    try {
        socket = new DatagramSocket();
        socket.setBroadcast(true);
        System.arraycopy(BROADCAST_SIGNATURE, 0, buffSend, 0, BROADCAST_SIGNATURE.length);
        DatagramPacket packet = new DatagramPacket(buffSend, buffSend.length, broadcastAddr, BROADCAST_PORT);
        socket.send(packet);
    } catch (Exception e) {
        e.printStackTrace();
        if(socket != null) try {socket.close();} catch (Exception e1) {}
    }


public static InetAddress getNetworkLocalBroadcastAddressdAsInetAddress() throws IOException {
    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
        NetworkInterface intf = en.nextElement();
        if(VERSION.SDK_INT < 9) { 
            if(!intf.getInetAddresses().nextElement().isLoopbackAddress()){
                byte[] quads = intf.getInetAddresses().nextElement().getAddress();
                quads[0] = (byte)255;
                return InetAddress.getByAddress(quads);
            }
        }else{
            if(!intf.isLoopback()){
                List<InterfaceAddress> intfaddrs = intf.getInterfaceAddresses();
                return intfaddrs.get(0).getBroadcast(); //return first IP address
            }
        }
    }
    return null;
}

To receice broadcast:

        try {
            socketReceiver = new DatagramSocket(BROADCAST_PORT);
            socketReceiver.setBroadcast(true);
            DatagramPacket packet = new DatagramPacket(buffRecv, buffRecv.length);
            while(Thread.currentThread() == cThreadReceiver){
                socketReceiver.receive(packet);
                //here you receive the packet and can check the sender IP address
            }
        } catch (Exception e) {
            e.printStackTrace();
            if(socketReceiver != null) try {socketReceiver.close();} catch (Exception e1) {}
        }

You will need to do some editing but should start you in the right track.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!