[.NET]取得本機上所有的IP Address
要取得執行程式的電腦上所有的IP Address可透過 NetworkInterface 來達到這個目的。
C#程式如下,
//取得本機上所有的IP Address
int num = 1;
System.Text.StringBuilder ipAddressList = new System.Text.StringBuilder();
foreach (System.Net.NetworkInformation.NetworkInterface nic
in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces())
{
foreach (System.Net.NetworkInformation.IPAddressInformation ipInfo
in nic.GetIPProperties().UnicastAddresses)
{
//取得IP Address
ipAddressList.Append("IP #" + num + ": " + ipInfo.Address.ToString() + Environment.NewLine );
num += 1;
}
}
MessageBox.Show("全部的IP:" + Environment.NewLine + ipAddressList.ToString());
//取得本機上ipv4及非Loopback的IP Address
ipAddressList.Clear();
num = 1;
foreach (System.Net.NetworkInformation.NetworkInterface nic
in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces())
{
foreach (System.Net.NetworkInformation.IPAddressInformation ipInfo
in nic.GetIPProperties().UnicastAddresses)
{
if (System.Net.IPAddress.IsLoopback(ipInfo.Address) == false
&& ipInfo.Address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetworkV6)
{
//取得IP Address
ipAddressList.Append("IP #" + num + ": " + ipInfo.Address.ToString() + Environment.NewLine );
num += 1;
}
}
}
MessageBox.Show("只列出ipv4及非Loopback的IP:" + Environment.NewLine + ipAddressList.ToString());
VB.NET程式如下,
'取得本機上所有的IP Address
Dim num As Integer = 1
Dim ipAddressList As System.Text.StringBuilder = New System.Text.StringBuilder
For Each nic As System.Net.NetworkInformation.NetworkInterface
_ In System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()
For Each ipInfo As System.Net.NetworkInformation.IPAddressInformation
_ In nic.GetIPProperties().UnicastAddresses
'取得IP Address
ipAddressList.Append("IP #" & num & ": " & ipInfo.Address.ToString() & vbCrLf)
num += 1
Next
Next
MessageBox.Show("全部的IP:" & vbCrLf & ipAddressList.ToString())
'取得本機上ipv4及非Loopback的IP Address
ipAddressList.Clear()
num = 1
For Each nic As System.Net.NetworkInformation.NetworkInterface
_ In System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()
For Each ipInfo As System.Net.NetworkInformation.IPAddressInformation
_ In nic.GetIPProperties().UnicastAddresses
If System.Net.IPAddress.IsLoopback(ipInfo.Address) = False _
AndAlso ipInfo.Address.AddressFamily <> Net.Sockets.AddressFamily.InterNetworkV6 Then
'取得IP Address
ipAddressList.Append("IP #" & num & ": " & ipInfo.Address.ToString() & vbCrLf)
num += 1
End If
Next
Next
MessageBox.Show("只列出ipv4及非Loopback的IP:" & vbCrLf & ipAddressList.ToString())
如果要取得MAC Address也可以透過 NetworkInterface.GetPhysicalAddress 方法哦!
Hi,
亂馬客Blog已移到了 「亂馬客 : Re:從零開始的軟體開發生活」
請大家繼續支持 ^_^