Android广播地址 [英] Android Broadcast Address

查看:19
本文介绍了Android广播地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的 Android 手机制作客户端服务器应用程序.

I am making a Client Server application for my Android phone.

我在 Python 中创建了一个 UDP 服务器,用于监听连接.

I have created a UDP Server in Python which sits and listens for connections.

我可以像 192.169.0.100 一样直接输入服务器 IP 地址,它可以正常发送数据.我也可以输入 192.168.0.255 并在 192.169.0.100 上找到服务器.

I can put either the server IP address in directly like 192.169.0.100 and it sends data fine. I can also put in 192.168.0.255 and it find the server on 192.169.0.100.

是否可以获取我的 Android 手机所连接网络的广播地址?我只会在我的 Wifi 网络或其他 Wifi 网络上使用此应用程序.

Is it possible to get the broadcast address of the network my Android phone is connected to? I am only ever going to use this application on my Wifi network or other Wifi networks.

干杯

推荐答案

由于广播IP地址是当前IP地址但以255结尾,你可以这样做:

As the broadcast IP address is the current IP address but finishing with 255, you can do something like this:

public String getLocalIpAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface
                .getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {}
    return null;
}

public static String getBroadcast() throws SocketException {
    System.setProperty("java.net.preferIPv4Stack", "true");
    for (Enumeration<NetworkInterface> niEnum = NetworkInterface.getNetworkInterfaces(); niEnum.hasMoreElements();) {
        NetworkInterface ni = niEnum.nextElement();
        if (!ni.isLoopback()) {
            for (InterfaceAddress interfaceAddress : ni.getInterfaceAddresses()) {
                return interfaceAddress.getBroadcast().toString().substring(1);
            }
        }
    }
    return null;
}

这篇关于Android广播地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