Exemple #1
0
        static void Main(string[] args)
        {
            while (true)
            {
                Task.Run(() =>
                {
                    while (true)
                    {
                        try
                        {
                            Socket ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);

                            ClientSocket.Blocking = false;
                            ClientSocket.Bind(new IPEndPoint(IPAddress.Parse("10.101.194.195 "), 2000));
                            try
                            {
                                ClientSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, 1);
                                byte[] IN = new byte[4] {
                                    1, 0, 0, 0
                                };
                                byte[] OUT = new byte[4];

                                //低级别操作模式,接受所有的数据包,这一步是关键,必须把socket设成raw和IP   Level才可用SIO_RCVALL
                                int ret_code = ClientSocket.IOControl(IOControlCode.ReceiveAll, IN, OUT);
                                ret_code     = OUT[0] + OUT[1] + OUT[2] + OUT[3]; //把4个8位字节合成一个32位整数
                                                                                  //if(ret_code   !=   0)   ret_value   =   false;
                            }
                            catch (SocketException)
                            {
                                //ret_value   =   false;
                                MessageBox.Show("sdfsf ");
                            }

                            // IPEndPoint   ff   =   new   IPEndPoint(IPAddress.Parse( "10.101.64.174 "),2000);
                            // EndPoint   rr   =   (EndPoint)ff;
                            // ClientSocket.Bind(rr);
                            //填充tcp_header
                            ip_header iph   = new ip_header();
                            tcp_header tcph = new tcp_header();
                            iph.Version     = 4;
                            iph.comput_internet_header_length = false;
                            iph.type_service = 0;
                            iph.comput_internet_header_length = false;
                            iph.Identification          = 149;
                            iph.Flags                   = 2;
                            iph.FragmentOffset          = 0;
                            iph.TTL                     = 255;
                            iph.Protocol                = 6;
                            iph.comput_header_checksum  = true;
                            iph.HeaderChecksum          = 25895;
                            iph.str_Destination_address = "64.233.161.99 ";
                            iph.str_Source_address      = "10.101.64.174 ";

                            tcph.SourcePort           = 2000;
                            tcph.DestinationPort      = 80;
                            tcph.SequenceNumber       = 2758944060;
                            tcph.AcknowledgmentNumber = 101;
                            tcph.Reserved             = 0;
                            tcph.URG           = false;
                            tcph.ACK           = false;
                            tcph.PSH           = false;
                            tcph.RST           = false;
                            tcph.SYN           = true;
                            tcph.FIN           = false;
                            tcph.Window        = 19200;
                            tcph.Checksum      = 54523;
                            tcph.UrgentPointer = 0;

                            uint aa = BitConverter.ToUInt32(IPAddress.Parse("10.101.64.174 ").GetAddressBytes(), 0);
                            uint bb = BitConverter.ToUInt32(IPAddress.Parse(Dns.Resolve("www.google.com ").AddressList[0].ToString()).GetAddressBytes(), 0);

                            byte[] tt = tcph.encode(aa, bb);

                            iph.Data  = tt;
                            byte[] qq = iph.encode();
                            // IPEndPoint   yy   =   new   IPEndPoint(IPAddress.Parse( "64.233.161.99 "),80);
                            //
                            // EndPoint   ww   =   (EndPoint)yy;
                            IPEndPoint yy = new IPEndPoint(IPAddress.Parse("64.233.161.99 "), 80);

                            EndPoint ww = (EndPoint)yy;
                            //ClientSocket.Blocking   =   false;
                            //ClientSocket.Bind(
                            ClientSocket.SendTo(qq, ww);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.Data);
                        }
                    }
                });
            }
            Task.WaitAll();
        }
Exemple #2
0
        public void SetSignAlarmInfoList(List <MED_VITAL_SIGN> vitalSignList)
        {
            IPHostEntry ipHost = Dns.Resolve(Dns.GetHostName());
            IPAddress   ipAddr = ipHost.AddressList[0];
            List <MED_VITALSIGN_ALARM> vitalSignAlarmList = null;
            //List<MED_PAT_MONITOR_DATA_DICT> monitorDict = CommDictService.GetPatMonitorDict();
            //List<MED_RESCUE_MESSAGE_LOG> messageList = RescueService.GetRescueMessageList();
            //if (messageList != null && messageList.Count > 0)
            //    messageList = messageList.Where(p => p.MESSAGE_TYPE == 1 && p.PATIENT_ID == ExtendApplicationContext.Current.PatientContextExtend.PatientID &&
            //        p.VISIT_ID == ExtendApplicationContext.Current.PatientContextExtend.VisitID && p.OPER_ID == ExtendApplicationContext.Current.PatientContextExtend.OperID).ToList();
            //decimal value = 0;
            //if (vitalSignList != null && vitalSignList.Count > 0 && monitorDict != null && monitorDict.Count > 0)
            //{
            //    DateTime lastTime = vitalSignList[vitalSignList.Count - 1].TIME_POINT;
            //    vitalSignList = vitalSignList.Where(p => p.TIME_POINT == lastTime).ToList();
            //    foreach (MED_VITAL_SIGN signRow in vitalSignList)
            //    {
            //        MED_RESCUE_MESSAGE_LOG messageRow = messageList.Where(p => p.GROUP_ID == signRow.ITEM_CODE && p.SEND_TIME == signRow.TIME_POINT).FirstOrDefault();
            //        if (messageRow == null)
            //        {
            //            foreach (MED_PAT_MONITOR_DATA_DICT row in monitorDict)
            //            {
            //                if (signRow.ITEM_CODE == row.DB_DATA_NAME)
            //                {
            //                    if (!string.IsNullOrEmpty(signRow.ITEM_VALUE))
            //                    {
            //                        value = decimal.Parse(signRow.ITEM_VALUE);
            //                        MED_RESCUE_MESSAGE_LOG logRow = new MED_RESCUE_MESSAGE_LOG();
            //                        string message = "";
            //                        if ((row.LOW_SIGNS_VALUES.HasValue && value > 0 && value < row.LOW_SIGNS_VALUES))
            //                        {
            //                            logRow.MESSAGE_TYPE = 1;
            //                            logRow.SEND_CLIENT_IP = ipAddr.ToString();
            //                            logRow.SEND_USER_ID = "体征预警";
            //                            logRow.GROUP_ID = signRow.ITEM_CODE;
            //                            logRow.EXPERT_ID = ExtendApplicationContext.Current.LoginUser.USER_JOB_ID;
            //                            logRow.PATIENT_ID = ExtendApplicationContext.Current.PatientContextExtend.PatientID;
            //                            logRow.VISIT_ID = ExtendApplicationContext.Current.PatientContextExtend.VisitID;
            //                            logRow.OPER_ID = ExtendApplicationContext.Current.PatientContextExtend.OperID;
            //                            logRow.MESSAGE = signRow.TIME_POINT.ToString("yyyy-MM-dd hh:mm:ss") + " " + signRow.ITEM_NAME + " 值为:" + signRow.ITEM_VALUE + " 低于预设的警戒值 : " + row.LOW_SIGNS_VALUES;
            //                            logRow.SEND_TIME = signRow.TIME_POINT;
            //                            logRow.SEND_CONFIRM = 0;
            //                            logRow.RECEIVE_CONFIRM = 0;
            //                            messageList.Add(logRow);
            //                        }
            //                        if (row.HIGH_SIGNS_VALUES.HasValue && value > 0 && value > row.HIGH_SIGNS_VALUES)
            //                        {
            //                            logRow.MESSAGE_TYPE = 1;
            //                            logRow.SEND_CLIENT_IP = ipAddr.ToString();
            //                            logRow.SEND_USER_ID = "体征预警";
            //                            logRow.GROUP_ID = signRow.ITEM_CODE;
            //                            logRow.EXPERT_ID = ExtendApplicationContext.Current.LoginUser.USER_JOB_ID;
            //                            logRow.PATIENT_ID = ExtendApplicationContext.Current.PatientContextExtend.PatientID;
            //                            logRow.VISIT_ID = ExtendApplicationContext.Current.PatientContextExtend.VisitID;
            //                            logRow.OPER_ID = ExtendApplicationContext.Current.PatientContextExtend.OperID;
            //                            logRow.MESSAGE = signRow.TIME_POINT.ToString("yyyy-MM-dd hh:mm:ss") + " " + signRow.ITEM_NAME + " 值为:" + signRow.ITEM_VALUE + " 高于预设的警戒值 : " + row.HIGH_SIGNS_VALUES;
            //                            logRow.SEND_TIME = signRow.TIME_POINT;
            //                            logRow.SEND_CONFIRM = 0;
            //                            logRow.RECEIVE_CONFIRM = 0;
            //                            messageList.Add(logRow);
            //                        }

            //                    }
            //                }
            //            }
            //        }

            //    }
            //    RescueService.SaveRescueMessage(messageList);
            //}
        }
