Reputation: 13
I am New in socket programming in Java.Can someone tell me , how to get MAC Address without using IP Address in socket programming.
This is the code by which i can get MAC address in socket--
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());
but this is using IP Address ultimately.Is there any way to get the MAC Address without using IP Address?
Upvotes: 0
Views: 5204
Reputation: 1
try{
InetAddress ip = InetAddress.getLocalHost();
System.out.println("ip : " + ip);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());
String s=sb.toString();System.out.println(s);
Upvotes: -1
Reputation: 1316
MAC addresses are only used on local networks. It is the way a switch/router knows where a packet has to be sent. IP is used to transport packets from network to network.
All TCP/UDP packets include senders IP and MAC. This way the receiving device can include the MAC in the return package so the switch/router know where to deliver it. MAC addresses should be unique but there is no guarantee, and it is not possible to use as a device address on the internet.
When you use internet you use IP protocol (A global address system) When your on a local network the devices usually use MAC addresses.
Upvotes: 1