internal UnixDomainSocketEndPoint(SocketAddress socketAddress) { if (socketAddress == null) { throw new ArgumentNullException("socketAddress"); } if (socketAddress.Family != EndPointAddressFamily || socketAddress.Size > MaxSocketAddressSize) { throw new ArgumentOutOfRangeException("socketAddress"); } if (socketAddress.Size >= MinSocketAddressSize) { _encodedPath = new byte[socketAddress.Size - PathOffset]; for (int index = 0; index < socketAddress.Size - PathOffset; index++) { _encodedPath[index] = socketAddress[PathOffset + index]; } _path = s_pathEncoding.GetString(_encodedPath, 0, _encodedPath.Length); } else { // Empty path may be used by System.Net.Socket logging. _encodedPath = Array.Empty<byte>(); _path = string.Empty; } }
internal UnixDomainSocketEndPoint(SocketAddress socketAddress) { if (socketAddress == null) { throw new ArgumentNullException(nameof(socketAddress)); } if (socketAddress.Family != EndPointAddressFamily || socketAddress.Size > s_nativeAddressSize) { throw new ArgumentOutOfRangeException(nameof(socketAddress)); } if (socketAddress.Size > s_nativePathOffset) { _encodedPath = new byte[socketAddress.Size - s_nativePathOffset]; for (int i = 0; i < _encodedPath.Length; i++) { _encodedPath[i] = socketAddress[s_nativePathOffset + i]; } _path = s_pathEncoding.GetString(_encodedPath, 0, _encodedPath.Length); } else { _encodedPath = Array.Empty<byte>(); _path = string.Empty; } }
internal void SetUnmanagedStructures(byte[] buffer, int offset, int size, SocketAddress socketAddress, bool pinSocketAddress) { base.SetUnmanagedStructures(buffer); this.m_SingleBuffer.Length = size; this.m_SingleBuffer.Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer, offset); }
public static void ToString_Compare_Success() { SocketAddress sa1 = new SocketAddress(AddressFamily.InterNetwork, 64); SocketAddress sa2 = new SocketAddress(AddressFamily.InterNetwork, 64); SocketAddress sa3 = new SocketAddress(AddressFamily.InterNetwork, 48); SocketAddress sa4 = new SocketAddress(AddressFamily.InterNetworkV6, 48); Assert.Equal(sa1.ToString(), sa2.ToString()); Assert.NotEqual(sa1.ToString(), sa3.ToString()); Assert.NotEqual(sa1.ToString(), sa4.ToString()); }
public override SocketAddress Serialize() { var result = new SocketAddress(AddressFamily.Unix, MaxSocketAddressSize); // Ctor has already checked that PathOffset + _encodedPath.Length < MaxSocketAddressSize for (int index = 0; index < _encodedPath.Length; index++) { result[PathOffset + index] = _encodedPath[index]; } result[PathOffset + _encodedPath.Length] = 0; // The path must be ending with \0 return result; }
public override SocketAddress Serialize() { var result = new SocketAddress(AddressFamily.Unix, s_nativeAddressSize); Debug.Assert(_encodedPath.Length + s_nativePathOffset <= result.Size, "Expected path to fit in address"); for (int index = 0; index < _encodedPath.Length; index++) { result[s_nativePathOffset + index] = _encodedPath[index]; } result[s_nativePathOffset + _encodedPath.Length] = 0; // path must be null-terminated return result; }
public static void Equals_Compare_Success() { SocketAddress sa1 = new SocketAddress(AddressFamily.InterNetwork, 64); SocketAddress sa2 = new SocketAddress(AddressFamily.InterNetwork, 64); SocketAddress sa3 = new SocketAddress(AddressFamily.InterNetworkV6, 64); SocketAddress sa4 = new SocketAddress(AddressFamily.InterNetwork, 60000); Assert.False(sa1.Equals(null)); Assert.False(sa1.Equals("")); Assert.Equal(sa1, sa2); Assert.Equal(sa2, sa1); Assert.Equal(sa1.GetHashCode(), sa2.GetHashCode()); Assert.NotEqual(sa1, sa3); Assert.NotEqual(sa1.GetHashCode(), sa3.GetHashCode()); Assert.NotEqual(sa1, sa4); }
private void DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress) { IPEndPoint iPEndPoint = endPointSnapshot as IPEndPoint; if (!Socket.OSSupportsIPv4 && iPEndPoint != null && iPEndPoint.Address.IsIPv4MappedToIPv6) { SocketException ex = new SocketException(SocketError.InvalidArgument); this.UpdateStatusAfterSocketError(ex); throw ex; } SocketError socketError = OSSOCK.bind(this.m_Handle, socketAddress.m_Buffer, socketAddress.m_Size); if (socketError != SocketError.Success) { SocketException ex2 = new SocketException(); this.UpdateStatusAfterSocketError(ex2); throw ex2; } if (this.m_RightEndPoint == null) { this.m_RightEndPoint = endPointSnapshot; } }
public SocketAddress GetSocketAddress(string name, SocketAddress defaultValue) { return((SocketAddress)this.Fields[name]); }
// bytes 2 and 3 store the port, the rest // stores the address public override EndPoint Create(SocketAddress socketAddress) { if (socketAddress == null) throw new ArgumentNullException("socketAddress"); if (socketAddress.Family != AddressFamily) throw new ArgumentException("The IPEndPoint was created using " + AddressFamily + " AddressFamily but SocketAddress contains " + socketAddress.Family + " instead, please use the same type."); SocketAddress sockaddr = socketAddress; int size = sockaddr.Size; AddressFamily family = sockaddr.Family; int port; IPEndPoint ipe = null; switch (family) { case AddressFamily.InterNetwork: if (size < 8) { return (null); } port = (((int)sockaddr[2]) << 8) + (int)sockaddr[3]; long address = (((long)sockaddr[7]) << 24) + (((long)sockaddr[6]) << 16) + (((long)sockaddr[5]) << 8) + (long)sockaddr[4]; ipe = new IPEndPoint(address, port); break; #if NET_1_1 case AddressFamily.InterNetworkV6: if (size < 28) { return(null); } port = (((int)sockaddr[2])<<8) + (int)sockaddr[3]; /// maybe flowid ? /* int unknown = (int)sockaddr[4] + (((int)sockaddr[5])<<8) + (((int)sockaddr[6])<<16) + (((int)sockaddr[7])<<24); */ int scopeId = (int)sockaddr[24] + (((int)sockaddr[25])<<8) + (((int)sockaddr[26])<<16) + (((int)sockaddr[27])<<24); ushort[] addressData = new ushort[8]; for(int i=0; i<8; i++) addressData[i] = (ushort)((sockaddr[8+i*2] << 8) + sockaddr[8+i*2+1]); ipe = new IPEndPoint (new IPAddress(addressData, scopeId), port); break; #endif default: return null; } return (ipe); }
public override SocketAddress Serialize() { SocketAddress a = (SocketAddress) new NlSocketAddress(_pid); return(a); }
public MulticastSocket(SocketAddress arg0) : base(ProxyCtor.I) { Instance.CallConstructor("(Ljava/net/SocketAddress;)V", arg0); }
/// <summary> /// Creates an endpoint from a socket address. /// </summary> /// <param name="socketAddress">The <see cref="SocketAddress"/> to use for the endpoint.</param> /// <returns>An <see cref="EndPoint"/> instance using the specified socket address.</returns> public override EndPoint Create(SocketAddress socketAddress) { if (socketAddress == null) { throw new ArgumentNullException("socketAddress"); } //Dump("Create", socketAddress); //if a Bluetooth SocketAddress if (socketAddress[0] == (int)_addrFamily) { int ibyte; byte[] addrbytes = new byte[6]; for (ibyte = 0; ibyte < 6; ibyte++) { #if NETCF addrbytes[ibyte] = socketAddress[8 + ibyte]; #else addrbytes[ibyte] = socketAddress[2 + ibyte]; #endif } byte[] servicebytes = new byte[16]; for (ibyte = 0; ibyte < 16; ibyte++) { #if NETCF servicebytes[ibyte] = socketAddress[16 + ibyte]; #else if (_isBlueZ) // No SvcClassId field on BlueZ. { break; } servicebytes[ibyte] = socketAddress[10 + ibyte]; #endif } byte[] portbytes = new byte[4]; for (ibyte = 0; ibyte < 4; ibyte++) { #if NETCF portbytes[ibyte] = socketAddress[32 + ibyte]; #else if (_isBlueZ) // One byte Channel field on BlueZ. { portbytes[ibyte] = socketAddress[8 + ibyte]; break; } portbytes[ibyte] = socketAddress[26 + ibyte]; #endif } return(new BluetoothEndPoint(new BluetoothAddress(addrbytes), new Guid(servicebytes), BitConverter.ToInt32(portbytes, 0))); } else { #if DEBUG var len = socketAddress.Size; var arr = new byte[Math.Min(32, len)]; Array_Copy(socketAddress, arr, arr.Length); var txt = BitConverter.ToString(arr); Debug.WriteLine("Non BTH sa passed to BluetoothEndPoint.Create: (len: " + len + ") " + txt); #endif //use generic method return(base.Create(socketAddress)); } }
public Task ConnectAsync(IPEndPoint endPoint) { if (m_connectAsyncOperationState == null) { m_connectAsyncOperationState = new AsyncOperationState(this, CompleteConnectAsync); } if (m_remoteAddress != null) { m_remoteAddress.Dispose(); m_remoteAddress = null; } m_remoteAddress = new SocketAddress(endPoint.Address, endPoint.Port); int bytesSend; SocketError socketError = SocketError.Success; m_connectAsyncTaskCompletionSource = new TaskCompletionSource<bool>(); Task task = m_connectAsyncTaskCompletionSource.Task; m_connectAsyncOperationState.PrepareForCall(); try { if (!m_connectEx(Handle, m_remoteAddress.Buffer, m_remoteAddress.Size, IntPtr.Zero, 0, out bytesSend, m_connectAsyncOperationState.OverlappdAddress)) { socketError = (SocketError)Marshal.GetLastWin32Error(); } } catch (Exception ex) { m_connectAsyncTaskCompletionSource = null; throw; } if (socketError != SocketError.IOPending && socketError != SocketError.Success) { m_connectAsyncTaskCompletionSource.SetException(new SocketException((int)socketError)); m_connectAsyncTaskCompletionSource = null; } return task; }
public virtual EndPoint Create(SocketAddress socketAddress) { }
// Summary: // Creates an endpoint from a socket address. // // Parameters: // socketAddress: // The System.Net.SocketAddress to use for the endpoint. // // Returns: // An System.Net.EndPoint instance using the specified socket address. // // Exceptions: // System.ArgumentException: // The AddressFamily of socketAddress is not equal to the AddressFamily of the // current instance.-or- socketAddress.Size < 8. public override EndPoint Create(SocketAddress socketAddress);
// // SetUnmanagedStructures - // Fills in Overlapped Structures used in an Async Overlapped Winsock call // these calls are outside the runtime and are unmanaged code, so we need // to prepare specific structures and ints that lie in unmanaged memory // since the Overlapped calls can be Async // internal void SetUnmanagedStructures(byte[] buffer, int offset, int size, SocketAddress socketAddress, SocketFlags socketFlags) { m_MessageBuffer = new byte[s_WSAMsgSize]; m_WSABufferArray = new byte[s_WSABufferSize]; //ipv4 or ipv6? IPAddress ipAddress = (socketAddress.Family == AddressFamily.InterNetworkV6 ? socketAddress.GetIPAddress() : null); bool ipv4 = (((Socket)AsyncObject).AddressFamily == AddressFamily.InterNetwork || (ipAddress != null && ipAddress.IsIPv4MappedToIPv6)); // DualMode bool ipv6 = ((Socket)AsyncObject).AddressFamily == AddressFamily.InterNetworkV6; //prepare control buffer if (ipv4) { m_ControlBuffer = new byte[s_ControlDataSize]; } else if (ipv6) { m_ControlBuffer = new byte[s_ControlDataIPv6Size]; } //pin buffers object[] objectsToPin = new object[(m_ControlBuffer != null)?5:4]; objectsToPin[0] = buffer; objectsToPin[1] = m_MessageBuffer; objectsToPin[2] = m_WSABufferArray; //prepare socketaddress buffer m_SocketAddress = socketAddress; m_SocketAddress.CopyAddressSizeIntoBuffer(); objectsToPin[3] = m_SocketAddress.m_Buffer; if (m_ControlBuffer != null) { objectsToPin[4] = m_ControlBuffer; } base.SetUnmanagedStructures(objectsToPin); //prepare data buffer m_WSABuffer = (WSABuffer *)Marshal.UnsafeAddrOfPinnedArrayElement(m_WSABufferArray, 0); m_WSABuffer->Length = size; m_WSABuffer->Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer, offset); //setup structure m_Message = (UnsafeNclNativeMethods.OSSOCK.WSAMsg *)Marshal.UnsafeAddrOfPinnedArrayElement(m_MessageBuffer, 0); m_Message->socketAddress = Marshal.UnsafeAddrOfPinnedArrayElement(m_SocketAddress.m_Buffer, 0); m_Message->addressLength = (uint)m_SocketAddress.Size; m_Message->buffers = Marshal.UnsafeAddrOfPinnedArrayElement(m_WSABufferArray, 0); m_Message->count = 1; if (m_ControlBuffer != null) { m_Message->controlBuffer.Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(m_ControlBuffer, 0); m_Message->controlBuffer.Length = m_ControlBuffer.Length; } m_Message->flags = socketFlags; }
public IpAdapterAnycastAddress(uint Length = default, uint Flags = default, ref ptr <IpAdapterAnycastAddress> Next = default, SocketAddress Address = default) { this.Length = Length; this.Flags = Flags; this.Next = Next; this.Address = Address; }
internal void SetUnmanagedStructures(byte[] buffer, int offset, int size, SocketAddress socketAddress, SocketFlags socketFlags, ref OverlappedCache overlappedCache) { SetupCache(ref overlappedCache); SetUnmanagedStructures(buffer, offset, size, socketAddress, socketFlags); }
// // This method will be called by us when the IO completes synchronously and // by the ThreadPool when the IO completes asynchronously. (only called on WinNT) // internal override object PostCompletion(int numBytes) { SocketError errorCode = (SocketError)ErrorCode; SocketAddress remoteSocketAddress = null; if (errorCode == SocketError.Success) { m_LocalBytesTransferred = numBytes; if (Logging.On) { LogBuffer((long)numBytes); } //get the endpoint remoteSocketAddress = m_ListenSocket.m_RightEndPoint.Serialize(); IntPtr localAddr; int localAddrLength; IntPtr remoteAddr; //set the socket context try { m_ListenSocket.GetAcceptExSockaddrs( Marshal.UnsafeAddrOfPinnedArrayElement(m_Buffer, 0), m_Buffer.Length - (m_AddressBufferLength * 2), m_AddressBufferLength, m_AddressBufferLength, out localAddr, out localAddrLength, out remoteAddr, out remoteSocketAddress.m_Size ); Marshal.Copy(remoteAddr, remoteSocketAddress.m_Buffer, 0, remoteSocketAddress.m_Size); IntPtr handle = m_ListenSocket.SafeHandle.DangerousGetHandle(); errorCode = UnsafeNclNativeMethods.OSSOCK.setsockopt( m_AcceptSocket.SafeHandle, SocketOptionLevel.Socket, SocketOptionName.UpdateAcceptContext, ref handle, Marshal.SizeOf(handle)); if (errorCode == SocketError.SocketError) { errorCode = (SocketError)Marshal.GetLastWin32Error(); } GlobalLog.Print("AcceptOverlappedAsyncResult#" + ValidationHelper.HashString(this) + "::PostCallback() setsockopt handle:" + handle.ToString() + " AcceptSocket:" + ValidationHelper.HashString(m_AcceptSocket) + " itsHandle:" + m_AcceptSocket.SafeHandle.DangerousGetHandle().ToString() + " returns:" + errorCode.ToString()); } catch (ObjectDisposedException) { errorCode = SocketError.OperationAborted; } ErrorCode = (int)errorCode; } if (errorCode == SocketError.Success) { return(m_ListenSocket.UpdateAcceptSocket(m_AcceptSocket, m_ListenSocket.m_RightEndPoint.Create(remoteSocketAddress), false)); } else { return(null); } }
protected override void doBind(SocketAddress localAddress) { this._localAddress = localAddress; networkType = NetworkType.SERVER; connect(); }
} // OverlappedCallback() // // SetUnmanagedStructures - // Fills in Overlapped Structures used in an Async Overlapped Winsock call // these calls are outside the runtime and are unmanaged code, so we need // to prepare specific structures and ints that lie in unmanaged memory // since the Overlapped calls can be Async // internal void SetUnmanagedStructures( byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP, bool pinRemoteEP ) { // // create the event handle // m_OverlappedEvent = new AutoResetEvent(false); // // fill in the overlapped structure with the event handle. // Marshal.WriteIntPtr( m_UnmanagedBlob, Win32.OverlappedhEventOffset, m_OverlappedEvent.Handle ); // // Fill in Buffer Array structure that will be used for our send/recv Buffer // m_WSABuffer = new WSABuffer(); m_GCHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned); m_WSABuffer.Length = size; m_WSABuffer.Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer, offset); // // fill in flags if we use it. // m_Flags = socketFlags; // // if needed fill end point // if (remoteEP != null) { m_SocketAddress = remoteEP.Serialize(); if (pinRemoteEP) { m_GCHandleSocketAddress = GCHandle.Alloc(m_SocketAddress.m_Buffer, GCHandleType.Pinned); m_GCHandleSocketAddressSize = GCHandle.Alloc(m_SocketAddress.m_Size, GCHandleType.Pinned); } } } // SetUnmanagedStructures()
private void Dispose(bool disposing) { if (!m_disposed) { m_disposed = true; m_inOverlapped.Dispose(); m_outOverlapped.Dispose(); UnsafeMethods.CancelIoEx(Handle, IntPtr.Zero); int error = UnsafeMethods.closesocket(Handle); if (error != 0) { error = Marshal.GetLastWin32Error(); } if (m_remoteAddress != null) { m_remoteAddress.Dispose(); m_remoteAddress = null; } if (m_boundAddress != null) { m_boundAddress.Dispose(); m_boundAddress = null; } if (m_sendPinnedBuffer != null) { m_sendPinnedBuffer.Dispose(); m_sendPinnedBuffer = null; } if (m_receivePinnedBuffer != null) { m_receivePinnedBuffer.Dispose(); m_receivePinnedBuffer = null; } if (m_acceptSocketBufferAddress != IntPtr.Zero) { Marshal.FreeHGlobal(m_acceptSocketBufferAddress); } } }
private static unsafe void CopyOutAddress(IntPtr address, ref SocketAddress v4address, ref SocketAddress v6address) { if (address != IntPtr.Zero) { ushort addressFamily = *((ushort *)address); if (addressFamily == (ushort)AddressFamily.InterNetwork) { v6address = null; for (int index = 2; index < IPv4AddressSize; index++) { v4address[index] = ((byte *)address)[index]; } return; } if (addressFamily == (ushort)AddressFamily.InterNetworkV6) { v4address = null; for (int index = 2; index < IPv6AddressSize; index++) { v6address[index] = ((byte *)address)[index]; } return; } } v4address = null; v6address = null; }
// As seen below the structures on Win32 and WinCE are the same, except that // Win32 has 1-byte alignment turned on. Thus on Win32 there are also no // 64-bit differences. // // * Win32 //typedef ULONGLONG BTH_ADDR, *PBTH_ADDR; // //#include <pshpack1.h> //struct _SOCKADDR_BTH //{ // USHORT addressFamily; // Always AF_BTH // BTH_ADDR btAddr; // Bluetooth device address // GUID serviceClassId; // [OPTIONAL] system will query SDP for port // ULONG port; // RFCOMM channel or L2CAP PSM //} // // * WinCE //typedef ULONGLONG bt_addr, *pbt_addr, BT_ADDR, *PBT_ADDR; // //struct _SOCKADDR_BTH //{ // USHORT addressFamily; // bt_addr btAddr; // GUID serviceClassId; // ULONG port; //} // * BlueZ //struct sockaddr_rc //{ // sa_family_t rc_family; // bdaddr_t rc_bdaddr; // uint8_t rc_channel; //}; //typedef struct { // uint8_t b[6]; //} __attribute__((packed)) bdaddr_t; #region Serialize /// <summary> /// Serializes endpoint information into a <see cref="SocketAddress"/> instance. /// </summary> /// <returns>A <see cref="SocketAddress"/> instance containing the socket address for the endpoint.</returns> public override SocketAddress Serialize() { #if NETCF SocketAddress btsa = new SocketAddress(AddressFamily32.Bluetooth, 40); #else int salen = 30; if (_isBlueZ) { salen = 10; } SocketAddress btsa = new SocketAddress(_addrFamily, salen); #endif //copy address type btsa[0] = checked ((byte)_addrFamily); //copy device id if (m_id != null) { byte[] deviceidbytes = m_id.ToByteArray(); for (int idbyte = 0; idbyte < 6; idbyte++) { #if NETCF btsa[idbyte + 8] = deviceidbytes[idbyte]; #else btsa[idbyte + 2] = deviceidbytes[idbyte]; #endif } } //copy service clsid if (m_service != Guid.Empty) { byte[] servicebytes = m_service.ToByteArray(); for (int servicebyte = 0; servicebyte < 16; servicebyte++) { #if NETCF btsa[servicebyte + 16] = servicebytes[servicebyte]; #else if (_isBlueZ) // No SvcClassId field on BlueZ. { break; } btsa[servicebyte + 10] = servicebytes[servicebyte]; #endif } } //copy port byte[] portbytes = BitConverter.GetBytes(m_port); for (int portbyte = 0; portbyte < 4; portbyte++) { #if NETCF btsa[portbyte + 32] = portbytes[portbyte]; #else if (_isBlueZ) // One byte Channel field on BlueZ. { btsa[portbyte + 8] = portbytes[portbyte]; break; } btsa[portbyte + 26] = portbytes[portbyte]; #endif } //Dump("Serialize", btsa); return(btsa); }
public override void Bind(IPEndPoint localEndPoint) { if (m_boundAddress != null) { m_boundAddress.Dispose(); m_boundAddress = null; } m_boundAddress = new SocketAddress(localEndPoint.Address, localEndPoint.Port); SocketError bindResult = (SocketError)UnsafeMethods.bind(Handle, m_boundAddress.Buffer, m_boundAddress.Size); if (bindResult != SocketError.Success) { throw new SocketException((int)bindResult); } }
public override EndPoint Create(SocketAddress socketAddress) { return(new UnixDomainSocketEndPoint(socketAddress)); }
public DatagramPacket(byte[] par1ArrayOfByte, int length, SocketAddress getSocketAddress) { throw new System.NotImplementedException(); }
public override EndPoint Create(SocketAddress socketAddress) => new UnixDomainSocketEndPoint(socketAddress);
public IpAdapterUnicastAddress(uint Length = default, uint Flags = default, ref ptr <IpAdapterUnicastAddress> Next = default, SocketAddress Address = default, int PrefixOrigin = default, int SuffixOrigin = default, int DadState = default, uint ValidLifetime = default, uint PreferredLifetime = default, uint LeaseLifetime = default, byte OnLinkPrefixLength = default) { this.Length = Length; this.Flags = Flags; this.Next = Next; this.Address = Address; this.PrefixOrigin = PrefixOrigin; this.SuffixOrigin = SuffixOrigin; this.DadState = DadState; this.ValidLifetime = ValidLifetime; this.PreferredLifetime = PreferredLifetime; this.LeaseLifetime = LeaseLifetime; this.OnLinkPrefixLength = OnLinkPrefixLength; }
/// <summary> /// Connects this channel's socket. /// /// <para> The channel's socket is configured so that it only receives /// datagrams from, and sends datagrams to, the given remote <i>peer</i> /// address. Once connected, datagrams may not be received from or sent to /// any other address. A datagram socket remains connected until it is /// explicitly disconnected or until it is closed. /// /// </para> /// <para> This method performs exactly the same security checks as the {@link /// java.net.DatagramSocket#connect connect} method of the {@link /// java.net.DatagramSocket} class. That is, if a security manager has been /// installed then this method verifies that its {@link /// java.lang.SecurityManager#checkAccept checkAccept} and {@link /// java.lang.SecurityManager#checkConnect checkConnect} methods permit /// datagrams to be received from and sent to, respectively, the given /// remote address. /// /// </para> /// <para> This method may be invoked at any time. It will not have any effect /// on read or write operations that are already in progress at the moment /// that it is invoked. If this channel's socket is not bound then this method /// will first cause the socket to be bound to an address that is assigned /// automatically, as if invoking the <seealso cref="#bind bind"/> method with a /// parameter of {@code null}. </para> /// </summary> /// <param name="remote"> /// The remote address to which this channel is to be connected /// </param> /// <returns> This datagram channel /// </returns> /// <exception cref="ClosedChannelException"> /// If this channel is closed /// </exception> /// <exception cref="AsynchronousCloseException"> /// If another thread closes this channel /// while the connect operation is in progress /// </exception> /// <exception cref="ClosedByInterruptException"> /// If another thread interrupts the current thread /// while the connect operation is in progress, thereby /// closing the channel and setting the current thread's /// interrupt status /// </exception> /// <exception cref="SecurityException"> /// If a security manager has been installed /// and it does not permit access to the given remote address /// </exception> /// <exception cref="IOException"> /// If some other I/O error occurs </exception> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public abstract DatagramChannel connect(java.net.SocketAddress remote) throws java.io.IOException; public abstract DatagramChannel Connect(SocketAddress remote);
public static void BindCertificate(string ipAddress, int port, byte[] hash) { uint retVal = (uint)NOERROR; // NOERROR = 0 HTTPAPI_VERSION httpApiVersion = new HTTPAPI_VERSION(1, 0); retVal = HttpInitialize(httpApiVersion, HTTP_INITIALIZE_CONFIG, IntPtr.Zero); if ((uint)NOERROR == retVal) { HTTP_SERVICE_CONFIG_SSL_SET configSslSet = new HTTP_SERVICE_CONFIG_SSL_SET(); HTTP_SERVICE_CONFIG_SSL_KEY httpServiceConfigSslKey = new HTTP_SERVICE_CONFIG_SSL_KEY(); HTTP_SERVICE_CONFIG_SSL_PARAM configSslParam = new HTTP_SERVICE_CONFIG_SSL_PARAM(); IPAddress ip = IPAddress.Any; //IPAddress.Parse("0.0.0.0"); IPEndPoint ipEndPoint = new IPEndPoint(ip, port); // serialize the endpoint to a SocketAddress and create an array to hold the values. Pin the array. SocketAddress socketAddress = ipEndPoint.Serialize(); byte[] socketBytes = new byte[socketAddress.Size]; GCHandle handleSocketAddress = GCHandle.Alloc(socketBytes, GCHandleType.Pinned); // Should copy the first 16 bytes (the SocketAddress has a 32 byte buffer, the size will only be 16, //which is what the SOCKADDR accepts for (int i = 0; i < socketAddress.Size; ++i) { socketBytes[i] = socketAddress[i]; } httpServiceConfigSslKey.pIpPort = handleSocketAddress.AddrOfPinnedObject(); GCHandle handleHash = GCHandle.Alloc(hash, GCHandleType.Pinned); configSslParam.AppId = Guid.NewGuid(); configSslParam.DefaultCertCheckMode = 0; configSslParam.DefaultFlags = HTTP_SERVICE_CONFIG_SSL_FLAG_NEGOTIATE_CLIENT_CERT; configSslParam.DefaultRevocationFreshnessTime = 0; configSslParam.DefaultRevocationUrlRetrievalTimeout = 0; configSslParam.pSslCertStoreName = StoreName.My.ToString(); configSslParam.pSslHash = handleHash.AddrOfPinnedObject(); configSslParam.SslHashLength = hash.Length; configSslSet.ParamDesc = configSslParam; configSslSet.KeyDesc = httpServiceConfigSslKey; IntPtr pInputConfigInfo = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(HTTP_SERVICE_CONFIG_SSL_SET))); Marshal.StructureToPtr(configSslSet, pInputConfigInfo, false); retVal = HttpSetServiceConfiguration(IntPtr.Zero, HTTP_SERVICE_CONFIG_ID.HttpServiceConfigSSLCertInfo, pInputConfigInfo, Marshal.SizeOf(configSslSet), IntPtr.Zero); if ((uint)ERROR_ALREADY_EXISTS == retVal) // ERROR_ALREADY_EXISTS = 183 { retVal = HttpDeleteServiceConfiguration(IntPtr.Zero, HTTP_SERVICE_CONFIG_ID.HttpServiceConfigSSLCertInfo, pInputConfigInfo, Marshal.SizeOf(configSslSet), IntPtr.Zero); if ((uint)NOERROR == retVal) { retVal = HttpSetServiceConfiguration(IntPtr.Zero, HTTP_SERVICE_CONFIG_ID.HttpServiceConfigSSLCertInfo, pInputConfigInfo, Marshal.SizeOf(configSslSet), IntPtr.Zero); } } handleSocketAddress.Free(); handleHash.Free(); Marshal.FreeCoTaskMem(pInputConfigInfo); HttpTerminate(HTTP_INITIALIZE_CONFIG, IntPtr.Zero); } if ((uint)NOERROR != retVal) { throw new Win32Exception(Convert.ToInt32(retVal)); } }
public Session GetSession(SocketAddress address) { this._Sessions.TryGetValue(address, out var result); return(result); }
public void leaveGroup(SocketAddress arg0, NetworkInterface arg1) { Instance.CallMethod("leaveGroup", "(Ljava/net/SocketAddress;Ljava/net/NetworkInterface;)V", arg0, arg1); }
public void Remove(Session session, SocketAddress address) { this._Sessions.TryRemove(address, out session); this._SessionsByID.TryRemove(session.SessionID, out var existing); this._SessionList.Remove(session); }
/// <summary>Creates an endpoint from a socket address.</summary> /// <returns>An <see cref="T:System.Net.EndPoint" /> instance using the specified socket address.</returns> /// <param name="socketAddress">The <see cref="T:System.Net.SocketAddress" /> to use for the endpoint. </param> /// <exception cref="T:System.ArgumentException">The AddressFamily of <paramref name="socketAddress" /> is not equal to the AddressFamily of the current instance.-or- <paramref name="socketAddress" />.Size < 8. </exception> /// <PermissionSet> /// <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence" /> /// </PermissionSet> public override EndPoint Create(SocketAddress socketAddress) { if (socketAddress.Family != this.AddressFamily) { throw new ArgumentException("net_InvalidAddressFamily"); } if (socketAddress.Size < 8) { throw new ArgumentException("net_InvalidSocketAddressSize"); } return socketAddress.GetIPEndPoint(); }
// -- Socket-specific operations -- /// <exception cref="AlreadyBoundException"> {@inheritDoc} </exception> /// <exception cref="UnsupportedAddressTypeException"> {@inheritDoc} </exception> /// <exception cref="ClosedChannelException"> {@inheritDoc} </exception> /// <exception cref="IOException"> {@inheritDoc} </exception> /// <exception cref="SecurityException"> /// If a security manager has been installed and its {@link /// SecurityManager#checkListen checkListen} method denies the /// operation /// /// @since 1.7 </exception> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public abstract DatagramChannel bind(java.net.SocketAddress local) throws java.io.IOException; public abstract DatagramChannel Bind(SocketAddress local);
public override SocketAddress Serialize() { SocketAddress sockaddr = null; switch (address.AddressFamily) { case AddressFamily.InterNetwork: // .net produces a 16 byte buffer, even though // only 8 bytes are used. I guess its just a // holdover from struct sockaddr padding. sockaddr = new SocketAddress(AddressFamily.InterNetwork, 16); // bytes 2 and 3 store the port, the rest // stores the address sockaddr[2] = (byte)((port >> 8) & 0xff); sockaddr[3] = (byte)(port & 0xff); long addr = address.InternalIPv4Address; sockaddr[4] = (byte)(addr & 0xff); sockaddr[5] = (byte)((addr >> 8) & 0xff); sockaddr[6] = (byte)((addr >> 16) & 0xff); sockaddr[7] = (byte)((addr >> 24) & 0xff); break; #if NET_1_1 case AddressFamily.InterNetworkV6: sockaddr = new SocketAddress(AddressFamily.InterNetworkV6, 28); sockaddr [2] = (byte) ((port>>8) & 0xff); sockaddr [3] = (byte) (port & 0xff); byte[] addressBytes = address.GetAddressBytes(); for(int i=0; i<16; i++) sockaddr[8+i] = addressBytes[i]; sockaddr [24] = (byte) (address.ScopeId & 0xff); sockaddr [25] = (byte) ((address.ScopeId >> 8) & 0xff); sockaddr [26] = (byte) ((address.ScopeId >> 16) & 0xff); sockaddr [27] = (byte) ((address.ScopeId >> 24) & 0xff); break; #endif } return (sockaddr); }
internal UnixDomainSocketEndPoint(SocketAddress socketAddress) { if (socketAddress == null) { throw new ArgumentNullException("socketAddress"); } if (socketAddress.Family != EndPointAddressFamily || socketAddress.Size < MinSocketAddressSize || socketAddress.Size > MaxSocketAddressSize) { throw new ArgumentException("socketAddress"); } _encodedPath = new byte[socketAddress.Size - PathOffset]; for (int index = 0; index < socketAddress.Size - PathOffset; index++) { _encodedPath[index] = socketAddress[PathOffset + index]; } _path = PathEncoding.GetString(_encodedPath); }
private void Dispose(bool disposing) { if (!m_disposed) { m_disposed = true; if (m_connectAsyncOperationState != null) { m_connectAsyncOperationState.Dispose(); m_connectAsyncOperationState = null; } if (m_sendAsyncOperationState != null) { m_sendAsyncOperationState.Dispose(); m_sendAsyncOperationState = null; } if (m_receiveAsyncOperationState != null) { m_receiveAsyncOperationState.Dispose(); m_receiveAsyncOperationState = null; } if (m_acceptAsyncOperationState != null) { m_acceptAsyncOperationState.Dispose(); m_acceptAsyncOperationState = null; } if (m_remoteAddress != null) { m_remoteAddress.Dispose(); m_remoteAddress = null; } if (m_boundAddress != null) { m_boundAddress.Dispose(); m_boundAddress = null; } UnsafeMethods.closesocket(Handle); } }
public int SendTo_internal(byte[] buffer, int offset, int count, SocketFlags flags, SocketAddress sa, out int error) { return Send_internal(buffer, offset, count, flags, out error); }
public static void Ctor_AddressFamilySize_Success() { SocketAddress sa = new SocketAddress(AddressFamily.InterNetwork, 64); Assert.Equal(AddressFamily.InterNetwork, sa.Family); Assert.Equal(64, sa.Size); }
internal unsafe static IPEndPoint GetLocalEndPoint(byte[] memoryBlob, IntPtr originalAddress) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null); SocketAddress v4address = new SocketAddress(AddressFamily.InterNetwork, IPv4AddressSize); SocketAddress v6address = new SocketAddress(AddressFamily.InterNetworkV6, IPv6AddressSize); fixed (byte* pMemoryBlob = memoryBlob) { HTTP_REQUEST* request = (HTTP_REQUEST*)pMemoryBlob; IntPtr address = request->Address.pLocalAddress != null ? (IntPtr)(pMemoryBlob - (byte*)originalAddress + (byte*)request->Address.pLocalAddress) : IntPtr.Zero; CopyOutAddress(address, ref v4address, ref v6address); } IPEndPoint endpoint = null; if (v4address != null) { endpoint = s_any.Create(v4address) as IPEndPoint; } else if (v6address != null) { endpoint = s_ipv6Any.Create(v6address) as IPEndPoint; } if (NetEventSource.IsEnabled) NetEventSource.Exit(null); return endpoint; }
public UDTSocket Accept() { #if UDT_FULLTCP System.Net.Sockets.Socket newSocket = _tcpSocket.Accept(); UDTSocket newUDTSocket = new UDTSocket(newSocket); // Tracing UDTTrace("UDTSocket[" + _tcpSocket.Handle + ", new:" + newSocket.Handle + "]-Accept:" + newSocket.RemoteEndPoint.ToString()); return(newUDTSocket); #else //---- UDT EndPoint localEP = new IPEndPoint(IPAddress.Parse("0.0.0.0"), 0); SocketAddress address = ((IPEndPoint)localEP).Serialize(); byte[] addressBuffer = new byte[address.Size]; for (int index = 0; index < address.Size; index++) { addressBuffer[index] = address[index]; } //---- Accept int size = 0; int newHandle = API_Accept(_handle, addressBuffer, out size); if (UDT_INVALID_SOCK == newHandle) // UDT::INVALID_SOCK { throw new UDTSocketException(API_GetLastErrorCode(), API_GetLastErrorMessage()); } //---- Get the IP+port of the peer socket (RemoteEndPoint) for (int index = 0; index < address.Size; index++) { address[index] = addressBuffer[index]; } IPEndPoint remoteEndPoint; if (address.Family == AddressFamily.InterNetwork) { remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); } else { remoteEndPoint = new IPEndPoint(IPAddress.IPv6Any, 0); } remoteEndPoint = (IPEndPoint)(remoteEndPoint.Create(address)); //---- Get the IP+port of the socket (LocalEndPoint) size = address.Size; if (UDT_ERROR == API_Getpeername(newHandle, addressBuffer, out size)) { throw new UDTSocketException(API_GetLastErrorCode(), API_GetLastErrorMessage()); } IPEndPoint localEndPoint; if (address.Family == AddressFamily.InterNetwork) { localEndPoint = new IPEndPoint(IPAddress.Any, 0); } else { localEndPoint = new IPEndPoint(IPAddress.IPv6Any, 0); } localEndPoint = (IPEndPoint)(localEndPoint.Create(address)); //---- Tracing UDTTrace("UDTSocket[" + _handle + ", new:" + newHandle + "]-Accept:" + remoteEndPoint.ToString()); //---- Return the new socket return(new UDTSocket(newHandle, _socketType, remoteEndPoint, localEndPoint)); #endif }
/// <summary> /// Sends a datagram via this channel. /// /// <para> If this channel is in non-blocking mode and there is sufficient room /// in the underlying output buffer, or if this channel is in blocking mode /// and sufficient room becomes available, then the remaining bytes in the /// given buffer are transmitted as a single datagram to the given target /// address. /// /// </para> /// <para> The datagram is transferred from the byte buffer as if by a regular /// <seealso cref="WritableByteChannel#write(java.nio.ByteBuffer) write"/> operation. /// /// </para> /// <para> This method performs exactly the same security checks as the {@link /// java.net.DatagramSocket#send send} method of the {@link /// java.net.DatagramSocket} class. That is, if the socket is not connected /// to a specific remote address and a security manager has been installed /// then for each datagram sent this method verifies that the target address /// and port number are permitted by the security manager's {@link /// java.lang.SecurityManager#checkConnect checkConnect} method. The /// overhead of this security check can be avoided by first connecting the /// socket via the <seealso cref="#connect connect"/> method. /// /// </para> /// <para> This method may be invoked at any time. If another thread has /// already initiated a write operation upon this channel, however, then an /// invocation of this method will block until the first operation is /// complete. If this channel's socket is not bound then this method will /// first cause the socket to be bound to an address that is assigned /// automatically, as if by invoking the <seealso cref="#bind bind"/> method with a /// parameter of {@code null}. </para> /// </summary> /// <param name="src"> /// The buffer containing the datagram to be sent /// </param> /// <param name="target"> /// The address to which the datagram is to be sent /// </param> /// <returns> The number of bytes sent, which will be either the number /// of bytes that were remaining in the source buffer when this /// method was invoked or, if this channel is non-blocking, may be /// zero if there was insufficient room for the datagram in the /// underlying output buffer /// </returns> /// <exception cref="ClosedChannelException"> /// If this channel is closed /// </exception> /// <exception cref="AsynchronousCloseException"> /// If another thread closes this channel /// while the read operation is in progress /// </exception> /// <exception cref="ClosedByInterruptException"> /// If another thread interrupts the current thread /// while the read operation is in progress, thereby /// closing the channel and setting the current thread's /// interrupt status /// </exception> /// <exception cref="SecurityException"> /// If a security manager has been installed /// and it does not permit datagrams to be sent /// to the given address /// </exception> /// <exception cref="IOException"> /// If some other I/O error occurs </exception> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public abstract int send(java.nio.ByteBuffer src, java.net.SocketAddress target) throws java.io.IOException; public abstract int Send(ByteBuffer src, SocketAddress target);
/// <summary> /// /// </summary> /// <param name="listenAddresses"></param> public void StartListners(List <ListenAddress> listenAddresses, ref TcpListener listner) { byte[] responseBuffer = new byte[4000]; try { SocketAddress address = new SocketAddress(System.Net.Sockets.AddressFamily.InterNetwork); foreach (ListenAddress socketAddr in listenAddresses) { Common.StackLog.Write2TraceLog("Transport::SendMessage", "Starting Listening on " + socketAddr.IPAddress.ToString() + " with Port: " + socketAddr.Port.ToString()); listner = new TcpListener(IPAddress.Parse(socketAddr.IPAddress), socketAddr.Port); listner.Start(); Common.StackLog.Write2TraceLog("Transport::SendMessage", "Started Listening on " + listner.LocalEndpoint.ToString()); StackLog.Write2TraceLog("StartListners", "Started Listening on " + socketAddr.IPAddress + ":" + socketAddr.Port.ToString()); } while (true) { //try //{ if (listner.Pending()) { Common.StackLog.Write2TraceLog("Transport::StartListener", "Listening for Peer Connections "); Socket socket = listner.AcceptSocket(); Common.StackLog.Write2TraceLog("Transport::StartListener", "Recieved Message From [" + socket + " ]"); //Get the Message Length Array.Clear(responseBuffer, 0, responseBuffer.Length); int rcvdcount = socket.Receive(responseBuffer); byte[] RcvdBytes = new byte[rcvdcount]; Buffer.BlockCopy(responseBuffer, 0, RcvdBytes, 0, rcvdcount); // IPEndPoint remotePeer = socket.RemoteEndPoint as IPEndPoint; RecievedMessageInfo rcvdObject = new RecievedMessageInfo() { data = RcvdBytes, PeerIdentity = new URI("aaa://" + remotePeer.Address + ":" + remotePeer.Port + ";transport=tcp;protocol=diameter") }; DiameterAAAStack.RaisePeerStateChangeEvent(PEER_STATE_EVENT.Rcv_Message, RcvdBytes); Array.Clear(responseBuffer, 0, responseBuffer.Length); } //} //catch (Exception ex) //{ //} } } catch (Exception exp) { //Write Log Here.. Common.StackLog.Write2ErrorLog("Transport::StartListners()", "Error:" + exp.Message + " Stack:" + exp.StackTrace); //Shutdown and end connection //listner.Stop(); //throw exp; } finally { listner.Stop(); } }
private extern static void Connect_internal_real(IntPtr sock, SocketAddress sa, out int error);
public int RecvFrom_internal(byte[] buffer, int offset, int count, SocketFlags flags, ref SocketAddress sockaddr, out int error) { return Receive_internal(buffer, offset, count, flags, out error); }
private static void Connect_internal(IntPtr sock, SocketAddress sa, out int error) { Connect_internal(sock, sa, out error, true); }
private unsafe static void CopyOutAddress(IntPtr address, ref SocketAddress v4address, ref SocketAddress v6address) { if (address != IntPtr.Zero) { ushort addressFamily = *((ushort*)address); if (addressFamily == (ushort)AddressFamily.InterNetwork) { v6address = null; for (int index = 2; index < IPv4AddressSize; index++) { v4address[index] = ((byte*)address)[index]; } return; } if (addressFamily == (ushort)AddressFamily.InterNetworkV6) { v4address = null; for (int index = 2; index < IPv6AddressSize; index++) { v6address[index] = ((byte*)address)[index]; } return; } } v4address = null; v6address = null; }
internal void Connect(EndPoint remoteEP, bool requireSocketPolicy) { SocketAddress serial = null; if (disposed && closed) { throw new ObjectDisposedException(GetType().ToString()); } if (remoteEP == null) { throw new ArgumentNullException("remoteEP"); } IPEndPoint ep = remoteEP as IPEndPoint; if (ep != null) { if (ep.Address.Equals(IPAddress.Any) || ep.Address.Equals(IPAddress.IPv6Any)) { throw new SocketException((int)SocketError.AddressNotAvailable); } } #if NET_2_1 && !MONOTOUCH if (protocol_type != ProtocolType.Tcp) { throw new SocketException((int)SocketError.AccessDenied); } #elif NET_2_0 /* TODO: check this for the 1.1 profile too */ if (islistening) { throw new InvalidOperationException(); } #endif serial = remoteEP.Serialize(); int error = 0; blocking_thread = Thread.CurrentThread; try { Connect_internal(socket, serial, out error, requireSocketPolicy); } catch (ThreadAbortException) { if (disposed) { Thread.ResetAbort(); error = (int)SocketError.Interrupted; } } finally { blocking_thread = null; } if (error != 0) { throw new SocketException(error); } connected = true; #if NET_2_0 isbound = true; #endif seed_endpoint = remoteEP; }
// Summary: // Creates an System.Net.EndPoint instance from a System.Net.SocketAddress instance. // // Parameters: // socketAddress: // The socket address that serves as the endpoint for a connection. // // Returns: // A new System.Net.EndPoint instance that is initialized from the specified // System.Net.SocketAddress instance. // // Exceptions: // System.NotImplementedException: // Any attempt is made to access the method when the method is not overridden // in a descendant class. public virtual EndPoint Create(SocketAddress socketAddress);
//function will return connection id for this connect request ///PopData with eventtype ConnectEvent will be signal that this slot is successfully connected ///exceptionConnectionId defines connectionId with exception tuning params (returned from AddConfigException) ///exceptionConnectionId==0 means default connection ///return connectionId if success 0 otherwise public static int ConnectEndPoint(int hostId, EndPoint endPoint, int exceptionConnectionId, out byte error) { error = 0; // This class is implemented in the Xbox One Plugins API const string kXboxOneEndPointClass = "UnityEngine.XboxOne.XboxOneEndPoint"; // XboxOneEndPoint validation constants byte[] XboxOneEndPointPacketSignature = new byte[] { 0x5f, 0x24, 0x13, 0xf6 }; // Our magic signature (it's a constant we randomly-generated) const int kXboxOneEndPointPacketSize = 2 + 4 + 8; // sizeof(AddressFamily) + XboxOneEndPointPacketSignature.Length + 8 bytes(64bit pointer) const int kSDASocketStorageOffset = 6; // sizeof(AddressFamily) + XboxOneEndPointPacketSignature.Length const int kSockAddrStorageLength = 128; // sizeof(sockaddr_storage) if (endPoint == null) // We require an XboxOneEndPoint to continue { throw new NullReferenceException("Null EndPoint provided"); } if ((endPoint.GetType().FullName != kXboxOneEndPointClass) && (endPoint.GetType().FullName != "UnityEngine.PS4.SceEndPoint")) { throw new ArgumentException("Endpoint of type XboxOneEndPoint or SceEndPoint required"); } if (endPoint.GetType().FullName == kXboxOneEndPointClass) { EndPoint xboxOneEndPoint = endPoint; if (xboxOneEndPoint.AddressFamily != System.Net.Sockets.AddressFamily.InterNetworkV6) { throw new ArgumentException("XboxOneEndPoint has an invalid family"); } // Okay, now serialise the endpoint, and convert it to a normal byte[] buffer SocketAddress src = xboxOneEndPoint.Serialize(); if (src.Size != kXboxOneEndPointPacketSize) // The specified socket is not an XboxEndPoint (wrong size!) { throw new ArgumentException("XboxOneEndPoint has an invalid size"); } if (src[0] != 0 || src[1] != 0) { throw new ArgumentException("XboxOneEndPoint has an invalid family signature"); } if (src[2] != XboxOneEndPointPacketSignature[0] || src[3] != XboxOneEndPointPacketSignature[1] || src[4] != XboxOneEndPointPacketSignature[2] || src[5] != XboxOneEndPointPacketSignature[3]) { throw new ArgumentException("XboxOneEndPoint has an invalid signature"); } // Okay, now extract the pointer to the SOCKET_STORAGE address to a byte array byte[] dst = new byte[8]; // 8 bytes (64bit pointer) for (int i = 0; i < dst.Length; ++i) { dst[i] = src[kSDASocketStorageOffset + i]; } byte[] SocketAddressFamily = new byte[2]; // short Buffer.BlockCopy(dst, 0, SocketAddressFamily, 0, SocketAddressFamily.Length); System.Net.Sockets.AddressFamily a = (System.Net.Sockets.AddressFamily)((((int)SocketAddressFamily[1]) << 8) + (int)SocketAddressFamily[0]); if (a != System.Net.Sockets.AddressFamily.InterNetworkV6) { throw new ArgumentException("XboxOneEndPoint has corrupt or invalid SOCKET_STORAGE pointer"); } return(Internal_ConnectEndPoint(hostId, dst, kSockAddrStorageLength, exceptionConnectionId, out error)); } else { const int kSceEndPointPacketSize = 16; const int kSceSockAddrSize = 16; const int kSCE_NET_AF_INET = 2; // from <socket.h> // Sony platforms network code SocketAddress src = endPoint.Serialize(); if (src.Size != kSceEndPointPacketSize) // The specified socket is not an XboxEndPoint (wrong size!) { throw new ArgumentException("EndPoint has an invalid size"); } if (src[0] != src.Size) { throw new ArgumentException("EndPoint has an invalid size value"); } if (src[1] != kSCE_NET_AF_INET) { throw new ArgumentException("EndPoint has an invalid family value"); } byte[] dst = new byte[kSceSockAddrSize]; for (int i = 0; i < dst.Length; ++i) { dst[i] = src[i]; } int result = Internal_ConnectEndPoint(hostId, dst, kSceSockAddrSize, exceptionConnectionId, out error); return(result); } }
public override void Connect(IPEndPoint endPoint) { if (m_remoteAddress != null) { m_remoteAddress.Dispose(); m_remoteAddress = null; } m_remoteAddress = new SocketAddress(endPoint.Address, endPoint.Port); if (m_boundAddress == null) { if (endPoint.AddressFamily == AddressFamily.InterNetwork) Bind(new IPEndPoint(IPAddress.Any, 0)); else Bind(new IPEndPoint(IPAddress.IPv6Any, 0)); } int bytesSend; m_outOverlapped.StartOperation(OperationType.Connect); if (m_connectEx(Handle, m_remoteAddress.Buffer, m_remoteAddress.Size, IntPtr.Zero, 0, out bytesSend, m_outOverlapped.Address)) { CompletionPort.PostCompletionStatus(m_outOverlapped.Address); } else { SocketError socketError = (SocketError)Marshal.GetLastWin32Error(); if (socketError != SocketError.IOPending) { throw new SocketException((int)socketError); } } }
// The getPage method gets the server's home page content by // recreating the server's endpoint from the original serialized endpoint. // Then it creates a new socket and connects it to the endpoint. private static string getPage(string server, SocketAddress socketAddress) { //Set up variables and string to write to the server. Encoding ASCII = Encoding.ASCII; string Get = "GET / HTTP/1.1\r\nHost: " + server + "\r\nConnection: Close\r\n\r\n"; Byte[] ByteGet = ASCII.GetBytes(Get); Byte[] RecvBytes = new Byte[256]; String strRetPage = null; Socket socket = null; //<Snippet5> // Recreate the connection endpoint from the serialized information. IPEndPoint endpoint = new IPEndPoint(0, 0); IPEndPoint clonedIPEndPoint = (IPEndPoint)endpoint.Create(socketAddress); Console.WriteLine("clonedIPEndPoint: " + clonedIPEndPoint.ToString()); //</Snippet5> Console.WriteLine("Press any key to continue."); Console.ReadLine(); try { // Create a socket object to establish a connection with the server. socket = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); // Connect to the cloned end point. socket.Connect(clonedIPEndPoint); } catch (SocketException e) { Console.WriteLine("Source : " + e.Source); Console.WriteLine("Message : " + e.Message); } catch (Exception e) { Console.WriteLine("Source : " + e.Source); Console.WriteLine("Message : " + e.Message); } if (socket == null) { return("Connection to cloned endpoint failed"); } // Send request to the server. socket.Send(ByteGet, ByteGet.Length, 0); // Receive the server home page content. Int32 bytes = socket.Receive(RecvBytes, RecvBytes.Length, 0); // Read the first 256 bytes. strRetPage = "Default HTML page on " + server + ":\r\n"; strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes); while (bytes > 0) { bytes = socket.Receive(RecvBytes, RecvBytes.Length, 0); strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes); } socket.Close(); return(strRetPage); }
public static int ConnectEndPoint(int hostId, EndPoint endPoint, int exceptionConnectionId, out byte error) { error = 0; byte[] array = new byte[] { 95, 36, 19, 246 }; bool flag = endPoint == null; if (flag) { throw new NullReferenceException("Null EndPoint provided"); } bool flag2 = endPoint.GetType().FullName != "UnityEngine.XboxOne.XboxOneEndPoint" && endPoint.GetType().FullName != "UnityEngine.PS4.SceEndPoint" && endPoint.GetType().FullName != "UnityEngine.PSVita.SceEndPoint"; if (flag2) { throw new ArgumentException("Endpoint of type XboxOneEndPoint or SceEndPoint required"); } bool flag3 = endPoint.GetType().FullName == "UnityEngine.XboxOne.XboxOneEndPoint"; int result; if (flag3) { bool flag4 = endPoint.AddressFamily != AddressFamily.InterNetworkV6; if (flag4) { throw new ArgumentException("XboxOneEndPoint has an invalid family"); } SocketAddress socketAddress = endPoint.Serialize(); bool flag5 = socketAddress.Size != 14; if (flag5) { throw new ArgumentException("XboxOneEndPoint has an invalid size"); } bool flag6 = socketAddress[0] != 0 || socketAddress[1] > 0; if (flag6) { throw new ArgumentException("XboxOneEndPoint has an invalid family signature"); } bool flag7 = socketAddress[2] != array[0] || socketAddress[3] != array[1] || socketAddress[4] != array[2] || socketAddress[5] != array[3]; if (flag7) { throw new ArgumentException("XboxOneEndPoint has an invalid signature"); } byte[] array2 = new byte[8]; for (int i = 0; i < array2.Length; i++) { array2[i] = socketAddress[6 + i]; } IntPtr intPtr = new IntPtr(BitConverter.ToInt64(array2, 0)); bool flag8 = intPtr == IntPtr.Zero; if (flag8) { throw new ArgumentException("XboxOneEndPoint has an invalid SOCKET_STORAGE pointer"); } byte[] array3 = new byte[2]; Marshal.Copy(intPtr, array3, 0, array3.Length); AddressFamily addressFamily = (AddressFamily)(((int)array3[1] << 8) + (int)array3[0]); bool flag9 = addressFamily != AddressFamily.InterNetworkV6; if (flag9) { throw new ArgumentException("XboxOneEndPoint has corrupt or invalid SOCKET_STORAGE pointer"); } result = NetworkTransport.Internal_ConnectEndPoint(hostId, array2, 128, exceptionConnectionId, out error); } else { SocketAddress socketAddress2 = endPoint.Serialize(); bool flag10 = socketAddress2.Size != 16; if (flag10) { throw new ArgumentException("EndPoint has an invalid size"); } bool flag11 = (int)socketAddress2[0] != socketAddress2.Size; if (flag11) { throw new ArgumentException("EndPoint has an invalid size value"); } bool flag12 = socketAddress2[1] != 2; if (flag12) { throw new ArgumentException("EndPoint has an invalid family value"); } byte[] array4 = new byte[16]; for (int j = 0; j < array4.Length; j++) { array4[j] = socketAddress2[j]; } int num = NetworkTransport.Internal_ConnectEndPoint(hostId, array4, 16, exceptionConnectionId, out error); result = num; } return(result); }
/// <inheritdoc/> public override EndPoint Create(SocketAddress socketAddress) => new UdsEndPoint(socketAddress);