I am in the early stages of developing a cross platform UDP server client. In my case, the clients send a broadcast to an android phone that they are connected to, via the mobile hotspot option.
I am currently testing this by having the server and client on the same device. However, I only know how to get the broadcast address, thanks to a boxee remote app.
Is anyone aware of a way to do the same as the code below, but to get the Mobile network broadcast address?
So, here is the code:
InetAddress getBroadcastAdd(Context context) throws IOException {
WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
DhcpInfo dhcp = wifi.getDhcpInfo();
int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
for (int k = 0; k &开发者_运维问答lt; 4; k++)
quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
return InetAddress.getByAddress(quads);
}
For the eagle eyed readers, you will have gathered that I actually do not need this code for the app to work as the other devices will get a broadcast address from the wifi but I do need to do some testing on this one device first.
Thanks in advance!
Most networks (Wifi and 3G) use NAT. NAT allows outbound connections, but prevents inbound (internet to device) connections.
When your server and device are both on the same local network (wifi), then this works as you are not traversing NAT gateway.
Rationale: what you are trying to do (connecting from internet to device) will not work in most networks.
Update
If your devices are both on same local network then you can use a standardised way of advertising/discovering services: Bonjour aka Zeroconf. There is java implementation that is reported to work on android: http://jmdns.sourceforge.net/
Also see http://home.heeere.com/tech-androidjmdns.html
精彩评论