我对编程一般都很陌生,所以答案可能非常简单。我试图将每个NIC的所有IP显示在标签中。我可以在控制台中运行相同的代码,并使其正确输出。我可以将它添加到列表框并正确显示,但我无法弄清楚如何获得更多的IP到标签中。希望这是有道理的。我在互联网上发现了大部分代码,并试图了解它们如何一起工作,所以如果您看到一些可能无意义的注释行,那么您知道为什么。有问题的标签是label8.Text如何通过C#中的标签显示多个IP地址
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.NetworkInformation;
using System.Net;
using System.Net.Sockets;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//first we should create an array of the network interfaces
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
//now lets iterate through the list of nics and call them adapter
foreach (NetworkInterface adapter in nics)
{
//add the adapter description to the listbox1 items
listBox1.Items.Add(adapter.Description);
}
}
public void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//Lets make our form taller so that the labels can be seen.
Form1.ActiveForm.Height = 320;
//Get the currently chosen listBox item.
string nicname = listBox1.Text;
//Again build an array of all the Network Interfaces.
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
//Lets loop through those interfaces
foreach (NetworkInterface adapter in nics)
{
//Lets condition on the adapter description making sure it equals the nicname of the chosen adapter in the listbox1
if (nicname == adapter.Description)
{
//Lets update all the labels to display more information about the chosen adapter.
label1.Text = adapter.Description;
label2.Text = "Name: " + adapter.Name;
label3.Text = "Type: " + adapter.NetworkInterfaceType;
label4.Text = "Status: " + adapter.OperationalStatus;
label5.Text = "Speed: " + adapter.Speed;
label6.Text = "Multicast Support? " + adapter.SupportsMulticast;
label7.Text = "MAC: " + adapter.GetPhysicalAddress();
//NetworkInterface[] prop = NetworkInterface.GetAllNetworkInterfaces();
IPInterfaceProperties properties = adapter.GetIPProperties();
foreach (IPAddressInformation uniCast in properties.UnicastAddresses)
{
label8.Text = "IP: " + (uniCast.Address);
//label11.Text = "IP: " + uniCast.Address;
//listBox2.Items.Add(uniCast.Address);
foreach (UnicastIPAddressInformation uipi in adapter.GetIPProperties().UnicastAddresses)
label10.Text = "Subnet: " + uipi.IPv4Mask;
}
foreach (GatewayIPAddressInformation GateWay in properties.GatewayAddresses)
{
label9.Text = "Gateway: " + GateWay.Address;
}
}
}
}
}
}