Java doesn't recognize Wi-Fi Broadcast address - java

Alright, so I adapted the code from http://enigma2eureka.blogspot.com/2009/08/finding-your-ip-v4-broadcast-address.html in an attempt to find the IP address of the Broadcast Address on my Wi-Fi Router.
protected static InetAddress getBroadcastAddress() throws SocketException {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface networkInterface = interfaces.nextElement();
System.out.println(networkInterface.toString() + networkInterface.getInterfaceAddresses());
if (networkInterface.isLoopback())
continue; // Don't want to broadcast to the loopback interface
for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
InetAddress broadcast = interfaceAddress.getBroadcast();
if (broadcast == null)
continue;
return broadcast;
}
}
return null;
}
However, it prints the following - the name and the list of interface addresses:
name:lo (Software Loopback Interface 1)[/127.0.0.1/8 [/127.255.255.255]]
name:eth0 (Microsoft Kernel Debug Network Adapter)[]
name:net0 (Belkin USB Wireless Adaptor)[null]
...
The Belkin adapter - net0 - seems to have a null broadcast address, although it shouldn't. (I did remember to set the prefer IPv4 system property) Can anyone identify why it returns null?

Related

Binding Socket to any existing address on specific subnet

I have a java application in which I want to receive a udp broadcast telegram in a known subnet, for example 192.168.x.x (255.255.0.0). If I know the IP of the machine which is running the application, the following works (assuming the IP of the machine is 192.168.10.1)
InetAddress ip = InetAddress.getByName("192.168.10.1");
DatagramSocket socket = new DatagramSocket(2222, ip);
But if the IP is not fix, maybe from a dhcp server, how could I create a socket which is bounded to the ip which the machine gets from the dhcp server. There may be other interfaces on other subnets, so if I will use
DatagramSocket socket = new DatagramSocket(2222);
the socket is not surely bounded to the ip in the subnet with 192.168.x.x.
How could I solve this?
So if I understand your problem is to get the address assigned to an interface. I suppose you have more than one interface and you want to select one.
Also note by using DatagramSocket socket = new DatagramSocket(2222); you are binding to the wildcard address that often mean any and should work in many cases
From Oracle documentation List Network interfaces you can retrieve inetAddress from different interfaces
import java.io.*;
import java.net.*;
import java.util.*;
import static java.lang.System.out;
public class ListNets {
public static void main(String args[]) throws SocketException {
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(nets))
displayInterfaceInformation(netint);
}
static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
out.printf("Display name: %s\n", netint.getDisplayName());
out.printf("Name: %s\n", netint.getName());
Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
for (InetAddress inetAddress : Collections.list(inetAddresses)) {
out.printf("InetAddress: %s\n", inetAddress);
}
out.printf("\n");
}
}

How to check if internet through a certain interfaceaddress is up?

My pc is connected to 2 different interfaces that make access to the internet possible (a wired connection and a wifi connection to my smartphone that has mobile access, to be used in case the wired connection is lost).
When the wired connection has internet connection, I manually disconnect the other (mobile) connection at the DOS prompt :
netsh wlan disconnect interface="Wi-Fi"
Now i will check every minute or so if i can reach whatever site through the wired internet connection.
As soon as this fails, java will connect to the Wi-Fi connection again so that the loss of internet connection is minimal :
But here comes my problem : as soon as the wired internet is up and running again, I want java to automatically connect through that interface address again and disconnect the "Wi-Fi" (to limit costs ...).
I don't know if it is possible to connect to a URL starting with a predefined IP address in order to find out when the wired connection is online again.
Finally i found a solution myself, as illustrated in following code (this code runs as a test, start it on a desktop with both a wired and a wifi connection, which automatically results in closing the mobile connection, then manually disconnect the wired connection which automatically opens the mobile connection again. As soon as you manually reconnect the wired connection, the mobile connection will be disconnected again).
package testingPackage;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.util.Enumeration;
public class TestInternet {
public static void main(String[] args) {
int internet = 1;
int counter = 0;
while(counter<10){
counter = counter + 1;
int connections = 0;
Socket[] soc = new Socket[10];
try{
NetworkInterface nif = NetworkInterface.getByName("eth1");
//the right name of the wired internet can be found with following code in between /* … */
/*
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface interf = interfaces.nextElement();
if (interf.isUp() && !interf.isLoopback()) {
List<InterfaceAddress> adrs = interf.getInterfaceAddresses();
for (Iterator<InterfaceAddress> iter = adrs.iterator(); iter.hasNext();) {
InterfaceAddress adr = iter.next();
InetAddress inadr = adr.getAddress();
if (inadr instanceof Inet4Address){
NetworkInterface nif1 = NetworkInterface.getByInetAddress(inadr);
System.out.println("L30 = "+nif1);
}
}
}
}
*/
Enumeration<InetAddress> nifAddresses = nif.getInetAddresses();
while (nifAddresses.hasMoreElements()){
soc[connections] = new java.net.Socket();
soc[connections].bind(new InetSocketAddress(nifAddresses.nextElement(), 0));
connections = connections + 1;
}
soc[0].connect(new InetSocketAddress("www.google.com", 80));
if(internet==0){
System.out.println("Internet is BACK, throw out the mobile internet now !");
try{
Runtime.getRuntime().exec(new String[]{"netsh", "wlan", "disconnect", "interface=Wi-Fi"});
internet = 1;
}
catch (Exception e2) {System.out.println("Warning : Could not disconnect the mobile network !"); }
}
else{
System.out.println("Internet is UP");
}
}
catch (Exception e) {
System.out.println("enumeration failed");connections = 0;
System.out.println("Internet is still DOWN, connect to mobile internet now !");
connections = 0;
internet = 0;
//find SSID name, profile name and interface name of the wired and wireless network in DOS :
//netsh wlan show networks : returns the SSID name XXXX
//netsh wlan show profile (REQUIRED): returns the profile name YYYY
//netsh wlan show interfaces : returns the interface name
try{
Runtime.getRuntime().exec(new String[]{"netsh", "wlan", "connect","ssid=XXXX", "name=YYYY", "interface=Wi-Fi"});
}
catch (Exception e2) {System.out.println("Warning : no internet ! Could not connect to mobile network !"); }
}
System.out.println("number of wired connections = "+connections);
try {Thread.sleep(10000);}
catch (InterruptedException e) {System.out.println("no sleep"); }
}
}
}

