如何在.NET 中获取本地IP?

发布于 2024-07-23 11:06:08 字数 1031 浏览 0 评论 0原文

我有以下返回本地 IP 地址的 vbscript 代码。 效果很好。 我试图在我的 winform .net 应用程序中提供相同的功能。

我遇到的所有解决方案都涉及使用 DNS。 关于如何“移植”此脚本以便在 .net 中使用有什么想法吗?

也许有不同的方法来做到这一点?

谢谢!

Function GetIP()

 Dim ws : Set ws = CreateObject("WScript.Shell")
  Dim fso : Set fso = CreateObject("Scripting.FileSystemObject")
  Dim TmpFile : TmpFile = fso.GetSpecialFolder(2) & "/ip.txt"
  Dim ThisLine, IP
  If ws.Environment("SYSTEM")("OS") = "" Then
    ws.run "winipcfg /batch " & TmpFile, 0, True
  Else
    ws.run "%comspec% /c ipconfig > " & TmpFile, 0, True
  End If
  With fso.GetFile(TmpFile).OpenAsTextStream
    Do While NOT .AtEndOfStream
      ThisLine = .ReadLine
      If InStr(ThisLine, "Address") <> 0 Then IP = Mid(ThisLine, InStr(ThisLine, ":") + 2)
    Loop
    .Close
  End With

  If IP <> "" Then
    If Asc(Right(IP, 1)) = 13 Then IP = Left(IP, Len(IP) - 1)
  End If
  GetIP = IP
  fso.GetFile(TmpFile).Delete  
  Set fso = Nothing
  Set ws = Nothing
End Function

I have the following vbscript code that returns the local IP address. It works great. I am trying to provide the same functionality in my winform .net app.

All the solutions I have come across involve using DNS. Any ideas on how to "port" this script for use in .net?

A different way to do this maybe?

Thanks!

Function GetIP()

 Dim ws : Set ws = CreateObject("WScript.Shell")
  Dim fso : Set fso = CreateObject("Scripting.FileSystemObject")
  Dim TmpFile : TmpFile = fso.GetSpecialFolder(2) & "/ip.txt"
  Dim ThisLine, IP
  If ws.Environment("SYSTEM")("OS") = "" Then
    ws.run "winipcfg /batch " & TmpFile, 0, True
  Else
    ws.run "%comspec% /c ipconfig > " & TmpFile, 0, True
  End If
  With fso.GetFile(TmpFile).OpenAsTextStream
    Do While NOT .AtEndOfStream
      ThisLine = .ReadLine
      If InStr(ThisLine, "Address") <> 0 Then IP = Mid(ThisLine, InStr(ThisLine, ":") + 2)
    Loop
    .Close
  End With

  If IP <> "" Then
    If Asc(Right(IP, 1)) = 13 Then IP = Left(IP, Len(IP) - 1)
  End If
  GetIP = IP
  fso.GetFile(TmpFile).Delete  
  Set fso = Nothing
  Set ws = Nothing
End Function

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

情话难免假 2024-07-30 11:06:08

您可以通过查询网络接口来完成此操作,尽管这将包括所有本地地址,因此您可能必须添加一个 where 子句来选择您想要的一个,如果有多个接口(可能会出现)。 它当然不是脚本的直接端口,但希望会有一些用处:

var localAddress = 
    (from ni in NetworkInterface.GetAllNetworkInterfaces()
     where ni.NetworkInterfaceType != NetworkInterfaceType.Loopback
     let props = ni.GetIPProperties()
     from ipAddress in props.UnicastAddresses
     select ipAddress).FirstOrDefault();    

注意:如果您只需要 IPv4 地址,那么您可以将查询更改为:

var localAddress = 
    (from ni in NetworkInterface.GetAllNetworkInterfaces()
     where ni.NetworkInterfaceType != NetworkInterfaceType.Loopback
     let props = ni.GetIPProperties()
     from ipAddress in props.UnicastAddresses
     where ipAddress.AddressFamily == AddressFamily.InterNetwork // IPv4
     select ipAddress).FirstOrDefault();     

You can do this by querying the network interfaces, though this will include all local addresses so you may have to add a where clause to select the one you want if there are multiple interfaces (which there likely will be). It's certainly not a direct port of your script, but hopefully will be of some use:

var localAddress = 
    (from ni in NetworkInterface.GetAllNetworkInterfaces()
     where ni.NetworkInterfaceType != NetworkInterfaceType.Loopback
     let props = ni.GetIPProperties()
     from ipAddress in props.UnicastAddresses
     select ipAddress).FirstOrDefault();    

Note: If you only want IPv4 addresses, then you could alter the query to:

var localAddress = 
    (from ni in NetworkInterface.GetAllNetworkInterfaces()
     where ni.NetworkInterfaceType != NetworkInterfaceType.Loopback
     let props = ni.GetIPProperties()
     from ipAddress in props.UnicastAddresses
     where ipAddress.AddressFamily == AddressFamily.InterNetwork // IPv4
     select ipAddress).FirstOrDefault();     
