//连接 public void Connect() { if (isConnected || m_connectState == ConnectState.Connnecting) { Debug.Log("已经连接上了,别再连接,会出事的!"); return; } string strNewIp = ""; AddressFamily newAddressFamily = AddressFamily.InterNetwork; IPv6SupportMidleware.getIPType(mIp, mPort.ToString(), out strNewIp, out newAddressFamily); Debug.Log(" Socket AddressFamily :" + newAddressFamily.ToString() + "原始ip:" + mIp + ", 结果ip:" + strNewIp + ",端口:" + mPort); m_client = new TcpClient(newAddressFamily); m_client.SendTimeout = 1000; m_client.ReceiveTimeout = 5000; m_client.NoDelay = true; m_client.SendBufferSize = 1024 * 8; m_client.ReceiveBufferSize = NetConst.TMP_BUF_SIZE; m_client.Client.Blocking = true; m_connectState = ConnectState.Connnecting; try { m_client.BeginConnect(strNewIp, mPort, new AsyncCallback(OnConnect), m_client); } catch (Exception e) { //*设置失败次数++ Debug.Log("连接不通:" + e.Message + " ==>" + e.ToString()); m_connectState = ConnectState.ConnectFail; OnDisconnected(DisType.ConnectTimeOut, "连接游戏服务器失败!(-1)"); } }
private static bool IsProtocolSupported(AddressFamily af) { int family; switch (af) { case AddressFamily.InterNetwork: family = Interop.libc.AF_INET; break; case AddressFamily.InterNetworkV6: family = Interop.libc.AF_INET6; break; default: Debug.Fail("Invalid address family: " + af.ToString()); throw new ArgumentException("af"); } int socket = -1; try { socket = Interop.libc.socket(family, Interop.libc.SOCK_DGRAM, 0); if (socket == -1) { return Interop.Sys.GetLastError() != Interop.Error.EAFNOSUPPORT; } return true; } finally { if (socket != -1) { Interop.Sys.Close(socket); } } }
public override IPEndPoint CreateIPEndPoint(AddressFamily ipAddrFamily, int port) { IPAddress addr = null; String strAddr = null; IPEndPoint res = null; if (ipAddrFamily == AddressFamily.InterNetworkV6) { strAddr = _PredefinedIpV6; } if (ipAddrFamily == AddressFamily.InterNetwork) { strAddr = _PredefinedIpV4; } if (strAddr != null && strAddr != String.Empty) { if (!IPAddress.TryParse(strAddr, out addr)) { throw new Exception(strAddr + "Not Valid " + ipAddrFamily.ToString()); } IPHostEntry HostEntry = Dns.GetHostEntry(Dns.GetHostName()); //var foundInHost = from a in HostEntry.AddressList where a == ipAddress select a; //if (foundInHost.Count() == 0) // throw new Exception(strAddr + " is out of host addresses"); res = new IPEndPoint(addr, port); } return(res); }
public SocketClient(string ip, int port) { //targetIpString = ip; targetPort = port; #region ipv6 String newServerIp = ""; getIPType(ip, port.ToString(), out newServerIp, out newAddressFamily); // 这里newServerIp已经是IPv6类型的IP地址了 if (!string.IsNullOrEmpty(newServerIp)) { ip = newServerIp; } //socketClient = new Socket(newAddressFamily, SocketType.Stream, ProtocolType.Tcp); Debug.Log("Socket AddressFamily :" + newAddressFamily.ToString() + " ServerIp:" + ip + " newServerIp:" + newServerIp); #endregion if (ip.ToLower() == "local" || ip.ToLower() == "localhost") { TargetIPAddress = ConnectionHelp.GetMyIP(); } else { //TargetIPAddress = Dns.GetHostAddresses(ip).First(p => p.AddressFamily == AddressFamily.InterNetwork); TargetIPAddress = Dns.GetHostAddresses(ip).First(p => p.AddressFamily == newAddressFamily); Debug.Log("TargetIPAddress :" + TargetIPAddress); // 这里的TargetIPAddress已经是IPv6类型的IP地址了 } }
public static EndPoint Create(this EndPoint thisObj, Internals.SocketAddress socketAddress) { AddressFamily family = socketAddress.Family; if (family != thisObj.AddressFamily) { throw new ArgumentException(SR.Format(SR.net_InvalidAddressFamily, family.ToString(), thisObj.GetType().FullName, thisObj.AddressFamily.ToString()), nameof(socketAddress)); } if (family == AddressFamily.InterNetwork || family == AddressFamily.InterNetworkV6) { if (socketAddress.Size < 8) { throw new ArgumentException(SR.Format(SR.net_InvalidSocketAddressSize, socketAddress.GetType().FullName, thisObj.GetType().FullName), nameof(socketAddress)); } return(socketAddress.GetIPEndPoint()); } else if (family == AddressFamily.Unknown) { return(thisObj); } System.Net.SocketAddress address = GetNetSocketAddress(socketAddress); return(thisObj.Create(address)); }
public override string ToString() { if (Data is null) { return("NULL"); } return("" + new IPAddress(Data).ToString() + " (" + AddressFamily.ToString() + ")"); }
public override string ToString() { if (Handle.Handle == IntPtr.Zero) { return("NULL"); } return("" + IPAddress.ToString() + " (" + AddressFamily.ToString() + ")"); }
public static IPAddress GetLocalIp(AddressFamily type = AddressFamily.InterNetwork) { foreach (IPAddress address in Dns.GetHostAddresses(Dns.GetHostName())) { if (address.AddressFamily == type) { return(address); } } throw new Exception($"No address of type {type.ToString()} was found."); }
public void IsSerialized(String host, Int32 port, AddressFamily addressFamily) { var expectedToken = new JObject { ["Host"] = host, ["Port"] = port, ["AddressFamily"] = addressFamily.ToString() }; var actualToken = serializer.ToToken(new DnsEndPoint(host, port, addressFamily)); actualToken.Should().BeEquivalentTo(expectedToken); }
public void IsDeserialized(String host, Int32 port, AddressFamily addressFamily) { var token = new JObject { ["Host"] = host, ["Port"] = port, ["AddressFamily"] = addressFamily.ToString() }; var actual = serializer.FromToken <DnsEndPoint>(token); actual.Host.Should().Be(host); actual.Port.Should().Be(port); actual.AddressFamily.Should().Be(addressFamily); }
/************ Funcs **************/ public void Connect(string ip, int port) { SetForceKickOff(false); //try //{ LOG.Log("Time: " + System.DateTime.Now.Second.ToString() + " ip:" + ip + " port:" + port); /* #if !(UNITY_ANDROID || UNITY_IPHONE || UNITY_STANDALONE_WIN) * bool ret = Security.PrefetchSocketPolicy(ip, port, 10000); * LOG.Log("Time: " + System.DateTime.Now.Second.ToString() + " " + "Security.PrefetchSocketPolicy Ret: " + ret); * if (ret == false) * { * LOG.Error("无法获取策略文件!"); * state = NetworkState.ConnectFailed; * return; * } #else #endif */ try { String newServerIp = ""; AddressFamily newAddressFamily = AddressFamily.InterNetwork; //cc ipv6 getIPType(ip, port.ToString(), out newServerIp, out newAddressFamily); if (!string.IsNullOrEmpty(newServerIp)) { ip = newServerIp; } Debug.Log("Socket AddressFamily :" + newAddressFamily.ToString() + "ServerIp:" + ip); client = new TcpClient(newAddressFamily); client.Connect(ip, port); client.GetStream().BeginRead(readBuf, 0, READ_BUFFER_SIZE, new AsyncCallback(DoRead), null); state = NetworkState.ConnectSuccess; LOG.Log(state.ToString()); } catch (Exception ex) { state = NetworkState.ConnectFailed; LOG.Log("Can not Connect! " + ex + " exception"); //MessageBox.Instance.Show("服务器维护中"); } }
public string ExpandVariables( string input ) { string result = input; result = result.Replace( "$(Port)", Convert.ToString(Number) ); result = result.Replace( "$(PortAddressFamily)", AddressFamily.ToString() ); result = result.Replace( "$(PortSocketType)", SocketType.ToString() ); result = result.Replace( "$(PortProtocolType)", ProtocolType.ToString() ); //result = result.Replace( "$(HostName)", Owner.Address ); result = result.Replace( "$(Now)", DateTime.Now.ToString() ); result = result.Replace( "$(ErrorMessage)", Exception!=null?Exception.Message:"(no exception)" ); return result; }
static void Net_Test6_DualStack_Client() { string hostname = "www.google.com"; using (var tcp = LocalNet.ConnectIPv4v6Dual(new TcpConnectParam(hostname, 443, connectTimeout: 5 * 1000))) { tcp.Info.GetValue <ILayerInfoIpEndPoint>().RemoteIPAddress !.AddressFamily.ToString()._Print(); using (SslSock ssl = new SslSock(tcp)) { var sslClientOptions = new PalSslClientAuthenticationOptions() { TargetHost = hostname, ValidateRemoteCertificateProc = (cert) => { return(true); }, }; ssl.StartSslClient(sslClientOptions); var st = ssl.GetStream(); var w = new StreamWriter(st); var r = new StreamReader(st); w.WriteLine("GET / HTTP/1.0"); w.WriteLine($"HOST: {hostname}"); w.WriteLine(); w.WriteLine(); w.Flush(); while (true) { string?s = r.ReadLine(); if (s == null) { break; } Con.WriteLine(s); } } } }
public void SocketClient(string serverIp, String serverPorts) { String newServerIp = ""; AddressFamily newAddressFamily = AddressFamily.InterNetwork; IPV6.GetIPType(serverIp, serverPorts, out newServerIp, out newAddressFamily); if (!string.IsNullOrEmpty(newServerIp)) { serverIp = newServerIp; } Socket socketClient = new Socket(newAddressFamily, SocketType.Stream, ProtocolType.Tcp); IAsyncResult asyncResult = socketClient.BeginConnect(newServerIp, 8000, null, null); bool isFinished = asyncResult.AsyncWaitHandle.WaitOne(30, false); Debug.Log("Socket AddressFamily :" + newAddressFamily.ToString() + "ServerIp:" + serverIp); //socketClient.Connect(serverIp, 8000); StartCoroutine(check(socketClient)); }
private static bool IsProtocolSupported(AddressFamily af) { int family; switch (af) { case AddressFamily.InterNetwork: family = Interop.libc.AF_INET; break; case AddressFamily.InterNetworkV6: family = Interop.libc.AF_INET6; break; default: Debug.Fail("Invalid address family: " + af.ToString()); throw new ArgumentException("af"); } int socket = -1; try { socket = Interop.libc.socket(family, Interop.libc.SOCK_DGRAM, 0); if (socket == -1) { return(Interop.Sys.GetLastError() != Interop.Error.EAFNOSUPPORT); } return(true); } finally { if (socket != -1) { Interop.Sys.Close(socket); } } }
private void Initialize(AddressFamily addressFamily) { if (_socket != null) { Close(); _socket = null; } switch (addressFamily) { case AddressFamily.InterNetwork: Type = SessionType.IPv4; break; case AddressFamily.InterNetworkV6: Type = SessionType.IPv6; break; default: throw new Exception($"Not supported address family '{addressFamily.ToString()}'."); } _socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp); _receiver = new SessionReceiver(_defaultMaxPacketLength); _receiver.Reset(_defaultPacketLength); }
private static bool IsProtocolSupported(AddressFamily af) { SocketError errorCode; IntPtr s = IntPtr.Zero; bool ret = true; try { s = Interop.Winsock.WSASocketW(af, SocketType.Dgram, 0, IntPtr.Zero, 0, 0); if (s == IntPtr.Zero) { errorCode = (SocketError)Marshal.GetLastWin32Error(); if (errorCode == SocketError.AddressFamilyNotSupported) { ret = false; } } } finally { if (s != IntPtr.Zero) { SocketError closeResult = Interop.Winsock.closesocket(s); #if DEBUG if (closeResult != SocketError.Success) { errorCode = (SocketError)Marshal.GetLastWin32Error(); Debug.Fail("Failed to detect " + af.ToString() + " protocol: " + errorCode.ToString()); } #endif } } return ret; }
private static bool IsProtocolSupported(AddressFamily af) { SocketError errorCode; IntPtr s = IntPtr.Zero; bool ret = true; try { s = Interop.Winsock.WSASocketW(af, SocketType.Dgram, 0, IntPtr.Zero, 0, 0); if (s == IntPtr.Zero) { errorCode = (SocketError)Marshal.GetLastWin32Error(); if (errorCode == SocketError.AddressFamilyNotSupported) { ret = false; } } } finally { if (s != IntPtr.Zero) { SocketError closeResult = Interop.Winsock.closesocket(s); #if DEBUG if (closeResult != SocketError.Success) { errorCode = (SocketError)Marshal.GetLastWin32Error(); Debug.Fail("Failed to detect " + af.ToString() + " protocol: " + errorCode.ToString()); } #endif } } return(ret); }
/// <summary> /// Provides an IP address that matches all IPAddresses of the provided targetAddressFamily /// </summary> /// <param name="targetAddressFamily"></param> /// <returns></returns> private static IPAddress AnyRemoteIPAddress(AddressFamily targetAddressFamily) { if (targetAddressFamily == AddressFamily.InterNetwork) { return(IPAddress.Any); } else if (targetAddressFamily == AddressFamily.InterNetworkV6) { return(IPAddress.IPv6Any); } else { throw new CommunicationException("Attempting to send UDP packet over unsupported network address family: " + targetAddressFamily.ToString()); } }
void CheckAddrVer(AddressFamily af) { if (this.af != af) { throw new UdtException( string.Format("The AddressFamily {0} is different from the AddressFamily of this socket", af.ToString())); } }
private void Initialize(AddressFamily addressFamily, int maxPacketLength) { if (m_Socket != null) { Close(); m_Socket = null; } if (maxPacketLength <= 0) { throw new GameFrameworkException("Max packet length is invalid."); } m_MaxPacketLength = maxPacketLength; switch (addressFamily) { case AddressFamily.InterNetwork: m_NetworkType = NetworkType.IPv4; break; case AddressFamily.InterNetworkV6: m_NetworkType = NetworkType.IPv6; break; default: throw new GameFrameworkException(string.Format("Not supported address family '{0}'.", addressFamily.ToString())); } m_Socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp); m_ReceiveState = new ReceiveState(maxPacketLength); }
public IPAddress GetBindIPAddress(AddressFamily DesiredFamily) { IPAddress[] addresses = Dns.Resolve(Dns.GetHostName()).AddressList; foreach (IPAddress address in addresses) { if (address.AddressFamily == DesiredFamily) { MyWriteLine("DNS resolved localhost to " + address.ToString() + " for addressFamily " + DesiredFamily.ToString()); return(address); } } throw new Exception("Failed to resolve machine name to desired address family"); }