public static bool TryConnect(string ipString, int port)
 {
     if (!Initialized)
     {
         var wsaData = new WSAData();
         if (WSAStartup(0x0202, out wsaData) != 0) return false;
         m_Buffer = typeof(SocketAddress).GetField("m_Buffer", (BindingFlags.Instance | BindingFlags.NonPublic));
         Initialized = true;
     }
     IPAddress address;
     if (!IPAddress.TryParse(ipString, out address)) return false;
     if (!((port >= 0) && (port <= 0xffff))) return false;
     var remoteEP = new IPEndPoint(address, port);
     SocketAddress socketAddress = remoteEP.Serialize();
     IntPtr m_Handle = WSASocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, IntPtr.Zero, 0, 1 /*overlapped*/);
     if (m_Handle == new IntPtr(-1)) return false;
     new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, remoteEP.Address.ToString(), remoteEP.Port).Demand();
     var buf = (byte[])m_Buffer.GetValue(socketAddress);
     bool result = (WSAConnect(m_Handle, buf, socketAddress.Size, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero) == 0);
     closesocket(m_Handle);
     return result;
 }
Пример #2
0
        /// <summary>
        /// Gets protocol number by name (tcp/udp/icmp etc')
        /// </summary>
        /// <param name="name">protocol name</param>
        /// <returns>protocol number</returns>
        public static int GetProtoByName(string name)
        {
            // Vorbedingung
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }

            //check first in protocols file
            if (File.Exists(etcFileHelper.GetFullFilename(etcFileHelper.ProtocolFilename)))
            {
                var protocols = etcFileHelper.ReadProtocols(etcFileHelper.GetFullFilename(etcFileHelper.ProtocolFilename));
                var protocol = protocols.FirstOrDefault(i => i.Name.ToLower() == name.ToLower());
                if (protocol != null)
                    return protocol.ProtocolNumber;
            }

            //failed, use API.

            int result = 0;

            int intResult = -1;
            if (int.TryParse(name, out intResult))
            {
                result = System.Convert.ToInt32(name, CultureInfo.InvariantCulture);
            }
            else
            {
                WSAData dummy = new WSAData();
                int sccuessful = NativeMethods.WSAStartup(0x0202, ref dummy);
                if (sccuessful != 0)
                {
                    throw CreateWSAException();
                }

                IntPtr intPtr = NativeMethods.GetProtocolByName(name);

                try
                {
                    if (intPtr != IntPtr.Zero)
                    {
                        ProtoEnt protoent = (ProtoEnt)Marshal.PtrToStructure(intPtr, typeof(ProtoEnt));
                        result = System.Convert.ToInt32(protoent.p_proto);
                    }
                    else
                    {
                        throw CreateWSAException();
                    }
                }
                finally
                {
                    sccuessful = NativeMethods.WSACleanup();
                    if (sccuessful != 0)
                    {
                        throw CreateWSAException();
                    }
                }
            }

            return result;
        }
Пример #3
0
 public static extern Int32 WSAStartup(short wVersionRequested, ref WSAData wsaData);
Пример #4
0
        /// <summary>
        /// Gets service port number by name/protocol
        /// </summary>
        /// <remarks>http://stackoverflow.com/questions/3457977/convert-service-name-to-port</remarks>
        /// <param name="name">name of service</param>
        /// <param name="protocol">protocol the service is using</param>
        /// <returns>port number</returns>
        public static int GetServByName(string name,string protocol)
        {
            // Vorbedingung
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }

            //check first in services file
            if (File.Exists(etcFileHelper.GetFullFilename(etcFileHelper.ServicesFilename)))
            {
                var services = etcFileHelper.ReadServices(etcFileHelper.GetFullFilename(etcFileHelper.ServicesFilename));
                var service = services.FirstOrDefault(i => i.Name.ToLower() == name.ToLower() && i.Protocol.ToLower() == protocol.ToLower());
                if (service != null)
                    return service.Port;
            }

            //we failed to find an appropriate service in the file, use the api instead.

            int result = 0;

            int intResult = -1;
            if (int.TryParse(name, out intResult))
            {
                result = System.Convert.ToInt32(name, CultureInfo.InvariantCulture);
            }
            else
            {
                WSAData dummy = new WSAData();
                int sccuessful = NativeMethods.WSAStartup(0x0202, ref dummy);
                if (sccuessful != 0)
                {
                    throw CreateWSAException();
                }

                IntPtr intPtr = NativeMethods.GetServByName(name, protocol);

                try
                {
                    if (intPtr != IntPtr.Zero)
                    {
                        Servent servent = (Servent)Marshal.PtrToStructure(intPtr, typeof(Servent));
                        result = System.Convert.ToInt32(IPAddress.NetworkToHostOrder(servent.s_port));
                    }
                    else
                    {
                        throw CreateWSAException();
                    }
                }
                finally
                {
                    sccuessful = NativeMethods.WSACleanup();
                    if (sccuessful != 0)
                    {
                        throw CreateWSAException();
                    }
                }
            }

            return result;
        }
