ACR_ServerCommunicator.SocketIo.OnLowLevelReceive C# (CSharp) Method

OnLowLevelReceive() private static method

Called when nwn2server receives a message from UDP. The routine decides if the message should be internally handled, and, if so, packages it up for managed handling. Otherwise, the original nwn2server handling is continued.
private static OnLowLevelReceive ( IntPtr s, IntPtr buf, int len, int flags, IntPtr from, IntPtr fromlen ) : int
s System.IntPtr Supplies the socket that received data.
buf System.IntPtr Supplies the buffer pointer (length of len). ///
len int Supplies the count of bytes received.
flags int Supplies the original recvfrom flags.
from System.IntPtr Supplies the sender address. This is known to /// be at least the size of a sockaddr_in.
fromlen System.IntPtr Supplies the length of the sender address. ///
return int
        private static int OnLowLevelReceive(IntPtr s, IntPtr buf, int len, int flags, IntPtr from, IntPtr fromlen)
        {
            if (RecvfromSocket == IntPtr.Zero)
                RecvfromSocket = s;

            if (LocalDataPort == 0)
            {
                try
                {
                    sockaddr_in LocalSocketName;
                    int NameLen = Marshal.SizeOf(typeof(sockaddr_in));

                    if (getsockname(RecvfromSocket, out LocalSocketName, ref NameLen) == 0)
                    {
                        //
                        // Use loopback (disable deprecation warning) if we have no
                        // bound address.
                        //

#pragma warning disable 618
                        if (LocalSocketName.sin_addr == 0)
                            LocalSocketName.sin_addr = (uint)(ulong)IPAddress.Loopback.Address;
#pragma warning restore 618

                        LocalDataPort = (int)IPAddress.NetworkToHostOrder((short)LocalSocketName.sin_port);
                        LocalListenerAddress = (int)LocalSocketName.sin_addr;
                    }
                }
                catch
                {

                }
            }

            if (len < 5 || Marshal.ReadInt32(fromlen) < Marshal.SizeOf(typeof(sockaddr_in)))
                return len;

            if (Marshal.ReadInt32(buf) != ALFAProtocolMagic)
                return len;

            try
            {
                switch ((PROTOCOL_ID)Marshal.ReadByte(buf + 4))
                {

                    case PROTOCOL_ID.PROTOCOL_DATAGRAM:
                        sockaddr_in Sender = (sockaddr_in)Marshal.PtrToStructure(from, typeof(sockaddr_in));

                        if (Sender.sin_family != AF_INET)
                            return len;

                        OnDatagramReceive(buf, len, Sender);
                        return 0;

                    default:
                        return 0;

                }
            }
            catch
            {
                return 0;
            }
        }