触ぅ动初心 2024-07-30 11:06:08
using System.Net;

IPAddress localAddr = Dns.GetHostEntry(Dns.GetHostName().ToString()).AddressList[0];

[编辑] 嗯...刚刚意识到你提到你不想使用 DNS...为什么呢?

[编辑]从评论中向上移动...

如果您只关心本地,则更简单的版本,传递给 GetHostEntry 的空字符串默认情况下将仅返回本地

IPAddress localAddr = Dns.GetHostEntry("").AddressList[0];
using System.Net;

IPAddress localAddr = Dns.GetHostEntry(Dns.GetHostName().ToString()).AddressList[0];

[edit] hmmmm...just realized that you mentioned you don't want to use DNS...why is that?

[edit] moving up from comments....

Simpler version if you only care about local, empty string pass to GetHostEntry will by default return local only

IPAddress localAddr = Dns.GetHostEntry("").AddressList[0];
亚希 2024-07-30 11:06:08

看起来您的脚本正在调用 ipconfig,将输出保存到文件,然后解析该文件。 如果你想这样做,你会做这样的事情:

using System.Threading;

...

static void Main(string[] args)
{
    Process p = new Process();

    ProcessStartInfo psi = new ProcessStartInfo("ipconfig");
    psi.CreateNoWindow = true;
    psi.RedirectStandardOutput = true;
    psi.UseShellExecute = false;

    p.StartInfo = psi;
    p.Start();

    string s = p.StandardOutput.ReadToEnd();
    int startPos = s.IndexOf(":", s.IndexOf("IPv4 Address"));
    string output = s.Substring(startPos + 2, s.IndexOf("\r\n", startPos) - startPos - 2);
    Console.WriteLine(output);
    Console.ReadLine();
}

请注意,我不是特别喜欢这种方法 - 你可能会更好地使用此线程中列出的一些其他解决方案 - 但它是一个更直接翻译您的原始脚本。

It looks like your script is calling ipconfig, saving the output to a file, and then parsing the file. If you want to do that, you would do something like this:

using System.Threading;

...

static void Main(string[] args)
{
    Process p = new Process();

    ProcessStartInfo psi = new ProcessStartInfo("ipconfig");
    psi.CreateNoWindow = true;
    psi.RedirectStandardOutput = true;
    psi.UseShellExecute = false;

    p.StartInfo = psi;
    p.Start();

    string s = p.StandardOutput.ReadToEnd();
    int startPos = s.IndexOf(":", s.IndexOf("IPv4 Address"));
    string output = s.Substring(startPos + 2, s.IndexOf("\r\n", startPos) - startPos - 2);
    Console.WriteLine(output);
    Console.ReadLine();
}

Note that I'm not particularly fond of this method -- you would probably be better served with some of the other solutions listed in this thread -- but it is a more direct translation of your original script.

一杆小烟枪 2024-07-30 11:06:08

我个人建议使用 DNS,但如果您绝对不想这样做,您可以通过调用 System.Management 命名空间来获取信息,

string ipAddress = "";
ManagementObjectSearcher query =
    new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'");
ManagementObjectCollection queryCollection = query.Get();
foreach (ManagementObject mo in queryCollection)
{
    string[] addresses = (string[]) mo["IPAddress"];
    if (addresses.Length == 1 && addresses[0] != "0.0.0.0")
    {
        ipAddress = addresses[0];
        break;
    }

}
Console.WriteLine(ipAddress);

这应该正确获取 IP,但可能需要一些调整。

I personally would recommend using the DNS, but if you absolutely don't want to you can get the information from a call to the System.Management namespace

string ipAddress = "";
ManagementObjectSearcher query =
    new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'");
ManagementObjectCollection queryCollection = query.Get();
foreach (ManagementObject mo in queryCollection)
{
    string[] addresses = (string[]) mo["IPAddress"];
    if (addresses.Length == 1 && addresses[0] != "0.0.0.0")
    {
        ipAddress = addresses[0];
        break;
    }

}
Console.WriteLine(ipAddress);

That should correctly get the ip but may need some tweaking.

一刻暧昧 2024-07-30 11:06:08

您可以滚动查看所有 IP 地址。

    String hostName = Dns.GetHostName();                      
    IPHostEntry local = Dns.GetHostByName(hostName);
    foreach (IPAddress ipaddress in local.AddressList)
    {
        ipaddress.ToString();  //this gives you the IP address
        //logic here 
    }

You can scroll through this to find all ip addresses.

    String hostName = Dns.GetHostName();                      
    IPHostEntry local = Dns.GetHostByName(hostName);
    foreach (IPAddress ipaddress in local.AddressList)
    {
        ipaddress.ToString();  //this gives you the IP address
        //logic here 
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文