C# 获取当前局域网IP
时间: 2023-07-19 16:42:16 浏览: 75
您使用以下代码在C#中获取当前局域网IP地址:
```csharp
using System.Net;
using System.Net.Sockets;
public 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("Local IP Address not found.");
}
```
此代码将返回当前计算机在局域网中使用的IPv4地址。请注意,您需要添加以下命名空间:`System.Net`和`System.Net.Sockets`。
相关问题
C# 获取windows当前IP地址
可以使用以下代码来获取Windows当前IP地址:
```csharp
using System.Net;
using System.Net.Sockets;
public static string GetLocalIPAddress()
{
string ipAddress = "";
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
ipAddress = ip.ToString();
break;
}
}
return ipAddress;
}
```
此代码将返回Windows当前使用的IPv4地址。
C#Ping局域网IP地址
您可以使用System.Net.NetworkInformation命名空间中的Ping类来完成此操作。以下是一个简单的示例代码,用于Ping局域网中的IP地址:
```
using System;
using System.Net.NetworkInformation;
class Program
{
static void Main(string[] args)
{
string ipAddress = "192.168.0.1"; // 要Ping的IP地址
Ping pingSender = new Ping();
PingReply reply = pingSender.Send(ipAddress);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine("Ping成功!响应时间为:" + reply.RoundtripTime.ToString() + "毫秒");
}
else
{
Console.WriteLine("Ping失败!");
}
}
}
```
请注意,您需要将“ipAddress”变量替换为您要Ping的实际IP地址。此外,您还需要为应用程序添加对System.Net.NetworkInformation命名空间的引用。