2009-06-05 99 views
5

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

我遇到的所有解决方案都涉及使用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 

回答

9

你可以通过查询网络接口来做到这一点,虽然这将包括所有的本地地址,所以如果有多个接口(可能会有),你可能必须添加一个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();  
5
using System.Net; 

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

[编辑] hmmmm ......只是意识到你提到你不想使用DNS ......这是为什么?

[编辑]从评论连升....

,如果你只关心地方,空字符串传递给GetHostEntry将默认本地只返回

IPAddress localAddr = Dns.GetHostEntry("").AddressList[0]; 
+0

感谢您抽出宝贵时间! DNS要求他们目前有权访问我们的DNS,对吗?除非该声明不真实,否则我的问题在于我的应用程序是有时连接的应用程序,并不总是在我们的家庭网络上。他们可能在家或在客户家中。附: - >我觉得有趣的是,你有4个upvotes的答案是违背我发布的。我的意思是没有进攻,只是我在这里注意到越来越多的观察。 再次感谢! – 2009-06-05 16:59:55

+0

嗯,任何想法,为什么这将返回此 - > fe80 :: ad11:2dc5:58af:a24b%14? – 2009-06-05 17:05:27

+0

@Refracted Paladin - 这是一个IPv6 IP地址。 – 2009-06-05 17:14:42

1

我个人会建议简化版本使用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); 

这应该正确地获取日电子邮件但可能需要一些调整。

2

它看起来你的脚本正在调用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(); 
} 

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

0

您可以滚动查看所有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 
    }