/// <summary> /// Serializes an IPAddress. /// </summary> private static IntPtr ToIntPtr(IPAddress address, ushort port) { IntPtr pAddress = IntPtr.Zero; if (address == null) { return(pAddress); } if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { SOCKADDR_IN inet = new SOCKADDR_IN(); inet.family = AF_INET; inet.addr = address.GetAddressBytes(); inet.port = (ushort)(((port & 0xFF00) >> 8) | ((port & 0x00FF) << 8)); pAddress = Marshal.AllocHGlobal(Marshal.SizeOf <SOCKADDR_IN>()); Marshal.StructureToPtr(inet, pAddress, false); } else if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) { SOCKADDR_IN6 inet = new SOCKADDR_IN6(); inet.family = AF_INET6; inet.addr = address.GetAddressBytes(); inet.port = (ushort)(((port & 0xFF00) >> 8) | ((port & 0x00FF) << 8)); inet.scopeID = (int)address.ScopeId; pAddress = Marshal.AllocHGlobal(Marshal.SizeOf <SOCKADDR_IN6>()); Marshal.StructureToPtr(inet, pAddress, false); } return(pAddress); }
public static bool IsSocketInherited(IntPtr socketHandle, Process parentProcess) { IntPtr parentSocketHandle = IntPtr.Zero; SOCKADDR_IN sockaddrTargetProcess = new SOCKADDR_IN(); SOCKADDR_IN sockaddrParentProcess = new SOCKADDR_IN(); int sockaddrTargetProcessLen = Marshal.SizeOf(sockaddrTargetProcess); int sockaddrParentProcessLen = Marshal.SizeOf(sockaddrParentProcess); parentSocketHandle = GetSocketTargetProcess(parentProcess); if (parentSocketHandle == IntPtr.Zero) { return(false); } if (getpeername(socketHandle, ref sockaddrTargetProcess, ref sockaddrTargetProcessLen) != 0) { Console.WriteLine("getpeername sockaddrTargetProcess failed with wsalasterror " + WSAGetLastError().ToString()); CloseHandle(parentSocketHandle); return(false); } if (getpeername(parentSocketHandle, ref sockaddrParentProcess, ref sockaddrParentProcessLen) != 0) { Console.WriteLine("getpeername sockaddrParentProcess failed with wsalasterror " + WSAGetLastError().ToString()); CloseHandle(parentSocketHandle); return(false); } if (sockaddrTargetProcess.sin_addr == sockaddrParentProcess.sin_addr && sockaddrTargetProcess.sin_port == sockaddrParentProcess.sin_port) { CloseHandle(parentSocketHandle); return(true); } CloseHandle(parentSocketHandle); return(false); }
public SOCKADDR(byte[] addr, ushort port = 0, uint scopeId = 0) : base(addr.Length == 4 ? Marshal.SizeOf(typeof(SOCKADDR_IN)) : Marshal.SizeOf(typeof(SOCKADDR_IN6))) { if (addr.Length == 4) { var in4 = new SOCKADDR_IN(new IN_ADDR(addr), port); Marshal.StructureToPtr(in4, handle, false); } else if (addr.Length == 16) { var in6 = new SOCKADDR_IN6(addr, scopeId, port); Marshal.StructureToPtr(in6, handle, false); } else { throw new ArgumentOutOfRangeException(nameof(addr)); } }
private static IntPtr connectRemote(string remoteIp, int remotePort) { int port = 0; int error = 0; string host = remoteIp; try { port = Convert.ToInt32(remotePort); } catch { throw new ConPtyShellException("Specified port is invalid: " + remotePort.ToString()); } WSAData data; if (WSAStartup(2 << 8 | 2, out data) != 0) { error = WSAGetLastError(); throw new ConPtyShellException(String.Format("WSAStartup failed with error code: {0}", error)); } IntPtr socket = IntPtr.Zero; socket = WSASocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP, IntPtr.Zero, 0, WSA_FLAG_OVERLAPPED); SOCKADDR_IN sockinfo = new SOCKADDR_IN(); sockinfo.sin_family = (short)2; sockinfo.sin_addr = inet_addr(host); sockinfo.sin_port = (short)htons((ushort)port); if (connect(socket, ref sockinfo, Marshal.SizeOf(sockinfo)) != 0) { error = WSAGetLastError(); throw new ConPtyShellException(String.Format("WSAConnect failed with error code: {0}", error)); } return(socket); }
/// <summary> /// Serializes an IPAddress. /// </summary> private static IntPtr ToIntPtr(IPAddress address, ushort port) { IntPtr pAddress = IntPtr.Zero; if (address == null) { return pAddress; } if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { SOCKADDR_IN inet = new SOCKADDR_IN(); inet.family = AF_INET; inet.addr = address.GetAddressBytes(); inet.port = (ushort)(((port & 0xFF00) >> 8) | ((port & 0x00FF) << 8)); pAddress = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SOCKADDR_IN))); Marshal.StructureToPtr(inet, pAddress, false); } else if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) { SOCKADDR_IN6 inet = new SOCKADDR_IN6(); inet.family = AF_INET6; inet.addr = address.GetAddressBytes(); inet.port = (ushort)(((port & 0xFF00) >> 8) | ((port & 0x00FF) << 8)); inet.scopeID = (int)address.ScopeId; pAddress = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SOCKADDR_IN6))); Marshal.StructureToPtr(inet, pAddress, false); } return pAddress; }
/// <summary> /// Fetches the current SSL certificate configuration. /// </summary> public static List <SslCertificateBinding> GetSslCertificateBindings() { List <SslCertificateBinding> bindings = new List <SslCertificateBinding>(); // initialize library. HttpError error = NativeMethods.HttpInitialize( new HTTPAPI_VERSION(1, 0), HttpInitFlag.HTTP_INITIALIZE_CONFIG, IntPtr.Zero); if (error != HttpError.NO_ERROR) { throw ServiceResultException.Create( StatusCodes.BadUnexpectedError, "Could not initialize HTTP library.\r\nError={0}", error); } // set up the iterator. HTTP_SERVICE_CONFIG_SSL_QUERY query = new HTTP_SERVICE_CONFIG_SSL_QUERY(); query.QueryDesc = HTTP_SERVICE_CONFIG_QUERY_TYPE.HttpServiceConfigQueryNext; query.KeyDesc.pIpPort = IntPtr.Zero; IntPtr pInput = Marshal.AllocHGlobal(Marshal.SizeOf <HTTP_SERVICE_CONFIG_SSL_QUERY>()); NativeMethods.ZeroMemory(pInput, Marshal.SizeOf <HTTP_SERVICE_CONFIG_SSL_QUERY>()); IntPtr pOutput = IntPtr.Zero; try { // loop through each record. for (query.dwToken = 0; error == HttpError.NO_ERROR; query.dwToken++) { // get the size of buffer to allocate. Marshal.StructureToPtr(query, pInput, true); int requiredBufferLength = 0; error = NativeMethods.HttpQueryServiceConfiguration( IntPtr.Zero, HTTP_SERVICE_CONFIG_ID.HttpServiceConfigSSLCertInfo, pInput, Marshal.SizeOf <HTTP_SERVICE_CONFIG_SSL_QUERY>(), pOutput, requiredBufferLength, out requiredBufferLength, IntPtr.Zero); if (error == HttpError.ERROR_NO_MORE_ITEMS) { break; } if (error != HttpError.ERROR_INSUFFICIENT_BUFFER) { throw ServiceResultException.Create( StatusCodes.BadUnexpectedError, "Could not read SSL configuration information.\r\nError={0}", error); } // allocate the buffer. pOutput = Marshal.AllocHGlobal(requiredBufferLength); NativeMethods.ZeroMemory(pOutput, requiredBufferLength); // get the actual data. error = NativeMethods.HttpQueryServiceConfiguration( IntPtr.Zero, HTTP_SERVICE_CONFIG_ID.HttpServiceConfigSSLCertInfo, pInput, Marshal.SizeOf <HTTP_SERVICE_CONFIG_SSL_QUERY>(), pOutput, requiredBufferLength, out requiredBufferLength, IntPtr.Zero); if (error != HttpError.NO_ERROR) { throw ServiceResultException.Create( StatusCodes.BadUnexpectedError, "Could not read SSL configuration information.\r\nError={0}", error); } HTTP_SERVICE_CONFIG_SSL_SET sslSet = (HTTP_SERVICE_CONFIG_SSL_SET)Marshal.PtrToStructure <HTTP_SERVICE_CONFIG_SSL_SET>(pOutput); short family = Marshal.ReadInt16(sslSet.KeyDesc.pIpPort); SslCertificateBinding binding = new SslCertificateBinding(); if (family == AF_INET) { SOCKADDR_IN inet = (SOCKADDR_IN)Marshal.PtrToStructure <SOCKADDR_IN>(sslSet.KeyDesc.pIpPort); binding.IPAddress = new IPAddress(inet.addr); binding.Port = inet.port; } if (family == AF_INET6) { SOCKADDR_IN6 inet = (SOCKADDR_IN6)Marshal.PtrToStructure <SOCKADDR_IN6>(sslSet.KeyDesc.pIpPort); binding.IPAddress = new IPAddress(inet.addr, inet.scopeID); binding.Port = inet.port; } binding.Port = (ushort)(((binding.Port & 0xFF00) >> 8) | ((binding.Port & 0x00FF) << 8)); byte[] bytes = new byte[sslSet.ParamDesc.SslHashLength]; Marshal.Copy(sslSet.ParamDesc.pSslHash, bytes, 0, bytes.Length); binding.Thumbprint = Utils.ToHexString(bytes); binding.ApplicationId = sslSet.ParamDesc.AppId; binding.StoreName = sslSet.ParamDesc.pSslCertStoreName; binding.DefaultCertCheckMode = sslSet.ParamDesc.DefaultCertCheckMode; binding.DefaultRevocationFreshnessTime = sslSet.ParamDesc.DefaultRevocationFreshnessTime; binding.DefaultRevocationUrlRetrievalTimeout = sslSet.ParamDesc.DefaultRevocationUrlRetrievalTimeout; binding.DefaultSslCtlIdentifier = sslSet.ParamDesc.pDefaultSslCtlIdentifier; binding.DefaultSslCtlStoreName = sslSet.ParamDesc.pDefaultSslCtlStoreName; binding.DefaultFlags = sslSet.ParamDesc.DefaultFlags; bindings.Add(binding); Marshal.FreeHGlobal(pOutput); pOutput = IntPtr.Zero; } } finally { if (pInput != IntPtr.Zero) { Marshal.DestroyStructure <HTTP_SERVICE_CONFIG_SSL_QUERY>(pInput); Marshal.FreeHGlobal(pInput); } if (pOutput != IntPtr.Zero) { Marshal.FreeHGlobal(pOutput); } NativeMethods.HttpTerminate(HttpInitFlag.HTTP_INITIALIZE_CONFIG, IntPtr.Zero); } return(bindings); }
public bool Equals(SOCKADDR_IN other) => si_family == ADDRESS_FAMILY.AF_INET && Ipv4.Equals(other);
/// <summary> /// XP - IPv4 only /// </summary> /// <param name="destination"></param> /// <param name="prefix"></param> /// <param name="gateway"></param> /// <param name="interfaceIndex"></param> public static void DeleteRoute(string destination, string prefix, string gateway, string interfaceIndex) { if (Environment.OSVersion.Version.CompareTo(new Version("6.0")) < 0) { MIB_IPFORWARDROW route = new MIB_IPFORWARDROW(); route.dwForwardDest = BitConverter.ToUInt32(IPAddress.Parse(destination).GetAddressBytes().ToArray(), 0); route.dwForwardMask = BitConverter.ToUInt32(IPAddress.Parse(prefix).GetAddressBytes().ToArray(), 0); route.dwForwardNextHop = BitConverter.ToUInt32(IPAddress.Parse(gateway).GetAddressBytes().ToArray(), 0); route.dwForwardIfIndex = uint.Parse(interfaceIndex); route.dwForwardProto = NL_ROUTE_PROTOCOL.MIB_IPPROTO_NETMGMT; IntPtr pRoute = Marshal.AllocHGlobal(Marshal.SizeOf(route)); Marshal.StructureToPtr(route, pRoute, false); DeleteIpForwardEntry(pRoute); Marshal.DestroyStructure(pRoute, typeof(MIB_IPFORWARDROW)); Marshal.FreeHGlobal(pRoute); } else { MIB_IPFORWARD_ROW2 route2 = new MIB_IPFORWARD_ROW2(); uint prefixLength = 0; if (IPAddress.Parse(destination).AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { SOCKADDR_IN address = new SOCKADDR_IN(); address.sin_family = FAMILY.AF_INET; address.sin_addr.S_addr = BitConverter.ToUInt32(IPAddress.Parse(destination).GetAddressBytes().ToArray(), 0); route2.DestinationPrefix.Prefix.Ipv4 = address; uint ipMask = BitConverter.ToUInt32(IPAddress.Parse(prefix).GetAddressBytes().Reverse().ToArray(), 0); while (ipMask > 0) { prefixLength++; ipMask <<= 1; } address.sin_addr.S_addr = BitConverter.ToUInt32(IPAddress.Parse(gateway).GetAddressBytes().ToArray(), 0); route2.NextHop.Ipv4 = address; } else { SOCKADDR_IN6 address = new SOCKADDR_IN6(); address.sin6_family = FAMILY.AF_INET6; address.sin6_addr.Byte = IPAddress.Parse(destination).GetAddressBytes().ToArray(); route2.DestinationPrefix.Prefix.Ipv6 = address; prefixLength = uint.Parse(prefix); address.sin6_addr.Byte = IPAddress.Parse(gateway).GetAddressBytes().ToArray(); route2.NextHop.Ipv6 = address; } route2.DestinationPrefix.PrefixLength = prefixLength; route2.InterfaceIndex = uint.Parse(interfaceIndex); IntPtr pRoute = Marshal.AllocHGlobal(Marshal.SizeOf(route2)); Marshal.StructureToPtr(route2, pRoute, false); DeleteIpForwardEntry2(pRoute); Marshal.DestroyStructure(pRoute, typeof(MIB_IPFORWARD_ROW2)); Marshal.FreeHGlobal(pRoute); } }
/// <summary>Initializes a new instance of the <see cref="SOCKADDR_IN6"/> struct from a <see cref="SOCKADDR_IN"/>.</summary> /// <param name="v4">The IPv4 socket address.</param> public SOCKADDR_IN6(SOCKADDR_IN v4) : this(new IN6_ADDR(v4.sin_addr), 0, v4.sin_port) { }
public static extern int DnsValidateServerStatus( SOCKADDR_IN server, [MarshalAs(UnmanagedType.LPWStr)] string queryName, ref uint serverStatus );
private static extern int connect(IntPtr s, ref SOCKADDR_IN addr, int addrsize);
private static extern int getpeername(IntPtr s, ref SOCKADDR_IN name, ref int namelen);
private static Boolean TryConfigureBindAndStartListen(SOCKET serverSocket, TcpServerSettings settings) { // try disable use of the Nagle algorithm if requested if (settings.UseNagleAlgorithm == false) { var optionValue = -1; unsafe { var tryDisableNagle = WinsockInterop.setsockopt(serverSocket, WinsockInterop.IPPROTO_TCP, WinsockInterop.TCP_NODELAY, (Byte *)&optionValue, sizeof(Int32)); // check if attempt has succeed if (tryDisableNagle == WinsockInterop.SOCKET_ERROR) { return(false); } } } // try enable faster operations on the loopback if requested if (settings.UseFastLoopback) { unsafe { UInt32 optionValue = 1; UInt32 dwBytes; var tryEnableFastLoopbackResult = WinsockInterop.WSAIoctl(serverSocket, WinsockInterop.SIO_LOOPBACK_FAST_PATH, &optionValue, sizeof(UInt32), null, 0, out dwBytes, IntPtr.Zero, IntPtr.Zero); // check if attempt has succeed if (tryEnableFastLoopbackResult == WinsockInterop.SOCKET_ERROR) { return(false); } } } // try bind { // compose address var address = new IN_ADDR { s_addr = 0 }; // compose socket address var socketAddress = new SOCKADDR_IN { sin_family = WinsockInterop.AF_INET, sin_port = WinsockInterop.htons(settings.Port), sin_addr = address }; // try associate address with socket var tryBindResult = WinsockInterop.bind(serverSocket, ref socketAddress, SOCKADDR_IN.Size); if (tryBindResult == WinsockInterop.SOCKET_ERROR) { return(false); } } // try start listen { var tryStartListen = WinsockInterop.listen(serverSocket, settings.AcceptBacklogLength); if (tryStartListen == WinsockInterop.SOCKET_ERROR) { return(false); } } return(true); }