This article transferred from: http://blog.csdn.net/huutu/article/details/52155885
In fact, the difference between IPv4 and IPv6 is different when establishing a socket:
IPv4 socket:socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp);
IPv6 socket:socket = new Socket (ADDRESSFAMILY.INTERNETWORKV6, SocketType.Stream, protocoltype.tcp);
Then we set the socket to determine whether the user's current network type is IPv4 or IPv6.
Here's how unity adds support for IPV6.
One of them is dns.gethostaddress.
The following code:
Ipaddress[] Address=dns.gethostaddresses ("test.thisisgame.com.cn");
If the current network environment is IPV6, this function returns an IPV6 address, such as 64:ff9b::7237:5342.
If the current network environment is IPV4, this function returns an IPV4 address, such as 127.0.0.1.
Next, Judge IPAddress's addressfamily to determine the current network environment.
Address[0]. Addressfamily==addressfamily.internetworkv6
So you can judge whether it is IPV6 or IPV4.
public static string Checknetworkversion (String nhoststring)
{
String ntargetipstring = "www.baidu.com";
Ipaddress[] Address=dns.gethostaddresses (ntargetipstring);
if (address [0]. AddressFamily = = addressfamily.internetworkv6)
{
Debug.logerror ("[Socket network]------ipv6------");
MISINIP4 = false;
}else if (address [0]. AddressFamily = = addressfamily.internetwork) {
Debug.logerror ("[Socket network]------ipv4------");
}
string nouthost = nhoststring;
If the IPv6 network
if (!MISINIP4) {
System.Net.IPHostEntry host;
try {
Host = System.Net.Dns.GetHostEntry (nhoststring);
foreach (System.Net.IPAddress IP in host. AddressList) {
if (IP. AddressFamily = = System.Net.Sockets.AddressFamily.InterNetworkV6) {
Nouthost = IP. ToString ();
Break
}
}
} catch (Exception e) {
Debug.logerrorformat ("[Socket network] Error, getipaddress error: {0}", e.message);
}
}
Debug.logerror ("[Socket network]---IP addr---" + nouthost);
Mconnectsvrurl = Nouthost;
return nouthost;
}
public void Connect (Connectvars nvars)
{
if (Mnetcallback = = null) {
Return
}
Debug.logerror ("-----------connect-----------");
Mlinkstate = true;
Mconnectinfo = Nvars;
Debug.logerror ("-----------mIsInIp4-----------" + MISINIP4 + "/" + mconnectinfo.serveraddress);
if (MISINIP4) {
msocentity = new Socket (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp);
} else {
msocentity = new Socket (ADDRESSFAMILY.INTERNETWORKV6, SocketType.Stream, protocoltype.tcp);
}
Mreadbuffer = new byte[4096];
if (null = = msocentity)
return;
Mnetcallback.onrecvmessage (Fieventtype.connect_start, NULL, 0);
Debug.Log ("[" +tag+ "] Server IP =" +mconnectsvrurl+ "Server port=" +mconnectinfo.serverprot ");
IPEndPoint nendpoint = new IPEndPoint (Ipaddress.parse (Mconnectsvrurl), Mconnectinfo.serverprot);
Msocentity.beginconnect (Nendpoint, New System.AsyncCallback (onsocketconnected), msocentity);
}
Unity adds support for IPV6