Safe method to get computer IP on UNIX using Java - java

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.

Related

Java IP Address,MAC address return with name of device [duplicate]

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

Return internal IP from NetworkInterface Android

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.

Can I filter and select only IPV4 adresses on the InetAddress object? How to exlude the IPV6?

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);
}
}
}

Android IP address with java

I'm writing an Android video game that supports multiplayer. There is a dedicated server running which the androids connect to when the multiplayer button is clicked by opening a socket(this works fine). The server basically just acts as a matchmaking system.
When a client hosts a game, the server adds that client to the list of hosts. Other clients may choose to view this list and then subsequently connect to that host. This is where the problem is. The server is supposed to keep track of the ip/port of hosts, and then other clients are supposed to use this information to open a socket with the host and then the game starts. I'm trying to get the host to send its own IP address to server for other clients to use later.
I have tried many methods so far. One is:
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) {
}
This returns 10.0.2.15, which is obviously useless for other clients.
The other method I've tried is this:
String hostName = InetAddress.getLocalHost().getHostName();
InetAddress addrs[] = InetAddress.getAllByName(hostName);
for (InetAddress addr: addrs) {
System.out.println ("addr.getHostAddress() = " + addr.getHostAddress());
System.out.println ("addr.getHostName() = " + addr.getHostName());
System.out.println ("addr.isAnyLocalAddress() = " + addr.isAnyLocalAddress());
System.out.println ("addr.isLinkLocalAddress() = " + addr.isLinkLocalAddress());
System.out.println ("addr.isLoopbackAddress() = " + addr.isLoopbackAddress());
System.out.println ("addr.isMulticastAddress() = " + addr.isMulticastAddress());
System.out.println ("addr.isSiteLocalAddress() = " + addr.isSiteLocalAddress());
System.out.println ("");
if (!addr.isLoopbackAddress()){// && addr.isSiteLocalAddress()) {
myIP = addr.getHostAddress();
}
This returns the ip address that I'm looking for when I run it as a java application, but when I run it as an android application, it doesn't work. The last if condition is somehow not satisfied and myIP ends up being null. Note that I have included the permissions: android.permission.INTERNET, android.permission.ACCESS_WIFI_STATE, android.permission.ACCESS_COARSE_LOCATION, android.permission.ACCESS_NETWORK_STATE.
Can anybody help me?
If you just need the IP for the Wifi connection you can retrieve the IP as a 32 bit integer:
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ip = wifiInfo.getIpAddress();
Then, in order to construct the IP in dot-decimal notation; bit-shift and mask the result:
String ipString = String.format(
"%d.%d.%d.%d",
(ip & 0xff),
(ip >> 8 & 0xff),
(ip >> 16 & 0xff),
(ip >> 24 & 0xff));
android.permission.ACCESS_WIFI_STATE permission will be required in the manifest.
Do you have to rely on the host to figure out its own IP address and provide this to the server? If the host opens a connection and sends a message to the server announcing that it is hosting a game, then could the server use the IP address that the connection and message came from? This would avoid the problem altogether.
try this
WifiManager wim= (WifiManager) getSystemService(WIFI_SERVICE) ;
List<WifiConfiguration> l= wim.getConfiguredNetworks();
WifiConfiguration wc=l.get(0);
textview.append( "\n"+ Formatter.formatIpAddress(wim.getConnectionInfo().getIpAddress()));

Client computer name in java

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.

Categories