unity 获取本机IP
//工具脚本1:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using UnityEngine;
public class GeIP
{
public enum address
{
IPv4, IPv6
}
/// <summary>
/// 获取本机IP
/// </summary>
/// <param name="Addfam">要获取的IP类型</param>
/// <returns></returns>
public static string IP(address fam)
{
if (fam== address .IPv6 && !Socket.OSSupportsIPv6)
{
return null;
}
string output = "";
foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces())
{
NetworkInterfaceType _type1 = NetworkInterfaceType.Wireless80211;
NetworkInterfaceType _type2 = NetworkInterfaceType.Ethernet;
if ((item.NetworkInterfaceType == _type1 || item.NetworkInterfaceType == _type2) && item.OperationalStatus == OperationalStatus.Up)
{
foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses)
{
if (fam== address.IPv4)
{
if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
{
output = ip.Address.ToString();
}
}
else if (fam== address.IPv6)
{
if (ip.Address.AddressFamily == AddressFamily.InterNetworkV6)
{
output = ip.Address.ToString();
}
}
}
}
}
return output;
}
}
调用
using static GeIP;
public class Ip : MonoBehaviour
{
private string infoText;
void Start()
{
infoText = GeIP.IP(address.IPv4);
}
private void EndValue(string value)
{
InputText = value; //捕捉数据,方便后续操作
Debug.Log("IP内容" + value);
}
}
写法二:
private string[] GetLocalIpv4()
{
IPAddress[] localIPs;
localIPs = Dns.GetHostAddresses(Dns.GetHostName());
StringCollection IpCollection = new StringCollection();
foreach (IPAddress ip in localIPs)
{
//根据AddressFamily判断是否为ipv4(InterNetwork),如果是ipv6 则条件为 InterNetWorkV6
if (ip.AddressFamily == AddressFamily.InterNetwork)
IpCollection.Add(ip.ToString());
}
string[] IpArray = new string[IpCollection.Count];
IpCollection.CopyTo(IpArray, 0);
return IpArray;
}
写法三:
//获取本地ip
string GetLocalIP()
{
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adater in adapters)
{
if (adater.Supports((NetworkInterfaceComponent.IPv4)))
{
UnicastIPAddressInformationCollection uniCast = adater.GetIPProperties().UnicastAddresses;
if (uniCast.Count > 0)
{
foreach (UnicastIPAddressInformation uni in uniCast)
{
if (uni.Address.AddressFamily == AddressFamily.InterNetwork)
{
return uni.Address.ToString();
}
}
}
}
}
return "127.0.0.1";
}
}
鸣谢
文章内容来源:https://www.cnblogs.com/qq2351194611/p/11465313.html
优质学习网站:
代码先锋网