Created
November 8, 2018 17:01
-
-
Save SatyaSnehith/a1957a10ecf26db2ba0fe0a9fb25e4d4 to your computer and use it in GitHub Desktop.
Get IP Address of a Device
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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