Find IP Address of android device running web service

I have setup a web service in my android device. Now I want to send request to android from a pc through WiFi. I need the ip address of my android device to access it from a pc in the same network. How will I find the IP through my code?
Can anyone help me?
Thanks in advance..
To get device ip address use this method:
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) {
Log.e(LOG_TAG, ex.toString());
}
return null;
}
if this method returns null, there is no connection available.
If the method returns a string, this string contains the ip address currently used by the device independent of 3G or WiFi.
Just found how to get your internal IP:
Settings >> Wireless Controls >> Wi-Fi Settings
At the bottom under "Wi-Fi networks"
tap the connection you are connected to
It brings up a window with info like:
Status
Speed
Signal Strength
Security
**IP Address**

Get outgoing IP address in Java RMI

In my java RMI application, I can have instances that behave as servers both locally and on different hosts. In the latter case, how can I get my outgoing IP address so that I can set it as the argument of system property java.rmi.server.hostName?
Right now it's hard wired, but that's not a desirable solution.
You can use the classic Java way:
try {
InetAddress addr = InetAddress.getLocalHost();
// Get IP Address
byte[] ipAddr = addr.getAddress();
// Get hostname
String hostname = addr.getHostName();
} catch (UnknownHostException e) {
}
The following will display all available non-loopback IPv4 adresses on a host. You can easily adapt it to get IPv6 addresses as well.
public static void main(String...args) {
List<InetAddress> addresses = getNonLocalIPV4Addresses();
for (InetAddress addr: addresses) {
System.out.println("address: " + addr.getHostAddress());
}
}
/**
* Get a list of all known non-local IP v4 addresses for the current host.
* #return a List of <code>InetAddress</code>, may be empty but never null.
*/
public static List<InetAddress> getNonLocalIPV4Addresses() {
return getIPAddresses(new InetAddressFilter() {
public boolean accepts(InetAddress addr) {
return (addr instanceof Inet4Address)
&& !(addr.isLoopbackAddress()) || "localhost".equals(addr.getHostName()));
}
});
}
/**
* Get a list of all known IP addresses for the current host,
* according to the specified filter.
* #param filter filters out unwanted addresses.
* #return a List of <code>InetAddress</code>, may be empty but never null.
*/
public static List<InetAddress> getIPAddresses(InetAddressFilter filter) {
List<InetAddress> list = new ArrayList<InetAddress>();
try {
Enumeration<NetworkInterface> interfaces =
NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface ni = interfaces.nextElement();
Enumeration<InetAddress> addresses = ni.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
if ((filter == null) || filter.accepts(addr)) list.add(addr);
}
}
} catch(Exception e) {
e.printStackTrace();
}
return list;
}
/**
* Filter interface for the methods discovering available IP addresses.
*/
public interface InetAddressFilter {
/**
* Determine whether the specified address is accepted.
* #param addr the address to check.
* #return true if the address is accepted, false otherwise.
*/
boolean accepts(InetAddress addr);
}
I don't understand why you think you need this. The source-address in outgoing stubs is set to the host's IP address automatically. The only time you need to set this property is if the default setting isn't correct: e.g. if you have multiple NICs and only want to export via one, or if you have the Linux misconfiguration that maps your hostname to 127.0.0.1 instead of your IP address.

Getting the IP address of the android device when connected to 3G mobile network

When I am connected to WiFi, I can obtain the IP address of the Android phone.
However, when on the mobile network like 3G connection, is it still possible to obtain the IP address of the Android phone?
If yes, kindly post the code for the same.
try something like this
String ipAddress = null;
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()) {
ipAddress = inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {}
the mobile device does not have an ip when browsing over 3G connection, You will get the ISP ip on the server side code. I recommend you replace the ip with the unique id, device type and coordinates if possible.

Categories