本文转自:http://blog.csdn.net/huutu/article/details/52155885
其实ipv4与ipv6之间的区别在建立socket时就有不同:
ipv4的socket:socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
ipv6的socket:socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
然后我们在建立socket的时候要判断用户的当前网络类型是ipv4还是ipv6。
这里要说到Unity 新增的对IPV6的支持。
其中之一就是 Dns.GetHostAddress 。
如下代码:
IPAddress[] address=Dns.GetHostAddresses("test.thisisgame.com.cn");
如果当前是 IPV6 的网络环境,这个函数会返回一个 IPV6 地址,如64:ff9b::7237:5342。
如果当前是 IPV4 的网络环境,这个函数会返回一个 IPV4 地址,如 127.0.0.1。
接下来判断 IPAddress 的 AddressFamily来确定当前的网络环境。
address[0].AddressFamily==AddressFamily.InterNetworkV6
这样就可以判断是IPV6 还是 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;
//如果是ipv6 网络
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 );
}