Exemple #3
0
        public void StartListening()
        {
            //waiting start
            Main_Manager.ip_changing = true;

            // Data buffer for incoming data.
            byte[] bytes = new Byte[1024];

            // Establish the local endpoint for the socket.
            // Dns.GetHostName returns the name of the
            // host running the application.
            IPHostEntry ipHostInfo    = Dns.Resolve(Dns.GetHostName());
            IPAddress   ipAddress     = ipHostInfo.AddressList[0];
            IPEndPoint  localEndPoint = new IPEndPoint(ipAddress, 2222);

            // Create a TCP/IP socket.
            listener = new Socket(AddressFamily.InterNetwork,
                                  SocketType.Stream, ProtocolType.Tcp);



            context.log(" [아이피 변경] : 아이피 변경을 시작합니다");
            context.log(" [아이피 변경] : 모바일에서 다음의 아이피와 포트를 입력해주세요");
            context.log(" [아이피 변경] : " + localEndPoint.Address.ToString() + " port  " + localEndPoint.Port.ToString());


            // Bind the socket to the local endpoint and
            // listen for incoming connections.
            try
            {
                listener.Bind(localEndPoint);

                listener.Listen(10);



                // Start listening for connections.


                context.log(" [아이피 변경] : 연결을 기다리는 중입니다");


                // Program is suspended while waiting for an incoming connection.
                Socket handler = listener.Accept();
                data = null;

                //// An incoming connection needs to be processed.
                //while (true)
                //{
                //    bytes = new byte[1024];
                //    int bytesRec = handler.Receive(bytes);
                //    data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                //    if (data.IndexOf("<EOF>") > -1)
                //    {
                //        break;
                //    }
                //}

                //// Show the data on the console.
                //Console.WriteLine("Text received : {0}", data);

                // Echo the data back to the client.
                byte[] msg = Encoding.ASCII.GetBytes("change");

                handler.Send(msg);
                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                context.log(e.ToString());
            }

            context.log(" [아이피 변경] : 아이피 변경 명령을 내리는 중입니다...");

            while (true)
            {
                try
                {
                    context.log(" [아이피 변경] : 현재 아이피 : " + GetComputer_InternetIP() + "\n");

                    break;
                }
                catch (Exception ex)
                {
                    context.log(" [아이피 변경] : 연결 실패 다시 시도중...");
                    Thread.Sleep(1500);
                }
            }

            while (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
                Thread.Sleep(500);
                context.log(" [아이피 변경] : 대기");
            }

            //mysql 재연결

            //conn.mysql_refresh();

            context.log(" [아이피 변경] : 연결 성공!");


            //시작 버튼 활성화 시도

            context.start_button_valid("login");
            //waiting done
            Main_Manager.ip_changing = false;
        }
Exemple #4
0
        private void bConnect_Click(object sender, System.EventArgs e)
        {
            IPHostEntry iphe;
            IPAddress   locIpaddr;

            m_log.Add("Checking local address...");

            if (lbLocalIP.Text.Length == 0)
            {
                MessageBox.Show("Local IP address required", "Error",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation,
                                MessageBoxDefaultButton.Button1);
                return;
            }
            try {
                iphe = Dns.Resolve(lbLocalIP.Text);
            }
            catch (Exception ex) {
                MessageBox.Show("Invalid Local IP Address: " + ex.Message,
                                "Error",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation,
                                MessageBoxDefaultButton.Button1);
                return;
            }
            locIpaddr = iphe.AddressList[0];
            m_log.Add("\tdone.");
            m_log.Add("Checking local port...");

            if (tbPort.Text.Length == 0)
            {
                MessageBox.Show("Local UDP Port Required", "Error",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation,
                                MessageBoxDefaultButton.Button1);
                return;
            }
            try {
                m_LocalPort = UInt16.Parse(tbPort.Text);
            }
            catch (Exception ex) {
                MessageBox.Show("0 < local port < 65536: " + ex.Message,
                                "Error",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation,
                                MessageBoxDefaultButton.Button1);
                return;
            }
            m_mipLocalEndPoint = new MEETIPEndPoint(locIpaddr, m_LocalPort);

            m_log.Add("\tdone.");

            IPAddress remIpaddr;

            m_log.Add("Checking remote address...");

            if (cbRemoteIP.Text.Length == 0)
            {
                MessageBox.Show("Remote IP address required", "Error",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation,
                                MessageBoxDefaultButton.Button1);
                return;
            }
            try {
                iphe = Dns.Resolve(cbRemoteIP.Text);
            }
            catch (Exception ex) {
                MessageBox.Show("Invalid Remote IP Address: " + ex.Message,
                                "Error",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation,
                                MessageBoxDefaultButton.Button1);
                return;
            }
            remIpaddr = iphe.AddressList[0];
            m_log.Add("\tdone.");
            m_log.Add("Checking remote port...");

            if (tbRemotePort.Text.Length == 0)
            {
                MessageBox.Show("UDP Remote Port Required", "Error",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation,
                                MessageBoxDefaultButton.Button1);
                return;
            }
            try {
                m_RemotePort = UInt16.Parse(tbRemotePort.Text);
            }
            catch (Exception ex) {
                MessageBox.Show("0 < remote port < 65536: " + ex.Message,
                                "Error",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation,
                                MessageBoxDefaultButton.Button1);
                return;
            }
            m_mipRemoteEndPoint = new MEETIPEndPoint(remIpaddr, m_RemotePort);
            m_log.Add("\tdone.");
        }
