首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用IPv4实现C#

使用IPv4实现C#
EN

Stack Overflow用户
提问于 2021-10-28 06:35:33
回答 2查看 222关注 0票数 0

我试图使用IIS服务器上的IPv4来使用c#来获取ipconfig的c#字符串。我在用这个代码

代码语言:javascript
复制
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中的不同。如何使用IPv4从ipconfig cmd获得确切的C#?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-10-28 09:36:34

我不知道这是不是你想做的。但是您可以在c#中运行命令"ipconfig“。

并使用正则表达式获取ip。

如下所示:

代码语言:javascript
复制
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);
票数 1
EN

Stack Overflow用户

发布于 2021-10-28 12:28:13

你也可以用这个。若要选择要使用的接口,请执行以下操作。例如,接口类型以太网和名称“以太网”的名称也可以是"vEthernet“或"Virtualbox”。如下所示:

代码语言:javascript
复制
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();
        }
    }
}
} 

(这将更加优化)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69749287

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档