Atanu Baidya
Atanu Baidya

Reputation: 13

How to get MAC Address without using IP Address in java socket programming

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

Answers (3)

user4554525
user4554525

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

d00dle
d00dle

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

NPE
NPE

Reputation: 500933

Any PC's MAC ADDRESS by using socket

In a nutshell, there is no reliable method for finding out the MAC address of a host outside your subnet.

If you are on the same subnet as the host in question, take a look at ARP and RARP.

Upvotes: 2

Related Questions