unity 获取本机的IP子网掩码网关
时间: 2023-09-09 20:13:38 浏览: 66
你可以使用以下代码获取本机的IP地址、子网掩码和网关:
```csharp
using System.Net;
using System.Net.NetworkInformation;
public void GetIPAddress()
{
string ipAddress = "";
string subnetMask = "";
string gateway = "";
NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface networkInterface in networkInterfaces)
{
if (networkInterface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || networkInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
IPInterfaceProperties ipProperties = networkInterface.GetIPProperties();
foreach (UnicastIPAddressInformation ipAddressInformation in ipProperties.UnicastAddresses)
{
if (ipAddressInformation.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
ipAddress = ipAddressInformation.Address.ToString();
subnetMask = ipAddressInformation.IPv4Mask.ToString();
break;
}
}
foreach (GatewayIPAddressInformation gatewayIpAddressInformation in ipProperties.GatewayAddresses)
{
gateway = gatewayIpAddressInformation.Address.ToString();
break;
}
}
}
Debug.Log("IP address: " + ipAddress);
Debug.Log("Subnet mask: " + subnetMask);
Debug.Log("Gateway: " + gateway);
}
```
注意,此代码仅适用于获取 IPv4 地址。如果你需要获取 IPv6 地址,需要相应地修改代码。