Exemple #5
0
        // 收件
        private bool receiveMail()
        {
            string host = txtHost.Text; // POP3郵件伺服器之主機名稱或IP位址
            string port = txtPort.Text; // POP3郵件伺服器之通訊埠,預設通訊埠為110
            string user = txtUser.Text; // 登錄帳號
            string pass = txtPass.Text; // 密碼

            string data = "";

            byte[] bytes;
            int    bytesReceived;
            string strResponse;

            lstLog.Items.Clear();

            try
            {
                lstLog.Items.Add("C: Trying to connect to host " + host + ", port: " + port);

                IPAddress pop3ServerIP = Dns.Resolve(host).AddressList[0];

                // 使用伺服端之IPEndPoint
                IPEndPoint pop3ServerHost = new IPEndPoint(pop3ServerIP, Int32.Parse(port));

                pop3Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                // 建立用戶端與郵件伺服器連線
                pop3Socket.Connect(pop3ServerHost);

                // 判斷是否無法連線至郵件伺服器
                if (!pop3Socket.Connected)
                {
                    lstLog.Items.Add("Unable to connect to " + host + ":" + port);
                    return(false);
                }

                // 判斷郵件伺服器是否回傳 +OK hello from popgate 訊息?
                if (!POP3Response())
                {
                    return(false);
                }

                // 使用者認證
                // USER (登錄帳號)
                data = "USER " + user;

                // 傳送郵件訊息
                if (!POP3Request(data))
                {
                    return(false);
                }

                // 判斷郵件伺服器是否回應 +OK password required 訊息?
                if (!POP3Response())
                {
                    return(false);
                }

                // PASS
                data = "PASS " + pass;

                // 傳送郵件訊息
                if (!POP3Request(data))
                {
                    return(false);
                }

                // 判斷郵件伺服器是否回應 +OK maildrop ready, .. messages 訊息?
                if (!POP3Response())
                {
                    return(false);
                }

                // STAT
                data = "STAT";

                // 傳送郵件訊息
                if (!POP3Request(data))
                {
                    return(false);
                }

                // 設定接收資料緩衝區
                bytes = new Byte[1024];

                // 郵件伺服器回傳 +OK <# of Mail> <Mail Size>
                bytesReceived = pop3Socket.Receive(bytes, 0, bytes.Length, SocketFlags.None);

                strResponse = Encoding.ASCII.GetString(bytes, 0, bytesReceived);

                lstLog.Items.Add("S: " + strResponse.ToString());

                // 判斷郵件伺服器是否回傳 +OK <# of Mail> <Mail Size>
                if (!strResponse.StartsWith("+OK"))
                {
                    MessageBox.Show(strResponse.ToString(), "POP3 Error", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
                    return(false);
                }

                // +OK <#> <Size>
                string[] strTemp = strResponse.Split(" ".ToCharArray());

                totalMail = Int32.Parse(strTemp[1].Trim().ToString());
                mailSize  = Int32.Parse(strTemp[2].Trim().ToString());

                return(true);
            }
            catch (Exception ex)
            {
                lstLog.Items.Add(ex.ToString());

                // 同時暫停用戶端的傳送和接收作業
                pop3Socket.Shutdown(SocketShutdown.Both);
                // 關閉用戶端Socket
                pop3Socket.Close();

                return(false);
            }
        }
Exemple #6
0
        public void start()
        {
            this._open = true;
            //get our port
            try
            {
                this._port = Constants.getIntConst("ServerPort");
            }
            catch (ConstantNotFoundException cnf)
            {
                Logger.getLogger().log(Logger.EXCEPTION_PRIORITY, "ServerPort constant not found.  Reverting to port 5500", cnf);
                this._port = 5500;
            }

            //open our listener
            try
            {
                this._serverSocket          = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                this._serverSocket.Blocking = true;

                IPHostEntry IPHost     = Dns.Resolve(Dns.GetHostName());
                string[]    aliases    = IPHost.Aliases;
                IPAddress[] addr       = IPHost.AddressList;
                IPEndPoint  ipepServer = new IPEndPoint(addr[0], 5500);
                this._serverSocket.Bind(ipepServer);
                this._serverSocket.Listen(-1);
            }
            catch (Exception e)
            {
                Logger.getLogger().log(Logger.FATAL_PRIORITY, "Server socket cannot be opened.", e);
            }

            //as a connection comes in create a new client and add it to the server hashtable
            try
            {
                Logger.getLogger().log(Logger.DEBUG_PRIORITY, "We are about to start listening.");
                while (this._open)
                {
                    Socket client = this._serverSocket.Accept();
                    //client.Blocking = 0;
                    Logger.getLogger().log(Logger.DEBUG_PRIORITY, "Incoming Client");

                    if (client.Connected)
                    {
                        //as a client comes in we grab it and send it to a new thread for handling
                        ClientHandler incomingClient = new ClientHandler(client, this._server);
                        new Thread(new ThreadStart(incomingClient.start)).Start();
                        Logger.getLogger().log(Logger.INFO_PRIORITY, "New client has been recieved and spanwed off to thread.");
                    }
                    else
                    {
                        Logger.getLogger().log(Logger.INFO_PRIORITY, "Client Lost.");
                    }

                    Logger.getLogger().log(Logger.INFO_PRIORITY, "Return to listening for clients.");
                }
            }
            catch (Exception e)
            {
                Logger.getLogger().log(Logger.INFO_PRIORITY, "No Longer Listening for incoming clients.", e);
            }

            Logger.getLogger().log(Logger.INFO_PRIORITY, "Listener is exiting. Restart is possible.");
        }
Exemple #7
0
        static void Main(string[] args)
        {
            // se crean las variables a utilizar, incluyendo el nombre del servidor, puerto de conexión
            // y sus respectivos buffers
            String servidor = "localhost";

            byte[] buferTx = new byte[512];
            byte[] buferRx = new byte[512];
            int    puerto  = 8082;
            //se crea el socket del cliente
            Socket socketCliente = null;

            try
            {
                //creamos el socket para el cliente empleando el constructor en el que se especifica
                // el esquema de dirección, el tipo del socket, y el tipo de protocolo.
                socketCliente = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                // procedemos a realizar la solicitud de conexión en la cual el cliente
                //busca conectarse al servidor mediante el nombre del dominio y el puerto.
                socketCliente.Connect(new IPEndPoint(Dns.Resolve(servidor).AddressList[0], puerto));
            }
            catch (Exception e)
            {   //se muestra el mensaje de la excepción y termina el proceso
                Console.WriteLine(e.Message);
                Environment.Exit(-1);
            }

            // se crean las variables con el propósito de llevar el control de bytes enviados
            //y recibidos.
            int totalBytesEnviados  = 0;
            int totalBytesRecibidos = 0;


            // ### Ejecuta las aplicaciones y comprueba su funcionamiento.Cambia la cadena que se
            // ### envía, de igual manera cambia el tiempo que el cliente se va a dormir y observa
            // ### si el servidor rompe la conexión.
            // ### Si  se requiere ver el funcionamiento original del programa comente las siguientes
            // ### lineas hasta encontrar la linea //### y descomente las lineas //#



            //se codifica en bytes una cadena para poder ser enviada, y se guarda en el buffer de tx
            //# buferTx = Encoding.ASCII.GetBytes("ESTOY ENVIANDO TODO ESTOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO!");

            buferTx = Encoding.ASCII.GetBytes("AHOOOOOOOOOORA ESTOY ENVIANDO  TODO ESTOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO Y MAAAAAAAASSSSSSSSSS!!! XD XD XD XD hasta coooooooommmmmmmmleeeetar 600 Caracteres AHOOOOOOOOOORA ESTOY ENVIANDO  TODO ESTOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO Y MAAAAAAAASSSSSSSSSS!!! XD XD XD XD hasta coooooooommmmmmmmleeeetar 600 Caracteres AHOOOOOOOOOORA ESTOY ENVIANDO  TODO ESTOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO Y MAAAAAAAASSSSSSSSSS!!! XD XD XD XD hasta coooooooommmmmmmmleeeetar 600 Caracteres 1111111111111111111111 1 1 1 1 1 1 1XD .......................11111112222222222222222222222222222222222222222222222222222222222222222...........");

            //###


            // se establece en false la propiedad bloquing del socket para que no sea bloqueante
            socketCliente.Blocking = false;
            //Condición que establece que cuando los bytes recibidos sean siempre menores al tamaño del buffer de tx
            // se realice la condición interna

            while (totalBytesRecibidos < buferTx.Length)
            {
                // si los bytes enviados son menores al tamaño del buffer de transmisión entonces
                if (totalBytesEnviados < buferTx.Length)
                {
                    try
                    { // se incrementa la cantidad de bytes totales enviados, al enviar los datos se
                      // se setean los parámetros del buffer
                        totalBytesEnviados += socketCliente.Send(buferTx, totalBytesEnviados, buferTx.Length - totalBytesEnviados, SocketFlags.None);
                        // se muestra por consola la cantidad de bytes enviados
                        Console.WriteLine("Se han enviado un total de {0} bytes al servidor...", totalBytesEnviados);
                    }
                    catch (SocketException se)
                    {
                        //se controla la excepción "operation would block",
                        //mediante la condicion de identificador de excepción
                        if (se.ErrorCode == 10035)
                        {
                            //WSAEWOULDBLOCK: Recurso temporalmente no disponible
                            Console.WriteLine("Temporalmente no es posible enviar, se reintentará despues...");
                        }
                        else
                        {
                            //si no se muestra el mensaje de error, se cierra la conexión y se termina el proceso
                            Console.WriteLine(se.ErrorCode + ": " + se.Message);
                            socketCliente.Close();
                            Environment.Exit(se.ErrorCode);
                        }
                    }
                }
                try
                {   //se crea la variable bytes recibidos y se la setea en cero
                    int bytesRecibidos = 0;
                    //se condiciona si el buffer tx esta vacío
                    if ((bytesRecibidos = socketCliente.Receive(buferRx, totalBytesRecibidos, buferRx.Length - totalBytesRecibidos, SocketFlags.None)) == 0)
                    {   //se notifica
                        Console.WriteLine("La conexion se cerro prematuramente...");
                        break;
                    }

                    // adición de los bytes recibidos al total de bytes recibidos
                    totalBytesRecibidos += bytesRecibidos;
                }
                catch (SocketException se)
                { // se condiciona para identificar una excepción, y continuar con el procedimiento
                    if (se.ErrorCode == 10035)
                    {
                        continue;
                    }
                    else
                    {   //si no se muestra el mensaje con el error
                        Console.WriteLine(se.ErrorCode + ": " + se.Message);
                        break;
                    }
                }
                //se llama al método realizar Procesamiento
                RealizarProcesamiento();
            }
            //se muestra en pantalla el total de bytes recibidos por el servidor
            Console.WriteLine("Se han recibido {0} bytes desde el servidor: {1}", totalBytesRecibidos, Encoding.ASCII.GetString(buferRx, 0, totalBytesRecibidos));
            //se cierra la conexión
            socketCliente.Close();
        }
Exemple #8
0
 public void Deny_Resolve()
 {
     Dns.Resolve(null);
 }
Exemple #9
0
 public void PermitOnly_Resolve()
 {
     Dns.Resolve(null);
 }
        public Socket createDataSocket()
        {
            sendCommand("PASV");

            if (retValue != 227)
            {
                throw new IOException(reply.Substring(4));
            }


            int    index1 = reply.IndexOf('(');
            int    index2 = reply.IndexOf(')');
            string ipData = reply.Substring(index1 + 1, index2 - index1 - 1);

            int[] parts = new int[6];

            int    len       = ipData.Length;
            int    partCount = 0;
            string buf       = "";

            for (int i = 0; i < len && partCount <= 6; i++)
            {
                char ch = Char.Parse(ipData.Substring(i, 1));
                if (Char.IsDigit(ch))
                {
                    buf += ch;
                }
                else if (ch != ',')
                {
                    throw new IOException("Malformed PASV reply: " + reply);
                }

                if (ch == ',' || i + 1 == len)
                {
                    try
                    {
                        parts[partCount++] = Int32.Parse(buf);
                        buf = "";
                    }
                    catch (Exception)
                    {
                        throw new IOException("Malformed PASV reply: " + reply);
                    }
                }
            }

            string ipAddress = parts[0] + "." + parts[1] + "." +
                               parts[2] + "." + parts[3];

            int port = (parts[4] << 8) + parts[5];

            Socket     s  = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ep = new IPEndPoint(Dns.Resolve(ipAddress).AddressList[0], port);

            try
            {
                s.Connect(ep);
            }
            catch (Exception)
            {
                throw new IOException("Can't connect to remoteserver");
            }

            return(s);
        }
        public static void startServer()
        {
            // Data buffer for incoming data
            byte[] bytes = new Byte[1024];

            // Establish local endpoint for the socket.
            // DNS name of computer
            // listen on local network (obviously static ip, as defined in subnet)
            IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
            IPAddress   ipAddress  = ipHostInfo.AddressList[0];
            // port 11000 used randomly
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 10042);

            // Create socket
            Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // Bind socket to local address
            try
            {
                listener.Bind(localEndPoint);
                // 100ms refresh fairly std.
                listener.Listen(100);

                // socket created, wait for connection
                while (true)
                {
                    // Waiting for connection
                    // Thread suspended while waiting but that doesnt matter, because in own thread
                    Socket handler = listener.Accept();
                    data = null;

                    // Incoming connection being processed in own loop
                    while (true)
                    {
                        bytes = new byte[1024];
                        int bytesRec = handler.Receive(bytes);
                        data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                        if (data.IndexOf("<EOF>") > -1)
                        {
                            break;
                        }
                    }
                    // Cleanse string of '<EOF>' declarations
                    data = data.ToString().Remove(data.Length - 5);
                    string[] requestArray = data.Split('~');

                    string[] revisedArray = new string[2];
                    if (requestArray.Length == 1)
                    {
                        revisedArray[0] = requestArray[0];
                        revisedArray[1] = "";
                    }
                    else
                    {
                        revisedArray[0] = requestArray[0];
                        revisedArray[1] = requestArray[1];
                    }

                    // Got data, send to function to proces request
                    byte[] msg = Encoding.ASCII.GetBytes(processRequest(revisedArray));
                    handler.Send(msg);
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
            }
        }
        public static string SendRequest(string request, string serverName, int port)
        {
            string response = null;

            // Data buffer for incoming data.
            byte[] bytes = new byte[1024];

            // Connect to a remote device.
            try
            {
                // Establish the remote endpoint for the socket.
                // This example uses port 11000 on the local computer.
                IPHostEntry ipHostInfo = Dns.Resolve(serverName);
                IPAddress   ipAddress  = ipHostInfo.AddressList[0];
                IPEndPoint  remoteEP   = new IPEndPoint(ipAddress, port);

                // Create a TCP/IP  socket.
                Socket sender = new Socket(ipAddress.AddressFamily,
                                           SocketType.Stream, ProtocolType.Tcp);

                // Connect the socket to the remote endpoint. Catch any errors.
                try
                {
                    sender.Connect(remoteEP);

                    Logger.logMessage("Sending service request to IP " + serverName + ", PORT " + port.ToString() + " :" +
                                      Environment.NewLine +
                                      "\t>>" + request);

                    // Encode the data string into a byte array.
                    byte[] msg = Encoding.ASCII.GetBytes(request);

                    // Send the data through the socket.
                    int bytesSent = sender.Send(msg);

                    // Receive the response from the remote device.
                    int bytesRec = sender.Receive(bytes);
                    response = Encoding.ASCII.GetString(bytes, 0, bytesRec);

                    Logger.logMessage("Response from Published Service at IP " + serverName + ", PORT " + port.ToString() + " :" +
                                      Environment.NewLine +
                                      "\t>>" + response);

                    // Release the socket.
                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();
                }
                catch (ArgumentNullException ane)
                {
                    //Console.WriteLine("ArgumentNullException : {0}",ane.ToString());
                    Logger.logException(ane);

                    throw ane;
                }
                catch (SocketException se)
                {
                    //Console.WriteLine("SocketException : {0}",se.ToString());
                    Logger.logException(se);

                    throw se;
                }
                catch (Exception e)
                {
                    //Console.WriteLine("Unexpected exception : {0}", e.ToString());
                    Logger.logException(e);

                    throw e;
                }
            }
            catch (Exception e)
            {
                //Console.WriteLine( e.ToString());
                Logger.logException(e);

                throw e;
            }

            return(response);
        }
Exemple #13
0
 public GainCapitalClient(string host, int port, string token)
 {
     m_ipAddress = Dns.Resolve(host).AddressList[0];
     m_port      = port;
     m_token     = token;
 }
    public static void StartListening()
    {
        // Data buffer for incoming data.
        byte[] bytes = new Byte[1024];

        // Establish the local endpoint for the socket.
        // Dns.GetHostName returns the name of the
        // host running the application.
        int         port          = 11000;
        IPHostEntry ipHostInfo    = Dns.Resolve(Dns.GetHostName());
        IPAddress   ipAddress     = ipHostInfo.AddressList[0];
        IPEndPoint  localEndPoint = new IPEndPoint(ipAddress, port);

        // Create a TCP/IP socket.
        Socket listener = new Socket(AddressFamily.InterNetwork,
                                     SocketType.Stream, ProtocolType.Tcp);

        // Bind the socket to the local endpoint and
        // listen for incoming connections.
        try
        {
            listener.Bind(localEndPoint);
            listener.Listen(10);

            // Start listening for connections.
            while (true)
            {
                Console.WriteLine("Waiting for a connection...");
                // Program is suspended while waiting for an incoming connection.
                Socket handler = listener.Accept();
                data = null;

                // An incoming connection needs to be processed.
                while (true)
                {
                    bytes = new byte[1024];
                    int bytesRec = handler.Receive(bytes);
                    data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                    if (data.IndexOf("<EOF>") > -1)
                    {
                        break;
                    }
                }

                // Show the data on the console.
                Console.WriteLine("Text received : {0}", data);

                // Echo the data back to the client.
                byte[] msg = Encoding.ASCII.GetBytes(data);

                handler.Send(msg);
                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

        Console.WriteLine("\nPress ENTER to continue...");
        Console.Read();
    }
Exemple #15
0
 private void ConnectButton_Click(object sender, EventArgs e)
 {
     if (connected)
     {
         obj.client.Close();
     }
     else if (client == null || !client.IsAlive)
     {
         string    address  = addrTextBox.Text.Trim();
         string    number   = portTextBox.Text.Trim();
         string    username = usernameTextBox.Text.Trim();
         bool      error    = false;
         IPAddress ip       = null;
         if (address.Length < 1)
         {
             error = true;
             Log(SystemMsg("Address is required"));
         }
         else
         {
             try
             {
                 ip = Dns.Resolve(address).AddressList[0];
             }
             catch
             {
                 error = true;
                 Log(SystemMsg("Address is not valid"));
             }
         }
         int port = 0;
         if (number.Length < 1)
         {
             error = true;
             Log(SystemMsg("Port number is required"));
         }
         else if (!int.TryParse(number, out port))
         {
             error = true;
             Log(SystemMsg("Port number is not valid"));
         }
         else if (port < 0 || port > 65535)
         {
             error = true;
             Log(SystemMsg("Port number is out of range"));
         }
         if (username.Length < 1)
         {
             error = true;
             Log(SystemMsg("Username is required"));
         }
         if (!error)
         {
             // encryption key is optional
             client = new Thread(() => Connection(ip, port, username, keyTextBox.Text))
             {
                 IsBackground = true
             };
             client.Start();
         }
     }
 }
Exemple #16
0
 public void FixtureSetUp()
 {
     reset    = new ManualResetEvent(false);
     hostname = Dns.GetHostName();
     var ip = Dns.Resolve(site).AddressList[0];
 }
Exemple #17
0
        ///<summary>Processes a specified query and connects to the requested HTTP web server.</summary>
        ///<param name="Query">A string containing the query to process.</param>
        ///<remarks>If there's an error while processing the HTTP request or when connecting to the remote server, the Proxy sends a "400 - Bad Request" error to the client.</remarks>
        private void ProcessQuery(string Query)
        {
            HeaderFields = ParseQuery(Query);
            if (HeaderFields == null || !HeaderFields.ContainsKey("Host"))
            {
                SendBadRequest();
                return;
            }
            int    Port;
            string Host;
            int    Ret;

            if (HttpRequestType.ToUpper().Equals("CONNECT"))
            { //HTTPS
                Ret = RequestedPath.IndexOf(":");
                if (Ret >= 0)
                {
                    Host = RequestedPath.Substring(0, Ret);
                    if (RequestedPath.Length > Ret + 1)
                    {
                        Port = int.Parse(RequestedPath.Substring(Ret + 1));
                    }
                    else
                    {
                        Port = 443;
                    }
                }
                else
                {
                    Host = RequestedPath;
                    Port = 443;
                }
            }
            else
            { //Normal HTTP
                Ret = ((string)HeaderFields["Host"]).IndexOf(":");
                if (Ret > 0)
                {
                    Host = ((string)HeaderFields["Host"]).Substring(0, Ret);
                    Port = int.Parse(((string)HeaderFields["Host"]).Substring(Ret + 1));
                }
                else
                {
                    Host = (string)HeaderFields["Host"];
                    Port = 80;
                }
                if (HttpRequestType.ToUpper().Equals("POST"))
                {
                    int index = Query.IndexOf("\r\n\r\n");
                    m_HttpPost = Query.Substring(index + 4);
                }
            }
            try
            {
                IPEndPoint DestinationEndPoint = new IPEndPoint(Dns.Resolve(Host).AddressList[0], Port);
                DestinationSocket = new Socket(DestinationEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                if (HeaderFields.ContainsKey("Proxy-Connection") && HeaderFields["Proxy-Connection"].ToLower().Equals("keep-alive"))
                {
                    DestinationSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);
                }
                DestinationSocket.BeginConnect(DestinationEndPoint, new AsyncCallback(this.OnConnected), DestinationSocket);
            }
            catch
            {
                SendBadRequest();
                return;
            }
        }
Exemple #18
0
    public byte[] get(string request, string host, string community, string mibstring)
    {
        byte[] packet = new byte[1024];
        byte[] mib    = new byte[1024];
        int    snmplen;
        int    comlen = community.Length;

        string[] mibvals = mibstring.Split('.');
        int      miblen = mibvals.Length;
        int      cnt = 0, temp, i;
        int      orgmiblen = miblen;
        int      pos       = 0;

        // Convert the string MIB into a byte array of integer values
        // Unfortunately, values over 128 require multiple bytes
        // which also increases the MIB length
        for (i = 0; i < orgmiblen; i++)
        {
            temp = Convert.ToInt16(mibvals[i]);
            if (temp > 127)
            {
                mib[cnt]     = Convert.ToByte(128 + (temp / 128));
                mib[cnt + 1] = Convert.ToByte(temp - ((temp / 128) * 128));
                cnt         += 2;
                miblen++;
            }
            else
            {
                mib[cnt] = Convert.ToByte(temp);
                cnt++;
            }
        }
        snmplen = 29 + comlen + miblen - 1; //Length of entire SNMP packet

        //The SNMP sequence start
        packet[pos++] = 0x30;                        //Sequence start
        packet[pos++] = Convert.ToByte(snmplen - 2); //sequence size

        //SNMP version
        packet[pos++] = 0x02; //Integer type
        packet[pos++] = 0x01; //length
        packet[pos++] = 0x00; //SNMP version 1

        //Community name
        packet[pos++] = 0x04;                   // String type
        packet[pos++] = Convert.ToByte(comlen); //length
        //Convert community name to byte array
        byte[] data = Encoding.ASCII.GetBytes(community);
        for (i = 0; i < data.Length; i++)
        {
            packet[pos++] = data[i];
        }

        //Add GetRequest or GetNextRequest value
        if (request == "get")
        {
            packet[pos++] = 0xA0;
        }
        else
        {
            packet[pos++] = 0xA1;
        }

        packet[pos++] = Convert.ToByte(20 + miblen - 1); //Size of total MIB

        //Request ID
        packet[pos++] = 0x02; //Integer type
        packet[pos++] = 0x04; //length
        packet[pos++] = 0x00; //SNMP request ID
        packet[pos++] = 0x00;
        packet[pos++] = 0x00;
        packet[pos++] = 0x01;

        //Error status
        packet[pos++] = 0x02; //Integer type
        packet[pos++] = 0x01; //length
        packet[pos++] = 0x00; //SNMP error status

        //Error index
        packet[pos++] = 0x02; //Integer type
        packet[pos++] = 0x01; //length
        packet[pos++] = 0x00; //SNMP error index

        //Start of variable bindings
        packet[pos++] = 0x30;                               //Start of variable bindings sequence

        packet[pos++] = Convert.ToByte(6 + miblen - 1);     // Size of variable binding

        packet[pos++] = 0x30;                               //Start of first variable bindings sequence
        packet[pos++] = Convert.ToByte(6 + miblen - 1 - 2); // size
        packet[pos++] = 0x06;                               //Object type
        packet[pos++] = Convert.ToByte(miblen - 1);         //length

        //Start of MIB
        packet[pos++] = 0x2b;
        //Place MIB array in packet
        for (i = 2; i < miblen; i++)
        {
            packet[pos++] = Convert.ToByte(mib[i]);
        }
        packet[pos++] = 0x05; //Null object value
        packet[pos++] = 0x00; //Null

        //Send packet to destination
        Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
                                 ProtocolType.Udp);

        sock.SetSocketOption(SocketOptionLevel.Socket,
                             SocketOptionName.ReceiveTimeout, 5000);
        IPHostEntry ihe = Dns.Resolve(host);
        IPEndPoint  iep = new IPEndPoint(ihe.AddressList[0], 161);
        EndPoint    ep  = (EndPoint)iep;

        sock.SendTo(packet, snmplen, SocketFlags.None, iep);

        //Receive response from packet
        try
        {
            int recv = sock.ReceiveFrom(packet, ref ep);
        } catch (SocketException)
        {
            packet[0] = 0xff;
        }
        return(packet);
    }
Exemple #19
0
        /// <summary>
        /// Contacts the server and sends the StockLedgerReport.txt file name to print.
        /// </summary>
        public void Print()
        {
            byte[] bytes = new byte[1024];

            // Connect to a remote device.
            try
            {
                // Establish the remote endpoint for the socket.
                // The name of the
                // remote device is "host.contoso.com".
                IPHostEntry ipHostInfo = Dns.Resolve("127.0.0.1");
                IPAddress   ipAddress  = ipHostInfo.AddressList[0];
                IPEndPoint  remoteEP   = new IPEndPoint(ipAddress, 62000);

                // Create a TCP/IP  socket.
                Socket sender1 = new Socket(AddressFamily.InterNetwork,
                                            SocketType.Stream, ProtocolType.Tcp);

                // Connect the socket to the remote endpoint. Catch any errors.
                try
                {
                    sender1.Connect(remoteEP);
                    //CreateLogFiles.ErrorLog("Form:StockLedgerReport.aspx,Method:Print"+uid);
                    Console.WriteLine("Socket connected to {0}",
                                      sender1.RemoteEndPoint.ToString());

                    // Encode the data string into a byte array.
                    string home_drive = Environment.SystemDirectory;
                    home_drive = home_drive.Substring(0, 2);
                    byte[] msg = Encoding.ASCII.GetBytes(home_drive + "\\Inetpub\\wwwroot\\Servosms\\Sysitem\\ServosmsPrintServices\\ReportView\\StockLedgerReport.txt<EOF>");

                    // Send the data through the socket.
                    int bytesSent = sender1.Send(msg);

                    // Receive the response from the remote device.
                    int bytesRec = sender1.Receive(bytes);
                    Console.WriteLine("Echoed test = {0}",
                                      Encoding.ASCII.GetString(bytes, 0, bytesRec));

                    // Release the socket.
                    sender1.Shutdown(SocketShutdown.Both);
                    sender1.Close();
                    //CreateLogFiles.ErrorLog("Form:Vehiclereport.aspx,Method:print"+ "  Daily sales record  Printed   userid  "+uid);
                    CreateLogFiles.ErrorLog("Form:StockLedgerReport.aspx,Method:print. Report Printed   userid  " + uid);
                }
                catch (ArgumentNullException ane)
                {
                    Console.WriteLine("ArgumentNullException : {0}", ane.ToString());


                    CreateLogFiles.ErrorLog("Form:StockLedgerReport.aspx,Method:print" + " EXCEPTION " + ane.Message + "  userid  " + uid);
                }
                catch (SocketException se)
                {
                    Console.WriteLine("SocketException : {0}", se.ToString());
                    CreateLogFiles.ErrorLog("Form:StockLedgerReport.aspx,Method:print" + " EXCEPTION " + se.Message + "  userid  " + uid);
                }
                catch (Exception es)
                {
                    Console.WriteLine("Unexpected exception : {0}", es.ToString());
                    CreateLogFiles.ErrorLog("Form:StockLedgerReport.aspx,Method:print" + " EXCEPTION " + es.Message + "  userid  " + uid);
                }
            }
            catch (Exception ex)
            {
                CreateLogFiles.ErrorLog("Form:StockLedgerReport.aspx,Method:print  EXCEPTION " + ex.Message + "  userid  " + uid);
            }
        }
        //  public static IPAddress IP { get; set; }



        public static void StartListening()
        {
            IPHostEntry ipHostInfo    = Dns.Resolve(Dns.GetHostName());
            IPAddress   ipAddress     = ipHostInfo.AddressList[0];
            IPEndPoint  localEndPoint = new IPEndPoint(ipAddress, port);
            // Create a TCP/IP socket.
            Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);


            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(10);

                // Start listening for connections.
                // Console.WriteLine("Waiting for a connection...");
                // Program is suspended while waiting for an incoming connection.
                Socket     handler    = listener.Accept();
                IPEndPoint ipEndPoint = handler.RemoteEndPoint as IPEndPoint;
                if ((ipEndPoint) != null)
                {
                    Server.BeginInvoke(new AddClientHandler(Server.AddClient), ipEndPoint);
                }
                //lbxServer.Items.Add(ipEndPoint);
                //Int32 filesNumber = binFilesNames.Count;
                //byte[] filesNumberByte = BitConverter.GetBytes(filesNumber);
                //handler.Send(filesNumberByte);
                //// --
                //foreach (string binName in binFilesNames)
                //{
                //    fileNameByte = Encoding.UTF8.GetBytes(binName);
                //    fileNameLenByte = BitConverter.GetBytes(fileNameByte.Length);
                //    handler.Send(fileNameLenByte);
                //    handler.Send(fileNameByte);
                //    // --
                //    fileStream = new FileStream(sourceFilePath + binName, FileMode.Open, FileAccess.Read);
                //    fileLen = fileStream.Length;
                //    fileLenByte = BitConverter.GetBytes(fileLen);
                //    handler.Send(fileLenByte);
                //    // --
                //    NoOfPackets = Convert.ToInt32(Math.Ceiling(
                //        Convert.ToDouble(fileLen) / Convert.ToDouble(BufferSize)));
                //    for (i = 0; i < NoOfPackets; i++)
                //    {
                //        if (fileLen > BufferSize)
                //        {
                //            buffer = new byte[BufferSize];
                //            // reeding data from file and writing it to the bytes "buffer"
                //            readBytes = fileStream.Read(buffer, 0, BufferSize);
                //            // send bytes from "buffer"
                //            handler.Send(buffer, readBytes, SocketFlags.None);
                //            fileLen -= BufferSize;
                //        }
                //        else
                //        {
                //            buffer = new byte[fileLen];
                //            // reeding data from file and writing it to the bytes "buffer"
                //            readBytes = fileStream.Read(buffer, 0, (int)fileLen);
                //            // send bytes from "buffer"
                //            handler.Send(buffer, readBytes, SocketFlags.None);
                //        }
                //    }
                //    fileStream.Close();
                //}
                // Release the socket.
                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Exemple #21
0
        private string GetLocalIPAddress()
        {
            IPAddress ipAddr = Dns.Resolve(Dns.GetHostName()).AddressList[0];

            return(ipAddr.ToString());
        }
Exemple #22
0
        /// <summary>
        /// Login to the remote server.
        /// </summary>
        public void Login()
        {
            if (this.loggedin)
            {
                this.Close();
            }

            Debug.WriteLine("Opening connection to " + this.server, "FtpClient");

            IPAddress  addr = null;
            IPEndPoint ep   = null;

            try
            {
                this.clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                addr = Dns.Resolve(this.server).AddressList[0];
                ep   = new IPEndPoint(addr, this.port);
                this.clientSocket.Connect(ep);
            }
            catch (Exception ex)
            {
                // doubtfull
                if (this.clientSocket != null && this.clientSocket.Connected)
                {
                    this.clientSocket.Close();
                }

                throw new FtpException("Couldn't connect to remote server", ex);
            }

            this.readResponse();

            if (this.resultCode != 220)
            {
                this.Close();
                throw new FtpException(this.result.Substring(4));
            }

            this.sendCommand("USER " + username);

            if (!(this.resultCode == 331 || this.resultCode == 230))
            {
                this.cleanup();
                throw new FtpException(this.result.Substring(4));
            }

            if (this.resultCode != 230)
            {
                this.sendCommand("PASS " + password);

                if (!(this.resultCode == 230 || this.resultCode == 202))
                {
                    this.cleanup();
                    throw new FtpException(this.result.Substring(4));
                }
            }

            this.loggedin = true;

            Debug.WriteLine("Connected to " + this.server, "FtpClient");

            this.ChangeDir(this.remotePath);
        }
Exemple #23
0
        public static void Main(string[] args)
        {
            // establish the local end point for the socket
            IPHostEntry ipHost     = Dns.Resolve("localhost");
            IPAddress   ipAddr     = ipHost.AddressList[0];
            IPEndPoint  ipEndPoint = new IPEndPoint(ipAddr, 11000);

            // create a Tcp/Ip Socket
            Socket sListener = new Socket(AddressFamily.InterNetwork,
                                          SocketType.Stream, ProtocolType.Tcp);

            // bind the socket to the local endpoint and
            // listen to the incoming sockets

            try
            {
                sListener.Bind(ipEndPoint);
                sListener.Listen(10);

                // Start listening for connections

                while (true)
                {
                    Console.WriteLine("Waiting for a connection on port {0}", ipEndPoint);

                    // program is suspended while waiting for an incoming connection
                    Socket handler = sListener.Accept();

                    string data = null;

                    // we got the client attempting to connect
                    while (true)
                    {
                        byte[] bytes = new byte[1024];

                        int bytesRec = handler.Receive(bytes);

                        data += Encoding.ASCII.GetString(bytes, 0, bytesRec);

                        if (data.IndexOf("<theend>") > -1)
                        {
                            break;
                        }
                    }

                    // show the data on the console
                    Console.WriteLine("Text Received: {0}", data);

                    string theReply = "Thank you for those " + data.Length.ToString()
                                      + " characters...";
                    byte[] msg = Encoding.ASCII.GetBytes(theReply);

                    handler.Send(msg);
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        } // end of Main
Exemple #24
0
        /// <summary>
        /// when doing data transfers, we need to open another socket for it.
        /// </summary>
        /// <returns>Connected socket</returns>
        private Socket createDataSocket()
        {
            this.sendCommand("PASV");

            if (this.resultCode != 227)
            {
                throw new FtpException(this.result.Substring(4));
            }

            int index1 = this.result.IndexOf('(');
            int index2 = this.result.IndexOf(')');

            string ipData = this.result.Substring(index1 + 1, index2 - index1 - 1);

            int[] parts = new int[6];

            int    len       = ipData.Length;
            int    partCount = 0;
            string buf       = "";

            for (int i = 0; i < len && partCount <= 6; i++)
            {
                char ch = char.Parse(ipData.Substring(i, 1));

                if (char.IsDigit(ch))
                {
                    buf += ch;
                }

                else if (ch != ',')
                {
                    throw new FtpException("Malformed PASV result: " + result);
                }

                if (ch == ',' || i + 1 == len)
                {
                    try
                    {
                        parts[partCount++] = int.Parse(buf);
                        buf = "";
                    }
                    catch (Exception ex)
                    {
                        throw new FtpException("Malformed PASV result (not supported?): " + this.result, ex);
                    }
                }
            }

            string ipAddress = parts[0] + "." + parts[1] + "." + parts[2] + "." + parts[3];

            int port = (parts[4] << 8) + parts[5];

            Socket     socket = null;
            IPEndPoint ep     = null;

            try
            {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                ep     = new IPEndPoint(Dns.Resolve(ipAddress).AddressList[0], port);
                socket.Connect(ep);
            }
            catch (Exception ex)
            {
                // doubtfull....
                if (socket != null && socket.Connected)
                {
                    socket.Close();
                }

                throw new FtpException("Can't connect to remote server", ex);
            }

            return(socket);
        }
        /// <summary>
        /// Prepares the report file DocumentCancelReport.txt for printing.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void BtnPrint_Click(object sender, System.EventArgs e)
        {
            //10.07.09 MessageBox.Show("This Task is under Proccess...");
            //10.07.09 return;
            if (Flag == 0)
            {
                MessageBox.Show("Please Click The View Button First");
                return;
            }
            byte[] bytes = new byte[1024];

            // Connect to a remote device.
            try
            {
                makingReport();
                // Establish the remote endpoint for the socket.
                // The name of the
                // remote device is "host.contoso.com".
                IPHostEntry ipHostInfo = Dns.Resolve("127.0.0.1");
                IPAddress   ipAddress  = ipHostInfo.AddressList[0];
                IPEndPoint  remoteEP   = new IPEndPoint(ipAddress, 62000);

                // Create a TCP/IP  socket.
                Socket sender1 = new Socket(AddressFamily.InterNetwork,
                                            SocketType.Stream, ProtocolType.Tcp);

                // Connect the socket to the remote endpoint. Catch any errors.
                try
                {
                    sender1.Connect(remoteEP);

                    Console.WriteLine("Socket connected to {0}",
                                      sender1.RemoteEndPoint.ToString());
                    CreateLogFiles.ErrorLog("Form:AttendenceReport.aspx,Class:PetrolPumpClass.cs,Method:btnprint_Clickt   Attendence Report  Printed" + "  userid  " + uid);
                    // Encode the data string into a byte array.
                    string home_drive = Environment.SystemDirectory;
                    home_drive = home_drive.Substring(0, 2);
                    byte[] msg = Encoding.ASCII.GetBytes(home_drive + "\\Inetpub\\wwwroot\\Servosms\\Sysitem\\ServosmsPrintServices\\ReportView\\AttendenceReport.txt<EOF>");

                    // Send the data through the socket.
                    int bytesSent = sender1.Send(msg);

                    // Receive the response from the remote device.
                    int bytesRec = sender1.Receive(bytes);
                    Console.WriteLine("Echoed test = {0}",
                                      Encoding.ASCII.GetString(bytes, 0, bytesRec));

                    // Release the socket.
                    sender1.Shutdown(SocketShutdown.Both);
                    sender1.Close();
                }
                catch (ArgumentNullException ane)
                {
                    Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
                    CreateLogFiles.ErrorLog("Form:AttendenceReport.aspx,Class:PetrolPumpClass.cs,Method:btnprint_Clickt    Attendence Report  Printed" + "  EXCEPTION " + ane.Message + "  userid  " + uid);
                }
                catch (SocketException se)
                {
                    Console.WriteLine("SocketException : {0}", se.ToString());
                    CreateLogFiles.ErrorLog("Form:AttendenceReport.aspx,Class:PetrolPumpClass.cs,Method:btnprint_Clickt    Attendence Report  Printed" + "  EXCEPTION " + se.Message + "  userid  " + uid);
                }
                catch (Exception es)
                {
                    Console.WriteLine("Unexpected exception : {0}", es.ToString());
                    CreateLogFiles.ErrorLog("Form:AttendenceReport.aspx,Class:PetrolPumpClass.cs,Method:btnprint_Clickt    Attendence Report  Printed" + "  EXCEPTION " + es.Message + "  userid  " + uid);
                }
            }
            catch (Exception ex)
            {
                CreateLogFiles.ErrorLog("Form:AttendenceReport.aspx,Class:PetrolPumpClass.cs,Method:btnprint_Clickt   Attendence Report  Printed" + "  EXCEPTION " + ex.Message + "  userid  " + uid);
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                IdMunicipio.Text = Session["IdMunicipio"].ToString();
                IdUnidad.Text    = Session["IdUnidad"].ToString();
                PUESTO.Text      = Session["PUESTO"].ToString();
                LBLUSUARIO.Text  = Session["Us"].ToString();
                cargarFecha();
                UNDD.Text      = Session["UNDD_DSCRPCION"].ToString();
                IdUsuario.Text = Session["IdUsuario"].ToString();

                Session["ID_ORDEN_TEMP"]   = "";
                Session["ID_USUARIO_TEMP"] = "";

                //IDtIPOuNIDAD.Text = Session["ID_UNDD_TPO"].ToString();

                Session["ID_UNIDAD"] = Request.QueryString["ID_UNIDAD"];

                if (Request.QueryString["ID_ORDEN"] != "")
                {
                    IdOrden.Text = Request.QueryString["ID_ORDEN"];
                }
                if (Request.QueryString["NUC"] != "")
                {
                    lblNucPI.Text = Request.QueryString["NUC"];
                }
                if (Request.QueryString["ID_CARPETA"] != "")
                {
                    Session["ID_CARPETA"] = Request.QueryString["ID_CARPETA"];
                    lblIdCarpeta.Text     = Request.QueryString["ID_CARPETA"];
                }

                //Para Cagar Documentos
                Session["op"]    = Request.QueryString["op"];
                Session["IdDoc"] = Request.QueryString["IdDoc"];
                if (Session["IdDoc"] == null)
                {
                    Session["IdDoc"] = "0";
                }
                if (Session["op"] == null)
                {
                    Session["op"] = "0";
                }

                if (Session["op"].ToString() == "Docs")
                {
                    CargarDocumento(Session["IdDoc"].ToString());
                }

                //Ocultar tablas de Asignar
                tbl_asignarPI.Visible = false;
                tbl_verPI.Visible     = false;

                if (Request.QueryString["btnAsignar"] == "1")
                {
                    Session["ASIGNADA"]   = Request.QueryString["ASIGNADA"];
                    tbl_asignarPI.Visible = true;
                    tbl_verPI.Visible     = false;
                }
                else if (Request.QueryString["btnVer"] == "1")
                {
                    tbl_asignarPI.Visible = false;
                    tbl_verPI.Visible     = true;
                }


                PGJ.CargaCombo(ddlTipoOrden, "CAT_TIPO_ORDEN", "IdTipoOrden", "TipoOrden");

                //Obtenemos la URL de la pagina aspx
                string path = HttpContext.Current.Request.Url.AbsolutePath;
                Session["PAGINA"] = path;

                // tenemos el nombre del equipo cliente
                string name = System.Net.Dns.GetHostName();
                Session["NOM_MAQUINA"] = name;

                IPAddress hostIPAddress1 = (Dns.Resolve(name)).AddressList[0];

                //string ip = System.Net.Dns.GetHostAddresses(name)[0].ToString();

                //Obtenemos la IP del CLIENTE
                Session["IP_SERVER"] = hostIPAddress1.ToString();  //Request.ServerVariables["LOCAL_ADDR"];


                //Label2.Text = Session["USUARIO"].ToString() + "  " + Session["IP_SERVER"].ToString() + "  " + Session["NOM_MAQUINA"].ToString() + "  " + Session["PAGINA"].ToString() + "  " + "INICIO DE SESIÓN";

                PGJ.InsertarBitacora(Session["USUARIO"].ToString(), Session["IP_SERVER"].ToString(), Session["NOM_MAQUINA"].ToString(), Session["PAGINA"].ToString(), "INICIO DE SESIÓN");


                Label332.Visible    = false;
                FileUpload1.Visible = false;
                cmdGuardar.Visible  = false;
            }
        }
Exemple #27
0
        void SubTestResolve(string addr)
        {
            IPHostEntry h = Dns.Resolve(addr);

            SubTestValidIPHostEntry(h);
        }
Exemple #28
0
    static void Main(string[] args)
    {
        // Check that an argument was specified when the
        // program was invoked.
        if (args.Length == 0)
        {
            Console.WriteLine("Error: The name of the host computer" +
                              " must be specified when the program is invoked.");
            return;
        }

        string remoteName = args[0];

        // Create the underlying socket and connect to the server.
        Socket clientSocket = new Socket(AddressFamily.InterNetwork,
                                         SocketType.Stream, ProtocolType.Tcp);

        clientSocket.Connect(new IPEndPoint(
                                 Dns.Resolve(remoteName).AddressList[0], 1800));

        Console.WriteLine("Client is connected.\n");

        // <Snippet2>
        // Create a NetworkStream that owns clientSocket and
        // then create a BufferedStream on top of the NetworkStream.
        // Both streams are disposed when execution exits the
        // using statement.
        using (Stream
               netStream = new NetworkStream(clientSocket, true),
               bufStream =
                   new BufferedStream(netStream, streamBufferSize))
        // </Snippet2>
        {
            // <Snippet3>
            // Check whether the underlying stream supports seeking.
            Console.WriteLine("NetworkStream {0} seeking.\n",
                              bufStream.CanSeek ? "supports" : "does not support");
            // </Snippet3>

            // Send and receive data.
            // <Snippet4>
            if (bufStream.CanWrite)
            {
                SendData(netStream, bufStream);
            }
            // </Snippet4>
            // <Snippet5>
            if (bufStream.CanRead)
            {
                ReceiveData(netStream, bufStream);
            }
            // </Snippet5>

            // <Snippet8>
            // When bufStream is closed, netStream is in turn
            // closed, which in turn shuts down the connection
            // and closes clientSocket.
            Console.WriteLine("\nShutting down the connection.");
            bufStream.Close();
            // </Snippet8>
        }
    }
Exemple #29
0
        static void Main(string[] args)
        {
            if ((args.Length < 6))
            {
                Console.WriteLine("Usage: SMTPClient [SMTP Server DNS/IP] [Port] [From] [To] [Subject] [Message]");
                return;
            }

            string host    = args[0]; // SMTP郵件伺服器之主機名稱或IP位址
            string port    = args[1]; // SMTP郵件伺服器之通訊埠,預設通訊埠為25
            string from    = args[2]; // 寄件者郵件地址
            string to      = args[3]; // 收件者郵件地址
            string subject = args[4]; // 郵件主旨
            string message = args[5]; // 郵件內容

            // 連線郵件伺服器
            try
            {
                IPAddress smtpServerIP = Dns.Resolve(host).AddressList[0];

                IPEndPoint smtpServerHost = new IPEndPoint(smtpServerIP, Int32.Parse(port));

                smtpSocket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                // 建立用戶端與郵件伺服器連線
                smtpSocket.Connect(smtpServerHost);

                // 判斷是否無法連線至郵件伺服器
                if (!smtpSocket.Connected)
                {
                    Console.WriteLine("無法連線至郵件伺服器: " + host + ":" + port);
                }

                // 判斷郵件伺服器是否回應 220 Ready 訊息
                if (!SMTPResponse("220"))
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            // 傳送郵件訊息
            try
            {
                string data = "";

                // 用戶端傳送 HELO <Mail Server> 訊息回應郵件伺服器
                data = "HELO " + host + "\r\n";

                // 傳送郵件訊息
                if (!SMTPRequest(data))
                {
                    return;
                }

                // 判斷郵件伺服器是否回應 250 OK 訊息
                if (!SMTPResponse("250"))
                {
                    return;
                }

                // 用戶端傳送 MAIL FROM:<寄件者E-Mail Address> 訊息
                // 一旦有任何錯誤或產生郵件回應時,將回傳至此郵件地址
                data = "MAIL FROM: " + from + "\r\n";
                if (!SMTPRequest(data))
                {
                    return;
                }

                // 若寄件者郵件地址正確,郵件伺服器將回傳 250 OK 訊息
                // 否則將回傳 550 No such user 訊息
                if (!SMTPResponse("250"))
                {
                    return;
                }

                // 當收件者有一個以上時,需以逗號(Comma)隔開
                string[] toAddress = to.Split(",".ToCharArray());

                for (int i = 0; i < toAddress.Length; i++)
                {
                    if (toAddress[i].Trim().ToString() != "")
                    {
                        // 用戶端傳送 RCPT TO:<收件者E-Mail Address> 指令
                        // 代表收件者郵件地址
                        data = "RCPT TO: " + toAddress[i].Trim().ToString() + "\r\n";

                        // 傳送郵件訊息
                        if (!SMTPRequest(data))
                        {
                            return;
                        }

                        // 若收件者郵件地址正確,郵件伺服器將回傳 250 OK 訊息
                        // 否則將回傳 550 No such user 訊息
                        if (!SMTPResponse("250"))
                        {
                            return;
                        }
                    }
                }

                // 開始處理郵件標題及內容,用戶端傳送 DATA 指令
                // 告知郵件伺服器接著要開始傳送郵件標題及內容
                data = "DATA" + "\r\n";

                // 傳送郵件訊息
                if (!SMTPRequest(data))
                {
                    return;
                }

                // 若正確,郵件伺服器將回應 354 Start mail input 訊息
                if (!SMTPResponse("354"))
                {
                    return;
                }

                // 傳送郵件標題之日期 (Date) ,每一行須以<CR><LF>(換行歸位\r\n)結尾
                data = "Date: " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString() + "\r\n";

                // 傳送郵件訊息
                if (!SMTPRequest(data))
                {
                    return;
                }

                // 傳送郵件標題之寄件者郵件地址 (From)
                data = "From: " + from + "\r\n";

                // 傳送郵件訊息
                if (!SMTPRequest(data))
                {
                    return;
                }

                // 傳送郵件標題之收件者郵件地址 (To)
                data = "To: " + to + "\r\n";

                // 傳送郵件訊息
                if (!SMTPRequest(data))
                {
                    return;
                }

                // 傳送郵件標題之主旨 (Subject)
                data = "Subject: " + subject + "\r\n" + "\r\n";

                // 傳送郵件訊息
                if (!SMTPRequest(data))
                {
                    return;
                }

                // 傳送郵件內容
                data = message + "\r\n";

                // 傳送郵件訊息
                if (!SMTPRequest(data))
                {
                    return;
                }

                // 傳送歸位、換行、句點、歸位、換行字串,則<CR><LF>.<CR><LF>
                // 代表郵件內容傳送結束
                data = "\r\n" + "." + "\r\n";

                // 傳送郵件訊息
                if (!SMTPRequest(data))
                {
                    return;
                }

                // 判斷郵件伺服器是否回應 250 OK 訊息,代表傳送成功
                if (!SMTPResponse("250"))
                {
                    return;
                }

                // 用戶端傳送 QUIT 指令,要求結束通訊連結
                data = "QUIT" + "\r\n";

                // 傳送郵件訊息
                if (!SMTPRequest(data))
                {
                    return;
                }

                // 判斷郵件伺服器是否回應 221 Service closing transmission channel 訊息,代表連線結束
                if (!SMTPResponse("221"))
                {
                    return;
                }

                // 同時暫停用戶端的傳送和接收作業
                smtpSocket.Shutdown(SocketShutdown.Both);
                // 關閉用戶端Socket
                smtpSocket.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
 public void Dns_Resolve_CallSocketInit_Ok()
 {
     NameResolutionPal.FakesReset();
     Assert.ThrowsAny <Exception>(() => Dns.Resolve(null));
     Assert.NotEqual(0, NameResolutionPal.FakesEnsureSocketsAreInitializedCallCount);
 }