我试图使用IIS服务器上的IPv4来使用c#来获取ipconfig的c#字符串。我在用这个代码
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#?
发布于 2021-10-28 09:36:34
我不知道这是不是你想做的。但是您可以在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);发布于 2021-10-28 12:28:13
你也可以用这个。若要选择要使用的接口,请执行以下操作。例如,接口类型以太网和名称“以太网”的名称也可以是"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();
}
}
}
} (这将更加优化)
https://stackoverflow.com/questions/69749287
复制相似问题