C# winform点击按钮获取指定ip的mac地址代码怎么写

2024-12-14 19:00:31
推荐回答(2个)
回答1:

我自己写的 你可以参考一下 using system.net.NetworkInformation

private void button1_Click(object sender, EventArgs e)
{
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
this.listBox1.Items.Clear();
//远程服务器ip
string remoteHostNameAddress = this.textBox1.Text.Trim();
//构造Ping实例
Ping pingSender = new Ping();
//Ping选项设置
PingOptions options = new PingOptions();
options.DontFragment = true;
//测试数据
string data = "test data abcabc";
byte[] buffer = Encoding.ASCII.GetBytes(data);
//设置超时时间
int timeout = 120;
//调用同步send方法发送数据,将返回结果保存至PingReply实例
PingReply reply = pingSender.Send(remoteHostNameAddress, timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
foreach (NetworkInterface adapter in adapters)
{
listBox1.Items.Add("答复的主机地址:" + reply.Address.ToString());
listBox1.Items.Add("往返时间:" + reply.RoundtripTime);
listBox1.Items.Add("生存时间(TTL):" + reply.Options.Ttl);
listBox1.Items.Add("MAC地址:" + adapter.GetPhysicalAddress());
}
}
else
{
listBox1.Items.Add(reply.Status.ToString());
}
}

回答2:

自己建立一个form窗体,同时在窗体上添加你需要的控件(button,TextBox等)

///


/// 通过Ip得到MAC地址
///

///
///
private string GetMacAddress(string IpAddress)//得到指定IP的MAC地址
{
string macAddress = "";
Int32 ldest = 0;
try
{
ldest = inet_addr(IpAddress);
}
catch (Exception iperr)
{
MessageBox.Show(iperr.Message);
}
Int64 macinfo = new Int64();
Int32 len = 6;
try
{
int res = SendARP(ldest, 0, ref macinfo, ref len);
}
catch (Exception err)
{
// throw new Exception("在解析MAC地址过程发生了错误!");
MessageBox.Show(err.Message);
}
string originalMACAddress = macinfo.ToString("X4");
if (originalMACAddress != "0000" && originalMACAddress.Length == 12)
{ //合法MAC地址
string mac1, mac2, mac3, mac4, mac5, mac6;
mac1 = originalMACAddress.Substring(10, 2);
mac2 = originalMACAddress.Substring(8, 2);
mac3 = originalMACAddress.Substring(6, 2);
mac4 = originalMACAddress.Substring(4, 2);
mac5 = originalMACAddress.Substring(2, 2);
mac6 = originalMACAddress.Substring(0, 2);
macAddress = mac1 + ":" + mac2 + ":" + mac3 + ":" + mac4 + ":" + mac5 + ":" + mac6;
//canPing = true;
}
else
{
macAddress = "无法探测到MAC地址";
//canPing = false;
}
return macAddress;
}