public static void main(String[] args) {
try {
InetAddress address = InetAddress.getLocalHost();
// InetAddress address = InetAddress.getByName("192.168.46.53");
/*
* Get NetworkInterface for the current host and then read the
* hardware address.
*/
NetworkInterface ni = NetworkInterface.getByInetAddress(address);
if (ni != null) {
byte[] mac = ni.getHardwareAddress();
if (mac != null) {
/*
* Extract each array of mac address and convert it to hexa with the
* following format 08-00-27-DC-4A-9E.
*/
for (int i = 0; i < mac.length; i++) {
System.out.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "");
}
} else {
System.out.println("Address doesn't exist or is not accessible.");
}
} else {
System.out.println("Network Interface for the specified address is not found.");
}
I'm having a problem finding the MAC address of a remote host, but I am able to find the MAC address of my local host. If I have the IP address of the other system can I retrieve the MAC address of that system?
InetAddress address = InetAddress.getByName("192.168.46.53");
if i specify the ip address of a system in my workgroup... ni values gets null.... and not able to fetch it.... but if give my ip address of my system...it fetches???
Thanks,
Sunny
You will only be able to fetch the MAC address of remote hosts on your local LAN, that is, hosts that are in the same subnet as your computer. MAC addresses of hosts more than one hop away (IP hop, not Ethernet hop) cannot be determined.
And note that fetching the corresponding MAC address for hosts on your local LAN requires the permissions necessary to fetch either the ARP table, or those necessary to send and receive raw packets. Most OSes allow reading of the ARP table without special permissions, but the mechanism you use to do so will change depending on the OS. If you need a technique for a particular OS, you will have to update your question to include that info.
Related
I have tried below program on System it returns the host IP address but when running as docker container its give container IP
public static Map<String, String> getMAC(){
Map<String, String> dataMap = new HashMap<>();
try{
InetAddress inetaddress=InetAddress.getLocalHost(); //Get LocalHost refrence
String ip = inetaddress.getHostAddress(); // Get Host IP Address
dataMap.put("ip", ip);
//get Network interface Refrence by InetAddress Refrence
NetworkInterface network = NetworkInterface.getByInetAddress(inetaddress);
byte[] macArray = network.getHardwareAddress(); //get Harware address Array
StringBuilder str = new StringBuilder();
// Convert Array to String
for (int i = 0; i < macArray.length; i++) {
str.append(String.format("%02X%s", macArray[i], (i < macArray.length - 1) ? "-" : ""));
}
String macAddress=str.toString();
dataMap.put("mac", macAddress);
//return dataMap; //return MAc Address
}
catch(Exception E){
E.printStackTrace(); //print Exception StackTrace
//return null;
}
return dataMap;
}
According to Docker docs, you can get the host's IP address by resolving host.docker.internal. So try changing the first line in the try block to:
InetAddress inetaddress=InetAddress.getByName("host.docker.internal");
This is for development purpose and will not work in a production
environment outside of Docker Desktop for Mac.
I am developing a web application which acts as a server. In this application I have implimented ServerSocket for two way communication between server application and wi-fi device which acts as client. I am not connecting to my server directly, I am connecting to my router which port forwards to my system and two way communication is successful. All I want now is to find the MAC address of Wi-fi device which is connected.I have done some research and tried to get the MAC address but failed.Can anyone help me on this.Below is the part of my code.
public class ScheduleJob extends ServletApp implements Job{
private int port = 1717;
public static String number;
String ReceivedData = "";
public void execute(JobExecutionContext context)throws JobExecutionException {
System.out.println("Starting ... ");
ServerSocket Sersocket = null;
System.out.println("Starting the socket server at port:" +port);
boolean listeningSocket = true;
try {
Sersocket = new ServerSocket(port);
System.out.println("Waiting for clients...");
} catch (IOException e) {
System.err.println("Could not listen on port: 1717");
}
try {
while (listeningSocket) {
Socket scokt = Sersocket.accept();
InetAddress MachineAdd = scokt.getInetAddress();
System.out.println("Response-----:" +MachineAdd);
InetAddress ip = InetAddress.getLocalHost();
System.out.println("current 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());
MAC address is piece of information which belongs to layer 2 of OSI model.
In other words it's not preserved whenever you are communicating using L3 protocol (until you are communicating directly via cross cable or via L2 switch).
I would recommend you to send MAC address as a part of your application communication from client to your server, so it will not be lost when your router will do port forwarding.
Some of already asked questions on this topic:
Why can't the server get the client MAC address, like the client IP?
How can I get the MAC and the IP address of a connected client in PHP?
how to get a client's MAC address from HttpServlet?
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?
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.
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.
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);
How to get the IP address of the PC using Android phone? (In particular how to fetch the IP address of a system with a specific MAC address, connected on the same network as the Android phone)?
wired wired
modem--------router---------PC(mac:EE:00:B3:2F:56:12)
|
|
|
wireless
|
|
|
-------------android phone(A)
private String getIP(String mac) {
String ip = null;
try {
BufferedReader br = new BufferedReader(new FileReader("/proc/net/arp"));
String line = "";
while((line = br.readLine()) != null) {
String[] tokens = line.split("\\s+");
// The ARP table has the form:
// IP address HW type Flags HW address Mask Device
// 192.168.178.21 0x1 0x2 00:1a:2b:3c:4d:5e * tiwlan0
if(tokens.length >= 4 && tokens[3].equalsIgnoreCase(mac)) {
ip = tokens[0];
break;
}
}
br.close();
}
catch(Exception e) { Log.e(TAG, e.toString()); }
return ip;
}
But beware: Unless you have already established contact with your PC (and you'll need either its IP address or its name), the ARP table will be empty.
I suppose you'd like to do it the other way round, establish the connection with the PC knowing only its MAC address. Then it's not that simple. You might try to ping everyone on the local network (Runtime.getRuntime().exec("ping -b 192.168.178.255");) just to fill the ARP table.
Or, maybe, you can get the list of all clients with their IP addresses from your router?
I use this method in a loop to get the host name of 4 terminal in my local network identified by the ip address terminal[i].getIp() .
try {
// Get hostname by textual representation of IP address
InetAddress addr = InetAddress.getByName(terminal[i].getIp());
// Get the host name
String hostname = addr.getHostName();
} catch (UnknownHostException e) {
}
the problem here its that code take so long to return the result (up to 5 seconds)
I wonder if there is another more optimized method.
Try the library from Google Guava, I think there are more optimized
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/net/InetAddresses.html