Пример #5
0
        internal static void InitializeSockets() {
            if (!s_Initialized) {
                lock(InternalSyncObject){
                    if (!s_Initialized) {

                        WSAData wsaData = new WSAData();

                        SocketError errorCode =
                            UnsafeNclNativeMethods.OSSOCK.WSAStartup(
                                (short)0x0202, // we need 2.2
                                out wsaData );

                        if (errorCode!=SocketError.Success) {
                            //
                            // failed to initialize, throw
                            //
                            // WSAStartup does not set LastWin32Error
                            throw new SocketException(errorCode);
                        }

#if !FEATURE_PAL
                        //
                        // we're on WinNT4 or greater, we could use CompletionPort if we
                        // wanted. check if the user has disabled this functionality in
                        // the registry, otherwise use CompletionPort.
                        //

#if DEBUG
                        BooleanSwitch disableCompletionPortSwitch = new BooleanSwitch("DisableNetCompletionPort", "System.Net disabling of Completion Port");

                        //
                        // the following will be true if they've disabled the completionPort
                        //
                        UseOverlappedIO = disableCompletionPortSwitch.Enabled;
#endif
                        
                        bool   ipv4      = true; 
                        bool   ipv6      = true; 

                        SafeCloseSocket.InnerSafeCloseSocket socketV4 = 
                                                             UnsafeNclNativeMethods.OSSOCK.WSASocket(
                                                                    AddressFamily.InterNetwork, 
                                                                    SocketType.Dgram, 
                                                                    ProtocolType.IP, 
                                                                    IntPtr.Zero, 
                                                                    0, 
                                                                    (SocketConstructorFlags) 0);
                        if (socketV4.IsInvalid) {
                            errorCode = (SocketError) Marshal.GetLastWin32Error();
                            if (errorCode == SocketError.AddressFamilyNotSupported)
                                ipv4 = false;
                        }

                        socketV4.Close();

                        SafeCloseSocket.InnerSafeCloseSocket socketV6 = 
                                                             UnsafeNclNativeMethods.OSSOCK.WSASocket(
                                                                    AddressFamily.InterNetworkV6, 
                                                                    SocketType.Dgram, 
                                                                    ProtocolType.IP, 
                                                                    IntPtr.Zero, 
                                                                    0, 
                                                                    (SocketConstructorFlags) 0);
                        if (socketV6.IsInvalid) {
                            errorCode = (SocketError) Marshal.GetLastWin32Error();
                            if (errorCode == SocketError.AddressFamilyNotSupported)
                                ipv6 = false;
                        }

                        socketV6.Close();

                        // <



#if COMNET_DISABLEIPV6
                        //
                        // Turn off IPv6 support
                        //
                        ipv6 = false;
#else
                        //
                        // Now read the switch as the final check: by checking the current value for IPv6
                        // support we may be able to avoid a painful configuration file read.
                        //
                        if (ipv6) {
                            s_OSSupportsIPv6 = true;
                            ipv6 = SettingsSectionInternal.Section.Ipv6Enabled;
                        }
#endif

                    //
                    // Update final state
                    //
                        s_SupportsIPv4 = ipv4;
                        s_SupportsIPv6 = ipv6;

#else //!FEATURE_PAL

                        s_SupportsIPv4 = true;
                        s_SupportsIPv6 = false;

#endif //!FEATURE_PAL

                        // Cache some settings locally.

#if !FEATURE_PAL // perfcounter
                        s_PerfCountersEnabled = NetworkingPerfCounters.Instance.Enabled;
#endif
                        s_Initialized = true;
                    }
                }
            }
        }
Пример #6
0
 public static extern int WSAStartup(
     UInt16 wVersionRequested,
     WSAData wsaData);
Пример #7
0
 private static extern int WSAStartup([In] short wVersionRequested, out WSAData lpWSAData);
Пример #8
0
        //
        // Overlapped constants.
        //

        internal static bool InitializeSockets() {
            if (m_Initialized) {
                return true;
            }

            WSAData wsaData = new WSAData();

            int errorCode =
                UnsafeNclNativeMethods.OSSOCK.WSAStartup(
                    (short)0x0202, // we need 2.2
                    out wsaData );

            if (errorCode!=SocketErrors.Success) {
                //
                // failed to initialize, throw
                //
                throw new SocketException();
            }

            //
            // at this point we need to figure out if we're going to use CompletionPort,
            // which are supported only on WinNT, or classic Win32 OverlappedIO, so
            //

            return true;
        }
