【发布时间】:2016-10-28 01:56:58
【问题描述】:
是否可以通过C#中的TCPListener获取远程客户端的MAC地址?
using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
namespace TCPserver
{
class Program
{
private const int BUFSIZE = 32;
static void Main(string[] args)
{
if (args.Length > 1) // Test for correct of args
throw new ArgumentException("Parameters: [<Port>]");
int servPort = (args.Length == 1) ? Int32.Parse(args[0]) : 7;
TcpListener listener = null;
try
{
// Create a TCPListener to accept client connections
listener = new TcpListener(IPAddress.Any, servPort);
listener.Start();
}
catch (SocketException se)
{
Console.WriteLine(se.Message);
Environment.Exit(se.ErrorCode);
}
byte[] rcvBuffer = new byte[BUFSIZE]; // Receive buffer
int bytesRcvd; // Received byte count
for (; ; )
{ // Run forever, accepting and servicing connections
TcpClient client = null;
NetworkStream ns = null;
try
{
client = listener.AcceptTcpClient(); // Get client connection
ns = client.GetStream();
Console.Write("Handling client - ");
// Receive until client closes connection
int totalBytesEchoed = 0;
while ((bytesRcvd = ns.Read(rcvBuffer, 0, rcvBuffer.Length)) > 0)
{
ns.Write(rcvBuffer, 0, bytesRcvd);
totalBytesEchoed += bytesRcvd;
}
Console.WriteLine("echoed {0} bytes.", totalBytesEchoed);
ns.Close();
client.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
ns.Close();
}
}
}
}
}
【问题讨论】:
-
你有没有看ip helper library msdn.microsoft.com/en-us/library/windows/desktop/…
-
我不认为您想要什么是可能的,因为 MAC 地址是第 2 层(硬件)地址,并且在远程设备的 LAN 之外无法访问。在本地网络上,您可以执行 ARP 从 IP 地址获取 MAC 地址。
-
MAC用在数据链路层,不是网络层,所以严重怀疑。
-
@E.Moffat 如何转换为 C# 代码?
-
@Amy Well...您介意提供一种通过 IP 地址和端口获取它的正确方法吗?
标签: c# .net sockets mac-address tcplistener