Query Arp Cache to Get MAC Id

Query ARP cache to get MAC ID

Java provides no direct way to query the MAC address of a host in your network, as this is abstracted away by Java's socket libraries.

In a way, this makes sense, because the MAC address of a host actually says very little. There is no such thing as "the" MAC address of a host.

  • Many hosts will have several NICs, all with a separate MAC address, with which they can connect to the network. The computer I'm on at the moment has a wired ethernet adapter, a WiFi adapter, and a Firewire adapter, and they all have their own MAC address. This means that there is no definitive MAC address for a host.
  • If the host is on a different subnet, ARP will actually give you the MAC address for the last router your packet passed through, instead of the MAC address of the host you're scanning.

Put both of these issues together, and that means that one host may have many different MAC addresses (if it has more than one NIC), and one MAC address may represent many different hosts (if traffic passes through a router).

Assuming you know all this and you still need to get the MAC address of a host, the only way to do that in Java is by "going native":

  • Native to the client that runs your program:

    • You could launch an ARP command-line tool and parse its output.
    • You could use some sort of JNI call. I'm not too familiar with JNI, though, so I can't help you with that.
    • Write a separate, small native app that you can access from Java via Telnet or some such protocol, and which will run the ARP command for you.
  • Native to the host that you want to scan:

    • You could use SNMP, as some of the other answers to this thread suggest. I defer to these answers for making that work for you. SNMP is a great protocol, but be aware that SNMP's OIDs can be both platform-dependent and vendor-dependent. OIDs that work for Windows don't always work for Linux and vice versa.
    • If you know that your host runs Windows, you could use WMI. The Win32_NetworkAdapter class holds the information you want, but be aware that this returns all of the hosts NICs, even the ones Windows makes up. Also, it requires administrator credentials to the host you are scanning. Google will tell you how to connect to WMI from Java.
    • If you know your host runs OS X, you might be able to SSH into the machine and parse the output of the system_profile command.
    • For Linux, a tool similar to OS X's system_profile probably exists.

Get IP from MAC address. arp -a not showing device

I have tried this and it works:

for /L %N in (1,1,254) do start /b ping -n 1 -w 200 192.168.0.%N

provided the phone has ICMP enabled, you should have no problem.

Is there any better way to get mac address from arp table?

You can parse the /proc/net/arp file using awk:

awk "/^${ipAddress//./\.}\>/"' { print $4 }' /proc/net/arp

but I'm not sure it's simpler (it saves one fork and a subshell, though).

If you want a 100% bash solution:

while read ip _ _ mac _; do
[[ "$ip" == "$ipAddress" ]] && break
done < /proc/net/arp
echo "$mac"

Extract only MAC addresses from arp-scan -l

I am assuming that you are using a linux-like shell and awk utility is installed( it is mostly pre-installed )-

arp-scan -l | awk '/.*:.*:.*:.*:.*:.*/{print $2}'

Linux C++ How to Programatically Get MAC address for all adapters on a LAN

Full source here.

Open /proc/net/arp, then read each line like this:

char line[500]; // Read with fgets().
char ip_address[500]; // Obviously more space than necessary, just illustrating here.
int hw_type;
int flags;
char mac_address[500];
char mask[500];
char device[500];

FILE *fp = xfopen("/proc/net/arp", "r");
fgets(line, sizeof(line), fp); // Skip the first line (column headers).
while(fgets(line, sizeof(line), fp))
{
// Read the data.
sscanf(line, "%s 0x%x 0x%x %s %s %s\n",
ip_address,
&hw_type,
&flags,
mac_address,
mask,
device);

// Do stuff with it.
}

fclose(fp);

This was taken straight from BusyBox's implementation of arp, in busybox-1_21_0/networking/arp.c directory of the BusyBox 1.21.0 tarball. Look at the arp_show() function in particular.

If you're scared of C:

The command arp -a should give you what you want, both MAC addresses and IP addresses.

To get all MAC addresses on a subnet, you can try

nmap -n -sP <subnet>
arp -a | grep -v incomplete

How to get remote machines mac addresses java

How to get remote machines mac addresses

You cannot do that - not in the general case. MAC addresses are only available for machines in the same physical network segment. Those machines communicate directly with each other using the ARP protocol to "translate" IP addresses to physical (MAC) addresses.

As soon as an IP router or any other Layer-3 device is crossed, any MAC information is generally lost.

Bottom line: you cannot get the MAC address of a remote node over the Internet - you cannot even do that in any moderately sized private network, as implemented in e.g. most medium to large companies.

How do I access ARP-protocol information through .NET?

If you know which devices are out there you can use the Ping Class. This will allow you to at least fill up the ARP table. You can always execute ARP -a and parse the output if you have to. Here is also a link that shows how to pinvoke to call GetIpNetTable. I have included examples below of Ping Class and how to access the ARP table using the GetIpNetTable.

This is an example for the Ping Class

using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;

