Get MAC address on local machine with Java
With Java 6+, you can use NetworkInterface.getHardwareAddress
.
Bear in mind that a computer can have no network cards, especially if it's embedded or virtual. It can also have more than one. You can get a list of all network cards with NetworkInterface.getNetworkInterfaces()
.
Get All IP and Mac Address in lan
I've been working on a project to do the same thing. I think the best way to go about this is to execute another process at run time and read the results. As already suggested, you could read the system ARP table and parse results, but this is platform dependent. The windows command in command prompt is: arp -a.
I chose to make a remote call to nmap and parse those results. It requires installing nmap on your machine, but the solutions "should" be cross-platform as long as the appropriate version of nmap is installed:
Available here: https://nmap.org/download.html
Here's a quick example. You'd of course need to make some changes to dynamically choose the network to scan and parse the results instead of print them.
try {
Process proc = Runtime.getRuntime().exec("nmap -PR -sn 192.168.1.0/24");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
// read the output from the command
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
// read any errors from the attempted command
while ((s = stdError.readLine()) != null) {
System.err.println(s);
}
} catch (IOException ex) {
System.err.println(ex);
}
Get MAC Address of System in Java
If you account for multiple interfaces, and some null MAC addresses (I'm running Java 7 on Windows 7 with VMWare installed (so I have some virtual network adapters)) then this code seems to work:
public static void main(String[] args) {
try {
InetAddress ip = InetAddress.getLocalHost();
System.out.println("Current IP address : " + ip.getHostAddress());
Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
while(networks.hasMoreElements()) {
NetworkInterface network = networks.nextElement();
byte[] mac = network.getHardwareAddress();
if(mac != null) {
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());
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e){
e.printStackTrace();
}
}
Here is (a sanitized version of) what I see on my computer when I run it:
Current IP address : {I'm not telling :)}
Current MAC address :
Current MAC address : {actual hardware interface}
Current MAC address : 00-00-00-00-00-00-00-E0
Current MAC address : 00-00-00-00-00-00-00-E0
Current MAC address : 00-00-00-00-00-00-00-E0
Current MAC address : 00-00-00-00-00-00-00-E0
Current MAC address : 00-00-00-00-00-00-00-E0
Current MAC address : 00-50-56-C0-00-01
Current MAC address : 00-50-56-C0-00-08
And here is the output of running ipconfig /all
C:\>ipconfig /all
Windows IP Configuration (minus any actual interface because I don't like sharing that kind of information :)
Ethernet adapter Local Area Connection 2:
Media State . . . . . . . . . . . : Media disconnected
Connection-specific DNS Suffix . :
Description . . . . . . . . . . . : Gbridge Virtual Private Network Adapter
Physical Address. . . . . . . . . : 02-50-F2-CE-82-01
DHCP Enabled. . . . . . . . . . . : Yes
Autoconfiguration Enabled . . . . : Yes
Ethernet adapter VMware Network Adapter VMnet1:
Connection-specific DNS Suffix . :
Description . . . . . . . . . . . : VMware Virtual Ethernet Adapter for VMnet1
Physical Address. . . . . . . . . : 00-50-56-C0-00-01
DHCP Enabled. . . . . . . . . . . : No
Autoconfiguration Enabled . . . . : Yes
Link-local IPv6 Address . . . . . : fe80::9c27:3d03:da2c:f14d%19(Preferred)
Autoconfiguration IPv4 Address. . : {Hidden}(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.0.0
Default Gateway . . . . . . . . . :
DHCPv6 IAID . . . . . . . . . . . : 268456022
DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-13-DB-D9-CB-B8-AC-6F-AF-9D-F2
DNS Servers . . . . . . . . . . . : fec0:0:0:ffff::1%1
fec0:0:0:ffff::2%1
fec0:0:0:ffff::3%1
NetBIOS over Tcpip. . . . . . . . : Enabled
Ethernet adapter VMware Network Adapter VMnet8:
Connection-specific DNS Suffix . :
Description . . . . . . . . . . . : VMware Virtual Ethernet Adapter for VMnet8
Physical Address. . . . . . . . . : 00-50-56-C0-00-08
DHCP Enabled. . . . . . . . . . . : No
Autoconfiguration Enabled . . . . : Yes
Link-local IPv6 Address . . . . . : fe80::cdbb:434:7fd9:2574%20(Preferred)
IPv4 Address. . . . . . . . . . . : 192.168.42.1(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . :
DHCPv6 IAID . . . . . . . . . . . : 285233238
DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-13-DB-D9-CB-B8-AC-6F-AF-9D-F2
DNS Servers . . . . . . . . . . . : fec0:0:0:ffff::1%1
fec0:0:0:ffff::2%1
fec0:0:0:ffff::3%1
NetBIOS over Tcpip. . . . . . . . : Enabled
Tunnel adapter 6TO4 Adapter:
Description . . . . . . . . . . . : Microsoft 6to4 Adapter
Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
DHCP Enabled. . . . . . . . . . . : No
Autoconfiguration Enabled . . . . : Yes
IPv6 Address. . . . . . . . . . . : 2002:204c:1bc6::204c:1bc6(Preferred)
Default Gateway . . . . . . . . . :
NetBIOS over Tcpip. . . . . . . . : Disabled
Tunnel adapter isatap.{3E45CB42-BC1E-4F89-9C16-25166C0EABA1}:
Media State . . . . . . . . . . . : Media disconnected
Connection-specific DNS Suffix . :
Description . . . . . . . . . . . : Microsoft ISATAP Adapter
Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
DHCP Enabled. . . . . . . . . . . : No
Autoconfiguration Enabled . . . . : Yes
Tunnel adapter isatap.{77F1FADC-02BA-44AF-9FDF-97E23F8B5FE7}:
Media State . . . . . . . . . . . : Media disconnected
Connection-specific DNS Suffix . :
Description . . . . . . . . . . . : Microsoft ISATAP Adapter #3
Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
DHCP Enabled. . . . . . . . . . . : No
Autoconfiguration Enabled . . . . : Yes
Tunnel adapter isatap.{608257AC-C0F3-43A5-8595-898533C95D90}:
Media State . . . . . . . . . . . : Media disconnected
Connection-specific DNS Suffix . :
Description . . . . . . . . . . . : Microsoft ISATAP Adapter #5
Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
DHCP Enabled. . . . . . . . . . . : No
Autoconfiguration Enabled . . . . : Yes
The challenge in getting "just one value" from this mess comes from the relationship between InetAddress.getLocalHost().getHostAddress()
and the network interfaces themselves. Consider this slight expanded version of the initial program (using this really cool IterableEnumeration utility class):
public static void main(String[] args) throws UnknownHostException, SocketException {
System.out.println("Current IP address : " + InetAddress.getLocalHost().getHostAddress());
for(NetworkInterface network : IterableEnumeration.make(NetworkInterface.getNetworkInterfaces())) {
byte[] mac = network.getHardwareAddress();
if(mac != null) {
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());
//Bound InetAddress for interface
for(InetAddress address : IterableEnumeration.make(network.getInetAddresses())) {
System.out.println("\tBound to:"+address.getHostAddress());
}
}
}
}
If you run this on your computer you will see your current IP address correlates to one adapter but that MAC address of your hardware interface sees it's self as a different IP address. Maybe you can filter out virtual addresses or just find a way to utilize all available addresses.
How to get the MAC address of machine on local network in java
Try this code,
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.regex.*;
public class GetMac
{
public static void main(String[] args)
throws IOException
{
String address = new GetMac().getMacAddress();
System.out.println(address);
}
public String getMacAddress() throws IOException
{
String macAddress = null;
String command = "ipconfig /all";
Process pid = Runtime.getRuntime().exec(command);
BufferedReader in =
new BufferedReader(
new InputStreamReader(pid.getInputStream()));
while (true) {
String line = in.readLine();
if (line == null)
break;
Pattern p = Pattern.compile(".*Physical Address.*: (.*)");
Matcher m = p.matcher(line);
if (m.matches()) {
macAddress = m.group(1);
break;
}
}
in.close();
return macAddress;
}
}
Getting mac address without internet connection in java
You certainly use an indirection based on the IP address, in your code snippet. This may explain why you do not get anything when Internet network access is down.
Here is a code snippet that does not depend on the network connection status.
It displays each MAC address of your PC. Note that a PC often has multiple MAC addresses. Each address will be displayed by this code snippet.
package com.stackoverflow;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class GetHWAddresses {
public static void main(String[] args) throws SocketException {
final Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
while (e.hasMoreElements()) {
final byte [] mac = e.nextElement().getHardwareAddress();
if (mac != null) {
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());
}
}
}
}
Related Topics
Reverse Each Individual Word of "Hello World" String with Java
What Is the Point of Setters and Getters in Java
Concurrentmodificationexception When Adding Inside a Foreach Loop in Arraylist
Can the Jvm Recover from an Outofmemoryerror Without a Restart
Does Java Have Built in Libraries for Audio _Synthesis_
Why I Can't Create an Array with Large Size
How to Add Unicode in Truetype0Font on PDFbox 2.0.0
Efficient Swapping of Elements of an Array in Java
How to Simulate Keyboard Presses in Java
Package Conflicts with Automatic Modules in Java 9
Is Java.Util.Date Using Timezone
How to Sum Digits of an Integer in Java
How to Keep a Scanner from Throwing Exceptions When the Wrong Type Is Entered
What Is the Cross-Platform Way of Obtaining the Path to the Local Application Data Directory
Printing Runtime Exec() Outputstream to Console
Java 1.6: Creating an Array of List<T>
Hiding Instance Variables of a Class
The Connection Between 'System.Out.Println()' and 'Tostring()' in Java