使用 C# 获取 IPv4

Getting IPv4 using C#

我正在尝试使用 c# 获取 ipconfig cmd 的 IPv4 字符串,以便在 IIS 服务器上使用 API。我正在使用此代码

public static string GetLocalIPAddress()
{
    var host = Dns.GetHostEntry(Dns.GetHostName());
    foreach (var ip in host.AddressList)
    {
        if (ip.AddressFamily == AddressFamily.InterNetwork)
        {
            return ip.ToString();
        }
    }
    throw new Exception("No network adapters with an IPv4 address in the system!");
}

但是我得到的Ip和ipconfig cmd里的不一样。如何使用 C# 从 ipconfig cmd 获取准确的 IPv4?

不知道这是不是你想做的。 但是您可以 运行 在 c#
中使用命令“ipconfig” 并使用正则表达式获取 ip。
像这样:

System.Diagnostics.ProcessStartInfo procStartInfo =
    new System.Diagnostics.ProcessStartInfo("cmd", "/c " + "ipconfig");
// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
// Get the output into a string
string result = proc.StandardOutput.ReadToEnd();
// Get IP
result = Regex.Match(result,@"IPv4.*:.(?'ip'([0-9]{0,3}\.){3}([0-9]{0,3}))").Groups["ip"].ToString();
// Display the command output.
Console.WriteLine(result);

你也可以用这个。 选择您要使用的界面。 例如接口类型以太网和名称“以太网” 该名称也可以是“vEthernet”或“Virtualbox”...... 像这样:

foreach(NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()){
// Test connection type ip is Ethernet && Name == Ethernet
if(ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet && ni.Name == "Ethernet")
{
    // Console.WriteLine(ni.Name);
    foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
    {
        if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
        {
            //Console.WriteLine(ip.Address.ToString());
            return ip.Address.ToString();
        }
    }
}
} 

(这个会更优化)