namespace Examples.System.Net.NetworkInformation.PingTest
{
public class PingExample
{
// args[0] can be an IPaddress or host name.
public static void Main (string[] args)
{
Ping pingSender = new Ping ();
PingOptions options = new PingOptions ();

// Use the default Ttl value which is 128,
// but change the fragmentation behavior.
options.DontFragment = true;

// Create a buffer of 32 bytes of data to be transmitted.
string data = "Query Arp Cache to Get MAC IdQuery Arp Cache to Get MAC IdQuery Arp Cache to Get MAC IdQuery Arp Cache to Get MAC Id";
byte[] buffer = Encoding.ASCII.GetBytes (data);
int timeout = 120;
PingReply reply = pingSender.Send (args[0], timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine ("Address: {0}", reply.Address.ToString ());
Console.WriteLine ("RoundTrip time: {0}", reply.RoundtripTime);
Console.WriteLine ("Time to live: {0}", reply.Options.Ttl);
Console.WriteLine ("Don't fragment: {0}", reply.Options.DontFragment);
Console.WriteLine ("Buffer size: {0}", reply.Buffer.Length);
}
}
}
}

This is an example of the GetIpNetTable.

using System;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Net;

namespace GetIpNetTable
{
class Program
{
// The max number of physical addresses.
const int MAXLEN_PHYSADDR = 8;

// Define the MIB_IPNETROW structure.
[StructLayout(LayoutKind.Sequential)]
struct MIB_IPNETROW
{
[MarshalAs(UnmanagedType.U4)]
public int dwIndex;
[MarshalAs(UnmanagedType.U4)]
public int dwPhysAddrLen;
[MarshalAs(UnmanagedType.U1)]
public byte mac0;
[MarshalAs(UnmanagedType.U1)]
public byte mac1;
[MarshalAs(UnmanagedType.U1)]
public byte mac2;
[MarshalAs(UnmanagedType.U1)]
public byte mac3;
[MarshalAs(UnmanagedType.U1)]
public byte mac4;
[MarshalAs(UnmanagedType.U1)]
public byte mac5;
[MarshalAs(UnmanagedType.U1)]
public byte mac6;
[MarshalAs(UnmanagedType.U1)]
public byte mac7;
[MarshalAs(UnmanagedType.U4)]
public int dwAddr;
[MarshalAs(UnmanagedType.U4)]
public int dwType;
}

// Declare the GetIpNetTable function.
[DllImport("IpHlpApi.dll")]
[return: MarshalAs(UnmanagedType.U4)]
static extern int GetIpNetTable(
IntPtr pIpNetTable,
[MarshalAs(UnmanagedType.U4)]
ref int pdwSize,
bool bOrder);

[DllImport("IpHlpApi.dll", SetLastError = true, CharSet = CharSet.Auto)]
internal static extern int FreeMibTable(IntPtr plpNetTable);

// The insufficient buffer error.
const int ERROR_INSUFFICIENT_BUFFER = 122;

static void Main(string[] args)
{
// The number of bytes needed.
int bytesNeeded = 0;

// The result from the API call.
int result = GetIpNetTable(IntPtr.Zero, ref bytesNeeded, false);

// Call the function, expecting an insufficient buffer.
if (result != ERROR_INSUFFICIENT_BUFFER)
{
// Throw an exception.
throw new Win32Exception(result);
}

// Allocate the memory, do it in a try/finally block, to ensure
// that it is released.
IntPtr buffer = IntPtr.Zero;

// Try/finally.
try
{
// Allocate the memory.
buffer = Marshal.AllocCoTaskMem(bytesNeeded);

// Make the call again. If it did not succeed, then
// raise an error.
result = GetIpNetTable(buffer, ref bytesNeeded, false);

// If the result is not 0 (no error), then throw an exception.
if (result != 0)
{
// Throw an exception.
throw new Win32Exception(result);
}

// Now we have the buffer, we have to marshal it. We can read
// the first 4 bytes to get the length of the buffer.
int entries = Marshal.ReadInt32(buffer);

// Increment the memory pointer by the size of the int.
IntPtr currentBuffer = new IntPtr(buffer.ToInt64() +
Marshal.SizeOf(typeof(int)));

// Allocate an array of entries.
MIB_IPNETROW[] table = new MIB_IPNETROW[entries];

// Cycle through the entries.
for (int index = 0; index < entries; index++)
{
// Call PtrToStructure, getting the structure information.
table[index] = (MIB_IPNETROW) Marshal.PtrToStructure(new
IntPtr(currentBuffer.ToInt64() + (index *
Marshal.SizeOf(typeof(MIB_IPNETROW)))), typeof(MIB_IPNETROW));
}

for (int index = 0; index < entries; index++)
{
MIB_IPNETROW row = table[index];
IPAddress ip=new IPAddress(BitConverter.GetBytes(row.dwAddr));
Console.Write("IP:"+ip.ToString()+"\t\tMAC:");

Console.Write( row.mac0.ToString("X2") + '-');
Console.Write( row.mac1.ToString("X2") + '-');
Console.Write( row.mac2.ToString("X2") + '-');
Console.Write( row.mac3.ToString("X2") + '-');
Console.Write( row.mac4.ToString("X2") + '-');
Console.WriteLine( row.mac5.ToString("X2"));

}
}
finally
{
// Release the memory.
FreeMibTable(buffer);
}
}
}
}

Get IP with just knowing MAC address

for /f "skip=3 delims=\" %%A in ('net view ^| findstr /v /C:"The command completed successfully"') do Echo %%A >> "%userprofile%\desktop\computerlist.txt"

Lists turned on computers.

 wmic /node:@computerlist.txt nicconfig where macaddress='whatever:whatever:etc' get ipaddress /format:htable

To get IP for a specified MACAddress

 wmic /node:@computerlist.txt nicconfig get ipaddress /format:htable

to get the IPAddress for all MACAddresses on a computer.



Related Topics



Leave a reply



Submit