通过C#中的TCPListener获取MAC地址 [英] Get MAC address via TCPListener in C#
问题描述
是否可以通过C#中的TCPListener获取远程客户端的MAC地址?
Is it possible to get MAC Address of remote client via TCPListener in C#?
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();
}
}
}
}
}
推荐答案
否.MAC地址是链接层的一部分,仅用于通信同一主机中的两个主机物理链接.
No. The MAC address is part of the Link layer, only used to communicate two hosts in the same physical link.
过度简化...,假设 a
和 c
是计算机,而 b
是路由器.
Oversimplifying..., imagine that a
and c
are computers, and b
is a router.
a <-> b <-> c
如果 a
要发送数据包到 c
,则必须通过 b
.因此, a
发送的数据包的源IP地址为 a
,目标IP地址为 c
,源MAC地址为 a
地址 b
,因为路由器是下一跳.然后,当 b
收到该数据包时,它将使用源IP地址 a
,目标IP地址 c
c >,源MAC地址 b
和目标MAC地址 c
.
If a
wants to send a packet to c
, it has to go through b
. So a
sends packet with source IP address a
, target IP address c
, source MAC address a
and target MAC address b
, since the router is the next hop. Then when b
gets that packet, it will send it to c
using source IP address a
, target IP address c
, source MAC address b
and target MAC address c
.
这篇关于通过C#中的TCPListener获取MAC地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!