Пример #9
0
 static extern Int32 WSAStartup(Int16 wVersionRequested, out WSAData wsaData);
Пример #10
0
 internal static void InitializeSockets()
 {
     if (Socket.s_Initialized)
     return;
       lock (Socket.InternalSyncObject)
       {
     if (Socket.s_Initialized)
       return;
     WSAData local_0 = new WSAData();
     SocketError local_1 = UnsafeNclNativeMethods.OSSOCK.WSAStartup((short) 514, out local_0);
     if (local_1 != SocketError.Success)
       throw new SocketException(local_1);
     bool local_2 = true;
     bool local_3 = true;
     SafeCloseSocket.InnerSafeCloseSocket local_4 = UnsafeNclNativeMethods.OSSOCK.WSASocket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.IP, IntPtr.Zero, 0U, (SocketConstructorFlags) 0);
     if (local_4.IsInvalid && Marshal.GetLastWin32Error() == 10047)
       local_2 = false;
     local_4.Close();
     SafeCloseSocket.InnerSafeCloseSocket local_5 = UnsafeNclNativeMethods.OSSOCK.WSASocket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.IP, IntPtr.Zero, 0U, (SocketConstructorFlags) 0);
     if (local_5.IsInvalid && Marshal.GetLastWin32Error() == 10047)
       local_3 = false;
     local_5.Close();
     if (local_3)
     {
       Socket.s_OSSupportsIPv6 = true;
       local_3 = SettingsSectionInternal.Section.Ipv6Enabled;
     }
     Socket.s_SupportsIPv4 = local_2;
     Socket.s_SupportsIPv6 = local_3;
     Socket.s_PerfCountersEnabled = NetworkingPerfCounters.Instance.Enabled;
     Socket.s_Initialized = true;
       }
 }
Пример #11
0
        internal static void InitializeSockets()
        {
            if (!s_Initialized) {
                lock(InternalSyncObject){
                    if (!s_Initialized) {

                        WSAData wsaData = new WSAData();

                        SocketError errorCode =
                            UnsafeNclNativeMethods.OSSOCK.WSAStartup(
                                (short)0x0202, // we need 2.2
                                out wsaData );

                        if (errorCode!=SocketError.Success) {
                            //
                            // failed to initialize, throw
                            //
                            throw new SocketException();
                        }

                        s_SupportsIPv4 = true;
                        s_SupportsIPv6 = false;

                        s_Initialized = true;
                    }
                }
            }
        }
 internal static extern SocketError WSAStartup(
     [In] short wVersionRequested,
     [Out] out WSAData lpWSAData
     );
 internal static extern SocketError WSAStartup([In] short wVersionRequested, out WSAData lpWSAData);
 internal static void InitializeSockets()
 {
     if (!s_Initialized)
     {
         lock (InternalSyncObject)
         {
             if (!s_Initialized)
             {
                 WSAData lpWSAData = new WSAData();
                 if (UnsafeNclNativeMethods.OSSOCK.WSAStartup(0x202, out lpWSAData) != SocketError.Success)
                 {
                     throw new SocketException();
                 }
                 if (!ComNetOS.IsWinNt)
                 {
                     UseOverlappedIO = true;
                 }
                 bool flag = true;
                 bool flag2 = true;
                 SafeCloseSocket.InnerSafeCloseSocket socket = UnsafeNclNativeMethods.OSSOCK.WSASocket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.IP, IntPtr.Zero, 0, 0);
                 if (socket.IsInvalid && (Marshal.GetLastWin32Error() == 0x273f))
                 {
                     flag = false;
                 }
                 socket.Close();
                 SafeCloseSocket.InnerSafeCloseSocket socket2 = UnsafeNclNativeMethods.OSSOCK.WSASocket(System.Net.Sockets.AddressFamily.InterNetworkV6, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.IP, IntPtr.Zero, 0, 0);
                 if (socket2.IsInvalid && (Marshal.GetLastWin32Error() == 0x273f))
                 {
                     flag2 = false;
                 }
                 socket2.Close();
                 flag2 = flag2 && ComNetOS.IsPostWin2K;
                 if (flag2)
                 {
                     s_OSSupportsIPv6 = true;
                     flag2 = SettingsSectionInternal.Section.Ipv6Enabled;
                 }
                 s_SupportsIPv4 = flag;
                 s_SupportsIPv6 = flag2;
                 s_PerfCountersEnabled = NetworkingPerfCounters.Instance.Enabled;
                 s_Initialized = true;
             }
         }
     }
 }