gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 16:32:56 24 4
gpt4 key购买 nike

我有以下返回本地 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

最佳答案

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

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();

关于.net - 如何在 .NET 中获取本地 IP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/956907/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com