Getting the IP address of the current machine using Java
import java.net.DatagramSocket;
import java.net.InetAddress;
try(final DatagramSocket socket = new DatagramSocket()){
socket.connect(InetAddress.getByName("8.8.8.8"), 10002);
ip = socket.getLocalAddress().getHostAddress();
}
This way works well when there are multiple network interfaces. It always returns the preferred outbound IP. The destination 8.8.8.8
is not needed to be reachable.
Connect
on a UDP socket has the following effect: it sets the destination for Send/Recv, discards all packets from other addresses, and - which is what we use - transfers the socket into "connected" state, settings its appropriate fields. This includes checking the existence of the route to the destination according to the system's routing table and setting the local endpoint accordingly. The last part seems to be undocumented officially but it looks like an integral trait of Berkeley sockets API (a side effect of UDP "connected" state) that works reliably in both Windows and Linux across versions and distributions.
So, this method will give the local address that would be used to connect to the specified remote host. There is no real connection established, hence the specified remote ip can be unreachable.
Edit:
As @macomgil says, for MacOS you can do this:
Socket socket = new Socket();
socket.connect(new InetSocketAddress("google.com", 80));
System.out.println(socket.getLocalAddress());
Java getting my IP address
The NetworkInterface
class contains all the relevant methods, but be aware that there's no such thing as "my IP". A machine can have multiple interfaces and each interface can have multiple IPs.
You can list them all with this class but which interface and IP you choose from the list depends on what you exactly need to use this IP for.
(InetAddress.getLocalHost()
doesn't consult your interfaces, it simply returns constant 127.0.0.1 (for IPv4))
Get all ipaddress of a linux machine
I believe you should take a look on NetworkInterfaces class of Java.
You'll query for all available interfaces and enumerate over them to get the details (ip address in your case ) assigned to each one of there.
You can find example and explanations Here
Hope this helps
How can I get the actual IP in a linux machine from Java
Any modern computer have multiple IP-numbers, 127.0.0.1 being one of them. The actual configuration does not always get correctly reported up to the Java layer (in my experience).
You may simply want to execute /sbin/ifconfig -a
on a scheduled basis (or at startup time) and log the complete output.
Safe method to get computer IP on UNIX using Java
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;
}
How can i get list of MAC address and IP address of computer through java?
Since JDK 1.6, Java developers are able to access network card detail via NetworkInterface class.
InetAddress ip;
ip = InetAddress.getLocalHost();
System.out.println("Current IP address : " + ip.getHostAddress());
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
byte[] mac = network.getHardwareAddress();
System.out.print("Current MAC address : ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
System.out.println(sb.toString());
For multiple ip addresses :
java.util.Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
en.hasMoreElements(); ) {
NetworkInterface iface = en.nextElement();
List<InterfaceAddress> addrs = iface.getInterfaceAddresses();
//For each network interfaces iterate through each ip address
for(InterfaceAddress addr : addrs) {
ip = addr.getAddress();
//Process the IP ...
Get the IPaddress of the computer in an Android project using java
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(tag, ex.toString());
}
return "";
}
Related Topics
Variable Column Names Using Prepared Statements
Classcastexception When Casting to the Same Class
Deserialize a List≪T≫ Object With Gson
Looking for a CSS Parser in Java
Format Float to N Decimal Places
Service Discovery Failed Exception Using Bluetooth on Android
Wait Until Firestore Data Is Retrieved to Launch an Activity
Tool for Creating a Java Daemon Service on Linux
How to Avoid Java.Net.Bindexception: Address Already in Use
Equivalent of Data Protection API on Linux
Local_Policy.Jar and Us_Export_Policy.Jar Different with Unlimited Strength VS Default
How to Implement Basic Authentication with Glassfish
Sending Command to Java -Jar Using Stdin via /Proc/{Pid}/Fd/0