我有以下返回本地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
Run Code Online (Sandbox Code Playgroud)
您可以通过查询网络接口来执行此操作,但这将包括所有本地地址,因此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();
Run Code Online (Sandbox Code Playgroud)
注意:如果您只需要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();
Run Code Online (Sandbox Code Playgroud)
using System.Net;
IPAddress localAddr = Dns.GetHostEntry(Dns.GetHostName().ToString()).AddressList[0];
Run Code Online (Sandbox Code Playgroud)
[编辑]嗯......刚才意识到你提到你不想使用DNS ......为什么会这样?
[编辑]从评论中提升......
更简单的版本,如果您只关心本地,空字符串传递给GetHostEntry将默认返回本地
IPAddress localAddr = Dns.GetHostEntry("").AddressList[0];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3724 次 |
| 最近记录: |