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())
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());