C# 如何在本地网络中获取IP地址及其具有设备MAC的http端口
我有一个连接到本地网络的设备MAC:00408CBEEAE5C# 如何在本地网络中获取IP地址及其具有设备MAC的http端口,c#,.net,ip,C#,.net,Ip,我有一个连接到本地网络的设备MAC:00408CBEEAE5 如何在C#中查询该设备的IP地址?您可以尝试使用iphlapi.dll中的方法 您可以从.Net和PInvoke中找到如何使用此方法的示例代码。它将返回字典,但您可以根据物理地址对其进行更新,只返回一个IP地址 关于第二个问题,是的,您需要迭代该主机上所有打开的端口,并检查其中是否有任何端口返回正确的Http响应,这意味着侦听该端口的Web服务器。但不会这么快。而一些防火墙,如前哨防火墙可能认为这是一种攻击,并在一段时间内阻止您的IP
如何在C#中查询该设备的IP地址?您可以尝试使用
iphlapi.dll
中的方法
您可以从.Net和PInvoke中找到如何使用此方法的示例代码。它将返回字典
,但您可以根据物理地址
对其进行更新,只返回一个IP地址
关于第二个问题,是的,您需要迭代该主机上所有打开的端口,并检查其中是否有任何端口返回正确的Http响应,这意味着侦听该端口的Web服务器。但不会这么快。而一些防火墙,如前哨防火墙
可能认为这是一种攻击,并在一段时间内阻止您的IP
更新1
从示例中复制了代码
public class IPHelper
{
/// <summary>
/// MIB_IPNETROW structure returned by GetIpNetTable
/// DO NOT MODIFY THIS STRUCTURE.
/// </summary>
[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;
}
/// <summary>
/// GetIpNetTable external method
/// </summary>
/// <param name="pIpNetTable"></param>
/// <param name="pdwSize"></param>
/// <param name="bOrder"></param>
/// <returns></returns>
[DllImport("IpHlpApi.dll")]
[return: MarshalAs(UnmanagedType.U4)]
static extern int GetIpNetTable(IntPtr pIpNetTable,
[MarshalAs(UnmanagedType.U4)] ref int pdwSize, bool bOrder);
/// <summary>
/// Error codes GetIpNetTable returns that we recognise
/// </summary>
const int ERROR_INSUFFICIENT_BUFFER = 122;
/// <summary>
/// Get the IP and MAC addresses of all known devices on the LAN
/// </summary>
/// <remarks>
/// 1) This table is not updated often - it can take some human-scale time
/// to notice that a device has dropped off the network, or a new device
/// has connected.
/// 2) This discards non-local devices if they are found - these are multicast
/// and can be discarded by IP address range.
/// </remarks>
/// <returns></returns>
public static Dictionary<IPAddress, PhysicalAddress> GetAllDevicesOnLAN()
{
Dictionary<IPAddress, PhysicalAddress> all = new Dictionary<IPAddress, PhysicalAddress>();
// Add this PC to the list...
all.Add(GetIPAddress(), GetMacAddress());
int spaceForNetTable = 0;
// Get the space needed
// We do that by requesting the table, but not giving any space at all.
// The return value will tell us how much we actually need.
GetIpNetTable(IntPtr.Zero, ref spaceForNetTable, false);
// Allocate the space
// We use a try-finally block to ensure release.
IntPtr rawTable = IntPtr.Zero;
try
{
rawTable = Marshal.AllocCoTaskMem(spaceForNetTable);
// Get the actual data
int errorCode = GetIpNetTable(rawTable, ref spaceForNetTable, false);
if (errorCode != 0)
{
// Failed for some reason - can do no more here.
throw new Exception(string.Format(
"Unable to retrieve network table. Error code {0}", errorCode));
}
// Get the rows count
int rowsCount = Marshal.ReadInt32(rawTable);
IntPtr currentBuffer = new IntPtr(rawTable.ToInt64() + Marshal.SizeOf(typeof(Int32)));
// Convert the raw table to individual entries
MIB_IPNETROW[] rows = new MIB_IPNETROW[rowsCount];
for (int index = 0; index < rowsCount; index++)
{
rows[index] = (MIB_IPNETROW)Marshal.PtrToStructure(new IntPtr(currentBuffer.ToInt64() +
(index * Marshal.SizeOf(typeof(MIB_IPNETROW)))
),
typeof(MIB_IPNETROW));
}
// Define the dummy entries list (we can discard these)
PhysicalAddress virtualMAC = new PhysicalAddress(new byte[] { 0, 0, 0, 0, 0, 0 });
PhysicalAddress broadcastMAC = new PhysicalAddress(new byte[] { 255, 255, 255, 255, 255, 255 });
foreach (MIB_IPNETROW row in rows)
{
IPAddress ip = new IPAddress(BitConverter.GetBytes(row.dwAddr));
byte[] rawMAC = new byte[] { row.mac0, row.mac1, row.mac2, row.mac3, row.mac4, row.mac5 };
PhysicalAddress pa = new PhysicalAddress(rawMAC);
if (!pa.Equals(virtualMAC) && !pa.Equals(broadcastMAC) && !IsMulticast(ip))
{
//Console.WriteLine("IP: {0}\t\tMAC: {1}", ip.ToString(), pa.ToString());
if (!all.ContainsKey(ip))
{
all.Add(ip, pa);
}
}
}
}
finally
{
// Release the memory.
Marshal.FreeCoTaskMem(rawTable);
}
return all;
}
/// <summary>
/// Gets the IP address of the current PC
/// </summary>
/// <returns></returns>
public static IPAddress GetIPAddress()
{
String strHostName = Dns.GetHostName();
IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
IPAddress[] addr = ipEntry.AddressList;
foreach (IPAddress ip in addr)
{
if (!ip.IsIPv6LinkLocal)
{
return (ip);
}
}
return addr.Length > 0 ? addr[0] : null;
}
/// <summary>
/// Gets the MAC address of the current PC.
/// </summary>
/// <returns></returns>
public static PhysicalAddress GetMacAddress()
{
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
// Only consider Ethernet network interfaces
if (nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet &&
nic.OperationalStatus == OperationalStatus.Up)
{
return nic.GetPhysicalAddress();
}
}
return null;
}
/// <summary>
/// Returns true if the specified IP address is a multicast address
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
public static bool IsMulticast(IPAddress ip)
{
bool result = true;
if (!ip.IsIPv6Multicast)
{
byte highIP = ip.GetAddressBytes()[0];
if (highIP < 224 || highIP > 239)
{
result = false;
}
}
return result;
}
public static IPAddress GetIPAddress(PhysicalAddress physicalAddress)
{
var localIPs = GetAllDevicesOnLAN();
foreach (var pair in localIPs)
{
if (pair.Value.Equals(physicalAddress))
return pair.Key;
}
return null;
}
}
公共类IPHelper
{
///
///GetIpNetTable返回的MIB_IPNETROW结构
///不要修改此结构。
///
[StructLayout(LayoutKind.Sequential)]
结构MIB_IPNETROW
{
[Marshallas(UnmanagedType.U4)]
公共指数;
[Marshallas(UnmanagedType.U4)]
公共交通部;
[Marshallas(UnmanagedType.U1)]
公共字节mac0;
[Marshallas(UnmanagedType.U1)]
公共字节mac1;
[Marshallas(UnmanagedType.U1)]
公共字节mac2;
[Marshallas(UnmanagedType.U1)]
公共字节mac3;
[Marshallas(UnmanagedType.U1)]
公共字节mac4;
[Marshallas(UnmanagedType.U1)]
公共字节mac5;
[Marshallas(UnmanagedType.U1)]
公共字节mac6;
[Marshallas(UnmanagedType.U1)]
公共字节mac7;
[Marshallas(UnmanagedType.U4)]
公共int dwAddr;
[Marshallas(UnmanagedType.U4)]
公共int-dwType;
}
///
///GetIpNetTable外部方法
///
///
///
///
///
[DllImport(“iphlapi.dll”)]
[返回:Marshallas(UnmanagedType.U4)]
静态外部int GETIPNETABLE(IntPtr PIPNETABLE,
[Marshallas(UnmanagedType.U4)]ref int pdwSize,bool bOrder);
///
///我们识别的错误代码GetIpNetTable返回
///
常量int错误\u缓冲区不足=122;
///
///获取局域网上所有已知设备的IP和MAC地址
///
///
///1)此表不经常更新-可能需要一些人的时间
///注意到某个设备已从网络上断开,或新设备已断开
///已连接。
///2)如果找到非本地设备,则丢弃这些设备-这些设备是多播的
///并且可以按IP地址范围丢弃。
///
///
公共静态字典GetAllDeviceOnlan()
{
Dictionary all=新字典();
//将此电脑添加到列表中。。。
Add(GetIPAddress(),GetMacAddress());
int spaceForNetTable=0;
//获得所需的空间
//我们通过请求表来实现,但根本不给任何空间。
//返回值将告诉我们实际需要多少。
GetIpNetTable(IntPtr.Zero,ref spaceForNetTable,false);
//分配空间
//我们使用try-finally块来确保发布。
IntPtr rawTable=IntPtr.Zero;
尝试
{
rawTable=Marshal.allocTaskMem(spaceForNetTable);
//获取实际数据
int errorCode=GetIpNetTable(rawTable,ref spaceForNetTable,false);
如果(错误代码!=0)
{
//由于某种原因失败-在这里不能再做了。
抛出新异常(string.Format)(
无法检索网络表。错误代码{0},errorCode));
}
//计算行数
int rowscont=Marshal.ReadInt32(rawTable);
IntPtr currentBuffer=newintptr(rawTable.ToInt64()+Marshal.SizeOf(typeof(Int32));
//将原始表转换为单个条目
MIB_IPNETROW[]行=新的MIB_IPNETROW[rowsunt];
for(int index=0;indexclass Program
{
static void Main(string[] args)
{// Get my PC IP address
Console.WriteLine("My IP : {0}", IPHelper.GetIPAddress());
// Get My PC MAC address
Console.WriteLine("My MAC: {0}", IPHelper.GetMacAddress());
// Get all devices on network
Dictionary<IPAddress, PhysicalAddress> all = IPHelper.GetAllDevicesOnLAN();
foreach (KeyValuePair<IPAddress, PhysicalAddress> kvp in all)
{
Console.WriteLine("IP : {0}\n MAC {1}", kvp.Key, kvp.Value);
}
PhysicalAddress ph = PhysicalAddress.Parse("485B39C25E67");
var ip = IPHelper.GetIPAddress(ph);
Console.WriteLine("IP is {0}", ip);
}
}