从网络设备的IP地址列表中查找打印机IP地址



目标-我需要在wifi上检测我的Brother QL-720NW标签打印机,以便从我的应用程序打印。

我在SO上经历了各种类似的问题,比如获取打印机的IP地址,如何在Android上连接网络打印机,如何在android中获得同一wifi网络中其他主机的IP地址?etc

但以上这些都不能完全解决我的问题。

使用此如何从代码中获取设备的IP地址?我可以在我的wifi网络上获得所有ip地址的列表。

代码:

String myIpAdd= getIPAddress(true);
ArrayList<InetAddress>  inetAddresses=getConnectedDevices(myIpAdd);
public ArrayList<InetAddress> getConnectedDevices(String YourPhoneIPAddress) {
        ArrayList<InetAddress> ret = new ArrayList<InetAddress>();
        LoopCurrentIP = 0;
        String IPAddress = "";
        String[] myIPArray = YourPhoneIPAddress.split("\.");
        InetAddress currentPingAddr;
        for (int i = 0; i <= 255; i++) {
            try {
                // build the next IP address
                currentPingAddr = InetAddress.getByName(myIPArray[0] + "." +
                        myIPArray[1] + "." +
                        myIPArray[2] + "." +
                        Integer.toString(LoopCurrentIP));
                // 50ms Timeout for the "ping"
                if (currentPingAddr.isReachable(50)) {
                    ret.add(currentPingAddr);
                }
            } catch (UnknownHostException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            LoopCurrentIP++;
        }
        return ret;
    }
     /**
     * Get IP address from first non-localhost interface
     * @param ipv4  true=return ipv4, false=return ipv6
     * @return  address or empty string
     */
    public static String getIPAddress(boolean useIPv4) {
        try {
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface intf : interfaces) {
                List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
                for (InetAddress addr : addrs) {
                    if (!addr.isLoopbackAddress()) {
                        String sAddr = addr.getHostAddress().toUpperCase();
                        boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr); 
                        if (useIPv4) {
                            if (isIPv4) 
                                return sAddr;
                        } else {
                            if (!isIPv4) {
                                int delim = sAddr.indexOf('%'); // drop ip6 port suffix
                                return delim<0 ? sAddr : sAddr.substring(0, delim);
                            }
                        }
                    }
                }
            }
        } catch (Exception ex) { 
            ex.printStackTrace();
        } // for now eat exceptions
        return "";
    }

如何从Ip地址列表中检测打印机的哪个Ip地址

请帮忙。

如果您想要维护一个静态ip地址,您可能需要在打印机中设置它。如果你使用DHCP,在关闭并重新打开它之后,它可能会被分配一个新的IP。一旦它是静态的,你可以在应用程序中对其进行编码或将其放入设置中。这样你就不需要搜索ip地址了。

好吧,Rachita,我会添加(就在添加到列表之前)一个代码,通过Socket进行连接,并在端口9100上进行测试,寻找打印机。下面是一个例子。希望对有所帮助

最新更新