Skip to content

Instantly share code, notes, and snippets.

@SatyaSnehith
Created November 8, 2018 17:01
Show Gist options
  • Save SatyaSnehith/a1957a10ecf26db2ba0fe0a9fb25e4d4 to your computer and use it in GitHub Desktop.
Save SatyaSnehith/a1957a10ecf26db2ba0fe0a9fb25e4d4 to your computer and use it in GitHub Desktop.
Get IP Address of a Device
import java.net.*;
import java.util.*;
public class Ip {
public static void main(String[] args) {
getIPAddress();
}
String getSubnetAddress(String ip) {
try {
String[] split = ip.split("\\.");
return split[0] + "." + split[1] + "." + split[2] + ".";
} catch (ArrayIndexOutOfBoundsException e) {
return "NOT IP";
}
}
String getIPAddress() {
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();
// boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
boolean isIPv4 = sAddr.indexOf(':') < 0;
if (isIPv4)
return sAddr;
}
}
}
} catch (Exception ex) {
}
return "";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment