I am using the code to grab the IPv4 address my device is using:
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) { } // for now eat exceptions
return "";
}
My Samsung Galaxy Express is connected to WiFi and has a sim card with cell enabled.
The IP I get back from the code above is the 10. address which indicates the phone is using the cell signal, when I need it to use the 192. address available from the network.
Is there a way to alter the code above to choose the 192. if available? Or is this the phone that's at fault?
I have tried disabling mobile network, placing into airplane mode etc.
The only thing that worked was removing the sim card!! I can't expect users to do this just to get an Internal address?
Thanks
I'd be interested to know if there's a better way....
But for now, Look for the "wlan0" address. Also, the code below will filter out the loopback addresses for you.
List<NetworkInterface> interfaces;
try {
interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface ni : interfaces)
{
if ((ni.isLoopback() == false) && ni.isUp() && (ni.getName().equals("wlan0")))
{
// enumerate ip addresses on this network interface (e.g. ni.getInetAddresses()
// return the first one that is is Ipv4
}
}
You should combine the above code with calls to android.net.ConnectivityManager to confirm you are on wifi.
Related
This question already has an answer here:
Android Quickly Find All Local Devices on Network
(1 answer)
Closed 6 years ago.
I am trying to code in android to return the name of all devices and their ip on the wifi. I am having trouble on how to approach this. All of the examples online return only the localhost and its information. i.e.
try {
InetAddress localhost = InetAddress.getLocalHost();
System.out.println(" IP Addr: " + localhost.getHostAddress());
// Just in case this host has multiple IP addresses....
InetAddress[] allMyIps = InetAddress.getAllByName(localhost.getCanonicalHostName());
if (allMyIps != null && allMyIps.length > 1) {
System.out.println(" Full list of IP addresses:");
for (int i = 0; i < allMyIps.length; i++) {
System.out.println(" " + allMyIps[i]);
}
}
} catch (UnknownHostException e) {
System.out.println(" (error retrieving server host name)");
}
try {
System.out.println("Full list of Network Interfaces:");
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
System.out.println(" " + intf.getName() + " " + intf.getDisplayName());
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
System.out.println(" " + enumIpAddr.nextElement().toString());
}
}
} catch (SocketException e) {
System.out.println(" (error retrieving network interface list)");
}
This is not necessarily What I want, since I want to return all of the devices on the wifi.
I don't know how to go about this.
please help, thank you !
WifiManager This class provides the primary API for managing all aspects of Wi-Fi connectivity. Get an instance of this class by calling Context.getSystemService(Context.WIFI_SERVICE). It deals with several categories of items:
The list of configured networks. The list can be viewed and updated, and attributes of individual entries can be modified.
The currently active Wi-Fi network, if any. Connectivity can be established or torn down, and dynamic information about the state of the network can be queried.
Results of access point scans, containing enough information to make decisions about what access point to connect to.
It defines the names of various Intent actions that are broadcast upon any sort of change in Wi-Fi state.
WifiInfo Describes the state of any Wifi connection that is active or is in the process of being set up.
Example:
WifiManager wifiMgr = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
int ip = wifiInfo.getIpAddress();
String ipAddress = Formatter.formatIpAddress(ip);
String macAddress = wifiInfo.getMacAddress();
Ensure you have modified your manifest with the following:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Sources:
1. WifiManager
2. WifiInfo API
In trying to avoid having a hostname looked up from the public DNS for testing purposes, I need to essentially set /etc/hosts file, but I don't always know what hostnames I'll need to override the IP address for, so I'm trying to use dnsjava since the default Java DNS resolving doesn't allow for inserting directly into the cache.
Basically, you need to grab the correct DNS Type cache for dnsjava (A, AAAA, etc). Most likely A (for IPv4) or AAAA (for IPv6) is what you should use, although all of the other DNS entry types are also supported. You'll need to create a Name instance, and from that an ARecord which will be inserted into the Cache. Example is as below:
public void addHostToCacheAs(String hostname, String ipAddress) throws UnknownHostException, TextParseException {
//add an ending period assuming the hostname is truly an absolute hostname
Name host = new Name(hostname + ".");
//putting in a good long TTL, and using an A record, but AAAA might be desired as well for IPv6
Record aRec = new ARecord(host, Type.A, 9999999, getInetAddressFromString(ipAddress));
Lookup.getDefaultCache(Type.A).addRecord(aRec, Credibility.NORMAL,this);
}
public InetAddress getInetAddressFromString(String ip) throws UnknownHostException {
//Assume we are using IPv4
byte[] bytes = new byte[4];
String[] ipParts = ip.split("\\.");
InetAddress addr = null;
//if we only have one part, it must actually be a hostname, rather than a real IP
if (ipParts.length <= 1) {
addr = InetAddress.getByName(ip);
} else {
for (int i = 0; i < ipParts.length; i++) {
bytes[i] = Byte.parseByte(ipParts[i]);
}
addr = InetAddress.getByAddress(bytes);
}
return addr
}
I have the following problem: I create an ArrayList and I put in this arraylist all the IP addresses of my client (one if the client have a single network card, n if the client run on a PC having n network card) excluding the loopback adress, the point to point adress and the virtual adress.
I have do this in this way:
private static List<String> allIps = new ArrayList<String>();
static {
Enumeration<NetworkInterface> nets;
try {
nets = NetworkInterface.getNetworkInterfaces();
while(nets.hasMoreElements()) {
NetworkInterface current = nets.nextElement();
if ((current.isUp()) && (!current.isPointToPoint()) && (!current.isVirtual()) && (!current.isLoopback())) {
System.out.println(current.getName());
Enumeration<InetAddress> ee = current.getInetAddresses();
while (ee.hasMoreElements()) {
InetAddress i = ee.nextElement();
System.out.println(i.getHostAddress());
allIps.add(i.getHostAddress());
}
}
}
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("List of all IP on this client: "
+ allIps.toString());
System.out.println("Number of ip: " + allIps.size());
}
It seems work well, the only problem is that my output (in the Eclipse console) is:
eth0
fe80:0:0:0:20c:29ff:fe15:3dfe%2
192.168.15.135
List of all IP on this client: [fe80:0:0:0:20c:29ff:fe15:3dfe%2, 192.168.15.135]
Number of ip: 2
Using the debugger and the console output appear clear to me that, in this case, the only network interface present is eth0 (and this is ok) but, for this network interface, id found 2 IP adresses (the fits one is IPV6 address, the second one is the classic IPV4 address)
So it put in my adresses list allIps both.
I want select and put in my allIps list only the IPV4 adresses and not also the IPV6. What can I do to do it? Can I filter and select only IPV4 on my InetAddress object?
Tnx
Andrea
Use instanceof and the Inet4Address type:
for (NetworkInterface ni :
Collections.list(NetworkInterface.getNetworkInterfaces())) {
for (InetAddress address : Collections.list(ni.getInetAddresses())) {
if (address instanceof Inet4Address) {
System.out.println(address);
}
}
}
I need to get computer IP from Ubuntu using Java. I tried with InetAddress.getLocalHost.getHostAddress().toString(); but it returns 127.0.0.1 . I was searching for solution and found out this code:
NetworkInterface ni = NetworkInterface.getByName("eth0");
Enumeration<InetAddress> inetAddresses = ni.getInetAddresses();
while(inetAddresses.hasMoreElements()) {
InetAddress ia = inetAddresses.nextElement();
if(!ia.isLinkLocalAddress()) {
System.out.println("IP: " + ia.getHostAddress());
}
}
}
This code worked for me but problem is when computer uses "eth1" interface or computer can use wireless adapter to connect to network (wlan0). On that situatuon program will fail. Can you guys advise me with safe method to get IP from UNIX systems ? Regards.
Although a computer can have multiple network interfaces and different IPs, some of the interfaces can also be loopback or not running. To be "safe" you might even have to check names of the interface to see if you use the IP address from desired one.
Following method will give you a list of ip addresses from non-loopback, up and running interfaces.
public static List<InetAddress> getIPAddress() throws SocketException {
List<InetAddress> ipAddresses = new ArrayList<InetAddress>();
Enumeration e;
e = NetworkInterface.getNetworkInterfaces();
while (e.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) e.nextElement();
if (ni.isLoopback() || !ni.isUp()) continue;
for (Enumeration e2 = ni.getInetAddresses(); e2.hasMoreElements(); ) {
InetAddress ip = (InetAddress) e2.nextElement();
ipAddresses.add(ip);
}
}
return ipAddresses;
}
Use the enumeration getNetworkInterfaces(); and cycle through them.
Enumeration<NetworkInterface> eni = NetworkInterface.getNetworkInterfaces();
while (eni.hasMoreElements()) {
NetworkInterface ni = eni.nextElement();
Enumeration<InetAddress> inetAddresses = ni.getInetAddresses();
while(inetAddresses.hasMoreElements()) {
InetAddress ia = inetAddresses.nextElement();
if(!ia.isLinkLocalAddress()) {
System.out.println("Interface: " + ni.getName() + " IP: " + ia.getHostAddress());
}
}
}
On my linux box the isLinkLocalAddress() doesn't seem to work properly, as I get the 127.0.0.1 but that and the ipv6 version is easy to filter out manually.
Interface: wlan0 IP: 192.168.0.8
Interface: lo IP: 0:0:0:0:0:0:0:1%1
Interface: lo IP: 127.0.0.1
My machine is connected only on the wireless interface on 192.168.0.8
Check out the answers to this SO question:
How to enumerate IP addresses of all enabled NIC cards from Java?
I haven't tested it, but it seem to apply.
I want to find client computer name in java. My applciation runs in intranet. so i am using below code
public String findClientComputerName(HttpServletRequest request) {
String computerName = null;
String remoteAddress = request.getRemoteAddr();
System.out.println("remoteAddress: " + remoteAddress);
try {
InetAddress inetAddress = InetAddress.getByName(remoteAddress);
System.out.println("inetAddress: " + inetAddress);
computerName = inetAddress.getHostName();
System.out.println("computerName: " + computerName);
if (computerName.equalsIgnoreCase("localhost")) {
computerName = java.net.InetAddress.getLocalHost().getCanonicalHostName();
}
} catch (UnknownHostException e) {
log.error("UnknownHostException detected in StartAction. ", e);
}
if(StringUtils.trim(computerName).length()>0) computerName = computerName.toUpperCase();
System.out.println("computerName: " + computerName);
return computerName;
}
but sometimes i am getting host name properly but some time not. I am getting Correct IP. What may be the reason for this? Why inetAddress.getHostName(); is failing to give host name some time? Your help is very appriciated.
private String getHostName (InetAddress inaHost) throws UnknownHostException
{
try
{
Class clazz = Class.forName("java.net.InetAddress");
Constructor[] constructors = clazz.getDeclaredConstructors();
constructors[0].setAccessible(true);
InetAddress ina = (InetAddress) constructors[0].newInstance();
Field[] fields = ina.getClass().getDeclaredFields();
for (Field field: fields)
{
if (field.getName().equals("nameService"))
{
field.setAccessible(true);
Method[] methods = field.get(null).getClass().getDeclaredMethods();
for (Method method: methods)
{
if (method.getName().equals("getHostByAddr"))
{
method.setAccessible(true);
return (String) method.invoke(field.get (null), inaHost.getAddress());
}
}
}
}
} catch (ClassNotFoundException cnfe) {
} catch (IllegalAccessException iae) {
} catch (InstantiationException ie) {
} catch (InvocationTargetException ite) {
throw (UnknownHostException) ite.getCause();
}
return null;
}
above function returning host name correctly in Intranet. for local it will return localhost.
To get the name for local host we use computerName = java.net.InetAddress.getLocalHost().getCanonicalHostName();
HttpServletRequest will return the IP address (either v4 or v6) of whoever is hitting your servlet. That address may or may not resolve to a valid hostname. InetAddress.getHostName() does a reverse DNS resolution of the IP address. It is not required that each IP address allocated maps back to a valid DNS entry. There are, in fact, a large percent of IP addresses in the world that will not resolve to a hostname.
You can see the same thing using the 'host' command on a linux box to look up the reverse DNS entry (if any) for a given IP address.
The InetAddress.getHostName() function will return the host name if the InetAddress object was initialized with a host name. Otherwise, it'll do a reverse DNS lookup to get the host name.
To get this reverse DNS lookup to work, you'll need to make sure all of the clients on your intranet are configured with host names and that your DNS provider (e.g. your router) properly matches up the host names with its records. (Some routers can do this automatically.)
In order to get the hostname of windows machines, you will need to perform a reverse NetBIOS lookup on the IP address. Windows uses a system called WINS to provide hostnames to its computers. This system is based off NetBIOS.
If you don't want to try to find a specification of the protocol and implement it yourself, then you will want to execute the command nbtstat -A [ip address] if you are on Windows, or nmblookup -A [ip address] if you are on a Linux machine. If you are on a Linux machine, the Samba package will have to be installed as the nmblookup executable is installed on all Linux machines. You will then have to parse the output of that command to get the host name.
The alternative is, as stated before, try to find a specification of the protocol, and implement the part that you need to implement.