private void button1_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            var ControllerIPAddress = new IPAddress(new byte[] { 192, 168, 0, 2 });
            var ControllerPort = 40001;
            var ControllerEndPoint = new IPEndPoint(ControllerIPAddress, ControllerPort);
            _client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            var header = "@";
            var command = "00C";
            var checksum = "E3";
            var end = "\r\n";
            var data = header + command + checksum + end;
            byte[] bytes = new byte[1024];

            //Start Connect
            _connectDone.Reset();
            watch.Start();
            _client.BeginConnect(ControllerIPAddress, ControllerPort, new AsyncCallback(ConnectCallback), _client);
            //wait 2s
            _connectDone.WaitOne(2000, false);

            var text = (_client.Connected) ? "ok" : "ng";
            richTextBox1.AppendText(text + "\r\n");
            watch.Stop();
            richTextBox1.AppendText("Consumer time: " + watch.ElapsedMilliseconds + "\r\n");
        }
Beispiel #2
1
 /// <summary>
 /// Constructeur
 /// </summary>
 /// <param name="port">Port d'ecoute</param>
 /// <param name="cl"></param>
 public Recepteur(int port, Game1 cl)
 {
     this._client = cl;
     this._portReception = port;
     this._ip = GestionReseau.GetMyLocalIp();
     _reception = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 }
Beispiel #3
0
        public IPDestination(IPAddress ip, uint port, bool isOpenExternally)
        {
            this.ip = ip;
            this.port = port;

            base.isOpenExternally = isOpenExternally;
        }
Beispiel #4
0
 public static OSD FromIP(IPAddress address)
 {
     if (address != null && address != IPAddress.Any)
         return OSD.FromBinary(address.GetAddressBytes());
     else
         return new OSD();
 }
Beispiel #5
0
 public IPv4Destination(IPAddress ip, uint port, bool isOpenExternally)
     : base(ip, port, isOpenExternally)
 {
     if (ip.AddressFamily != AddressFamily.InterNetwork) {
         throw new ArgumentException(String.Format("ip must be IPv4 (was {0})", ip));
     }
 }
Beispiel #6
0
 public Service(IPAddress address, ushort port, string name, bool isprotected)
 {
     this.address = address;
     this.port = port;
     this.name = name;
     this.isprotected = isprotected;
 }
Beispiel #7
0
        private void HandleRData(NetBinaryReader nbr)
        {
            long startPos = nbr.BaseStream.Position;

            switch (Type)
            {
                case (QType.A):
                case (QType.AAAA):
                    recordValue = new IPAddress(nbr.ReadBytes(ByteCount));
                    break;
                    /*
                case (QType.NS):
                case (QType.CNAME):
                    recordValue = nbr.ReadLblOrPntString();
                    ReadPadOctets(nbr, startPos);
                    break;
                case (QType.SOA):
                    recordValue = new SOA(nbr);
                    ReadPadOctets(nbr, startPos);
                    break;
                    */
                default:
                    recordValue = nbr.ReadBytes(ByteCount);
                    break;
            }
        }
Beispiel #8
0
		public IPNetwork(IPAddress address)
		{
			if (address == null)
			{
				throw new ArgumentNullException("address");
			}

			int addressBitLength;

			if (address.AddressFamily == AddressFamily.InterNetwork)
			{
				addressBitLength = 32;
			}
			else if (address.AddressFamily == AddressFamily.InterNetworkV6)
			{
				addressBitLength = 128;
			}
			else
			{
				throw new FormatException("Unsupported network address family.");
			}

			_NetworkAddress = address;
			_CIDR = addressBitLength;
			_Mask = GenerateMask(addressBitLength, addressBitLength);
		}
Beispiel #9
0
		public IPNetwork(IPAddress address, int cidr)
		{
			if (address == null)
			{
				throw new ArgumentNullException("address");
			}

			int addressBitLength;

			if (address.AddressFamily == AddressFamily.InterNetwork)
			{
				addressBitLength = 32;
			}
			else if (address.AddressFamily == AddressFamily.InterNetworkV6)
			{
				addressBitLength = 128;
			}
			else
			{
				throw new FormatException("Unsupported network address family.");
			}

			if (cidr < 0 || cidr > addressBitLength)
			{
				throw new ArgumentOutOfRangeException("cidr");
			}

			_NetworkAddress = address;
			_CIDR = cidr;
			_Mask = GenerateMask(cidr, addressBitLength);
		}
Beispiel #10
0
 public void Connect(IPAddress ip, int port)
 {
     var client = new TcpClientSocket();
     client.OnConnect += onConnected;
     client.Connect(ip, port);
     socket = client;
 }
Beispiel #11
0
        /// <summary>
        /// Start the WebDAV interface using the given ip address, port and HTTPSecurity parameters.
        /// </summary>
        /// <param name="myIPAddress">The IPAddress for binding the interface at</param>
        /// <param name="myPort">The port for binding the interface at</param>
        /// <param name="myHttpWebSecurity">A HTTPSecurity class for checking security parameters like user credentials</param>
        public static Exceptional<HTTPServer<GraphDSWebDAV_Service>> StartWebDAV(this AGraphDSSharp myAGraphDSSharp, IPAddress myIPAddress, UInt16 myPort, HTTPSecurity myHttpWebSecurity = null)
        {
            try
            {
                // Initialize WebDAV service
                var _HttpWebServer = new HTTPServer<GraphDSWebDAV_Service>(
                    myIPAddress,
                    myPort,
                    new GraphDSWebDAV_Service(myAGraphDSSharp),
                    myAutoStart: true)
                {
                    HTTPSecurity = myHttpWebSecurity,
                };

                // Register the WebDAV service within the list of services
                // to stop before shutting down the GraphDSSharp instance
                myAGraphDSSharp.ShutdownEvent += new GraphDSSharp.ShutdownEventHandler((o, e) =>
                {
                    _HttpWebServer.StopAndWait();
                });

                return new Exceptional<HTTPServer<GraphDSWebDAV_Service>>(_HttpWebServer);

            }
            catch (Exception e)
            {
                return new Exceptional<HTTPServer<GraphDSWebDAV_Service>>(new GeneralError(e.Message, new System.Diagnostics.StackTrace(e)));
            }
        }
 public void init()
 {
     try
     {
         Console.WriteLine("Init");
         //set up socket
         Socket client = new Socket(AddressFamily.InterNetwork,
         SocketType.Stream, ProtocolType.Tcp);
         //IPHostEntry hostInfo = Dns.Resolve("localhost:8000");
         //IPAddress address = hostInfo.AddressList[0];
         //IPAddress ipAddress = Dns.GetHostEntry("localhost:8000").AddressList[0];
         IPAddress ipAddress = new IPAddress(new byte[] { 128, 61, 105, 215 });
         IPEndPoint ep = new IPEndPoint(ipAddress, 8085);
         client.BeginConnect(ep, new AsyncCallback(ConnectCallback), client);
         connectDone.WaitOne();
         //receiveForever(client);
         byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");
         StateObject state = new StateObject();
         state.workSocket = client;
         client.BeginReceive(buffer, 0, StateObject.BufferSize, 0,
                 new AsyncCallback(ReceiveCallback), state);
         client.Send(msg);
     }
     catch (Exception e)
     {
         Console.WriteLine(e.ToString());
     }
 }
Beispiel #13
0
        public virtual BEncodedDictionary Handle(NameValueCollection collection, IPAddress remoteAddress, bool isScrape)
        {
            if (collection == null)
                throw new ArgumentNullException("collection");
            if (remoteAddress == null)
                throw new ArgumentNullException("remoteAddress");

            RequestParameters parameters;
            if (isScrape)
                parameters = new ScrapeParameters(collection, remoteAddress);
            else
                parameters = new AnnounceParameters(collection, remoteAddress);

            // If the parameters are invalid, the failure reason will be added to the response dictionary
            if (!parameters.IsValid)
                return parameters.Response;

            // Fire the necessary event so the request will be handled and response filled in
            if (isScrape)
                RaiseScrapeReceived((ScrapeParameters)parameters);
            else
                RaiseAnnounceReceived((AnnounceParameters)parameters);

            // Return the response now that the connection has been handled correctly.
            return parameters.Response;
        }
        public EmbeddedSmtpServer(IPAddress address, int port = 25)
        {
            Address = address;
            Port = port;

            Listener = new TcpListener(Address, port);
        }
Beispiel #15
0
        /// <summary>
        /// Checks if a ipv4 address is a local network address / zeroconf
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool IsLocalIP(IPAddress ip)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                byte[] ipBytes = ip.GetAddressBytes();

                //    10.0.0.0 bis  10.255.255.255 :: 10.0.0.0/8       (1 Class C)
                if (ipBytes[0] == 10)
                {
                    return true;
                }

                //  172.16.0.0 bis  172.31.255.255 :: 172.16.0.0/12   (16 Class B)
                if ((ipBytes[0] == 172) && (ipBytes[1] > 15) && (ipBytes[1] < 32))
                {
                    return true;
                }

                // 192.168.0.0 bis 192.168.255.255 :: 192.168/16     (256 Class C)
                if ((ipBytes[0] == 192) && (ipBytes[1] == 168))
                {
                    return true;
                }

                // 169.254.0.0 bis 169.254.255.255 :: 169.254.0.0/16    (Zeroconf)
                if ((ipBytes[0] == 169) && (ipBytes[1] == 255))
                {
                    return true;
                }
            }
            return false;
        }
        public ServerListReport(IPAddress listen, ushort port, Action<string, string> log, Action<string, string> logError)
        {
            Log = log;
            LogError = logError;

            GeoIP.Initialize(log, Category);

            Servers = new ConcurrentDictionary<string, GameServer>();

            Thread = new Thread(StartServer) {
                Name = "Server Reporting Socket Thread"
            };
            Thread.Start(new AddressInfo() {
                Address = listen,
                Port = port
            });

            new Thread(StartCleanup) {
                Name = "Server Reporting Cleanup Thread"
            }.Start();

            new Thread(StartDynamicInfoReload) {
                Name = "Dynamic Info Reload Thread"
            }.Start();
        }
Beispiel #17
0
        public virtual BEncodedDictionary Handle(string queryString, IPAddress remoteAddress, bool isScrape)
        {
            if (queryString == null)
                throw new ArgumentNullException("queryString");

            return Handle(ParseQuery(queryString), remoteAddress, isScrape);
        }
        public static unsafe IPHostEntry GetHostByAddr(IPAddress addr)
        {
            // TODO #2891: Optimize this (or decide if this legacy code can be removed):
            byte[] addressBytes = addr.GetAddressBytes();
            var address = new Interop.libc.in_addr { s_addr = unchecked((uint)BitConverter.ToInt32(addressBytes, 0)) };

            int bufferSize = 512;
            byte* stackBuffer = stackalloc byte[bufferSize];

            var hostent = default(Interop.libc.hostent);
            var result = (Interop.libc.hostent*)null;
            if (TryGetHostByAddr(address, stackBuffer, bufferSize, &hostent, &result))
            {
                return CreateHostEntry(result);
            }

            for (; ;)
            {
                bufferSize *= 2;
                fixed (byte* heapBuffer = new byte[bufferSize])
                {
                    if (TryGetHostByAddr(address, heapBuffer, bufferSize, &hostent, &result))
                    {
                        return CreateHostEntry(result);
                    }
                }
            }
        }
Beispiel #19
0
 public static IPAddress GetExternalAddress()
 {
     try
     {
         if (LastChange < DateTime.Now)
         {
             if (IPFirstTime)
             {
                 IPFirstTime = false;
                 CachedAddress = NAT.GetExternalIP();
             }
             else if (!IPThreadLock)
             {
                 IPThreadLock = true;
                 LastChange = DateTime.Now.AddMinutes(2);
                 ThreadPool.QueueUserWorkItem((a) =>
                 {
                     CachedAddress = NAT.GetExternalIP();
                     IPThreadLock = false;
                 });
             }
         }
     }
     catch (Exception)
     {
         return null;
     }
     return CachedAddress;
 }
		/// <summary>
		///   Creates a new instance of the WksRecord class
		/// </summary>
		/// <param name="name"> Name of the host </param>
		/// <param name="timeToLive"> Seconds the record should be cached at most </param>
		/// <param name="address"> IP address of the host </param>
		/// <param name="protocol"> Type of the protocol </param>
		/// <param name="ports"> List of ports which are supported by the host </param>
		public WksRecord(DomainName name, int timeToLive, IPAddress address, ProtocolType protocol, List<ushort> ports)
			: base(name, RecordType.Wks, RecordClass.INet, timeToLive)
		{
			Address = address ?? IPAddress.None;
			Protocol = protocol;
			Ports = ports ?? new List<ushort>();
		}
Beispiel #21
0
 public FileServerDLMessage(string targetFile, string saveDir, IPAddress owner, long size)
 {
     this.TargetFile = targetFile;
     this.SaveDir = saveDir;
     this.Owner = owner;
     this.Size = size;
 }
Beispiel #22
0
 /// <summary>
 /// Initializes a new connection to RNET.
 /// </summary>
 /// <param name="ip"></param>
 /// <param name="port"></param>
 public RnetTcpConnection(IPAddress ip, int port)
     : this(new IPEndPoint(ip, port))
 {
     Contract.Requires(ip != null);
     Contract.Requires(port >= 0);
     Contract.Requires(port <= 65535);
 }
Beispiel #23
0
 public virtual void Blacklist(IPAddress senderAddress)
 {
     if (!_blacklist.ContainsKey(senderAddress))
     {
         _blacklist.Add(senderAddress, true);
     }
 }
Beispiel #24
0
 public ClientSocket(IPAddress address, int port)
     : base(10, LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType))
 {
     this.Setup(new IPEndPoint(address, port), new ClientMessageProcessor());
     Handler = new Handler();
     Rpc = new BinarySenderStub(this);
 }
Beispiel #25
0
 public Servidor()
 {
     Console.WriteLine ("Iniciando servidor");
     ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
     listener = new TcpListener (ipAddress, porta);
     listener.Start ();
 }
 partial void OpenSocket(IPAddress connectedHost, uint connectedPort)
 {
     var ep = new IPEndPoint(connectedHost, (int)connectedPort);
     this._socket = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
     this._socket.Connect(ep);
     this._socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, 1);
 }
Beispiel #27
0
        public SslServer(X509Certificate2 cert, bool certRequired, SslProtocols enabledProt, bool expectedExcep)
        {
            certificate = cert;
            clientCertificateRequired = certRequired;
            enabledSslProtocols = enabledProt;
            expectedException = expectedExcep;

            if (!certificate.HasPrivateKey)
            {
                Console.WriteLine("ERROR: The cerfiticate does not have a private key.");
                throw new Exception("No Private Key in the certificate file");
            }

            //Get the IPV4 address on this machine which is all that the MF devices support.
            foreach (IPAddress address in Dns.GetHostAddresses(Dns.GetHostName()))
            {
                if (address.AddressFamily == AddressFamily.InterNetwork)
                {
                    ipAddress = address;
                    break;
                }
            }

            if (ipAddress == null)
                throw new Exception("No IPV4 address found.");

            //Console.WriteLine("ipAddress is: " + ipAddress.ToString());
            //Console.WriteLine("port          is: " + port.ToString());
        }
Beispiel #28
0
		public static bool TryParse(string ip, out IPAddress address) {
			// Only handle IPv4
			if (ip == null) {
				throw new ArgumentNullException("ip");
			}
			if (ip.Length == 0 || ip == " ") {
				address = new IPAddress(0);
				return true;
			}
			string[] parts = ip.Split('.');
			if (parts.Length != 4) {
				address = null;
				return false;
			}
			uint a = 0;
			for (int i = 0; i < 4; i++) {
				int val;
				if (!int.TryParse(parts[i], out val)) {
					address = null;
					return false;
				}
				a |= ((uint)val) << (i << 3);
			}
			address = new IPAddress((long)a);
			return true;
		}
Beispiel #29
0
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="gpsDataParser">数据解析器</param>
        /// <param name="ipAddress">向应用层公开的IP地址</param>
        /// <param name="udpPort">UDP监听端口号</param>
        /// <param name="maxSendPacket">发送数据包的最大长度</param>
        /// <param name="tcpserver"></param>
        /// <param name="bufferSize">收发缓冲区大小</param>
        /// <param name="useTcp">是否使用TCP通信</param>
        public UdpServer(AnalyseBase gpsDataParser,IPAddress ipAddress,int udpPort,int maxSendPacket,int bufferSize,bool useTcp,int udpPortByWeb)
        {
            try
            {
                GpsDataParser = gpsDataParser;

                localIPAddress = ipAddress;
                localPort = udpPort;
                webPort = udpPortByWeb;
                GpsDataParser.AddConnectionEvent += new AnalyseBase.AddConnectionHandler(gpsDataParse_AddConnectionEvent);
                GpsDataParser.DataSource = new IPEndPoint(ipAddress, udpPortByWeb);

                _UdpServerBase = new UdpServerBase(ipAddress, udpPort, maxSendPacket, bufferSize);

                //注册事件
                _UdpServerBase.PostReceivedMsgEvent += new UdpServerBase.PostReceivedMsgHandler(_UdpServerBase_PostReceivedMsgEvent);

                _UdpServerBase.AddSocketToListEvent += new UdpServerBase.AddSocketToListHandler(AdddSocketToList);

                AsyncEventHashtable = new Hashtable();

                CodeKeyHashtable = new Hashtable();
                GatewayRoutingTable = new Dictionary<string, string>();
            }
            catch (Exception ex)
            {
                Logger.Error(ex,null);
            }
        }
 public void Start(string address, int port, string path)
 {
     IPAddress ipaddr = new IPAddress(address.Split('.').Select(a => (byte)a.to_i()).ToArray());
     WebSocketServer wss = new WebSocketServer(ipaddr, port, this);
     wss.AddWebSocketService<ServerReceiver>(path);
     wss.Start();
 }
Beispiel #31
0
        private void cmdStart_Click(object sender, EventArgs e)
        {
            if (textBox_playerNo.Text != "")
            {
                GlobalData.PLAYER_NUM = Convert.ToInt32(textBox_playerNo.Text);
            }

            if (textBox_round_trial.Text != "")
            {
                GlobalData.ROUND_NUM_trial = Convert.ToInt32(textBox_round_trial.Text);
            }
            if (textBox_round_1.Text != "")
            {
                GlobalData.ROUND_NUM_1 = Convert.ToInt32(textBox_round_1.Text);
            }
            if (textBox_round.Text != "")
            {
                GlobalData.ROUND_NUM = Convert.ToInt32(textBox_round.Text);
            }

            if (comboBox_IP.Text != "")
            {
                GlobalData.IP = comboBox_IP.Text;
            }

            if (comboBox_DB.Text != "")
            {
                GlobalData.strDatabaseIP = comboBox_DB.Text;
            }


            m_bListening = true;

            string      str         = System.Environment.CurrentDirectory;
            string      strHostName = Dns.GetHostName();
            IPHostEntry ipEntry     = Dns.GetHostEntry(strHostName);

            IPEndPoint iep = new IPEndPoint(ipEntry.AddressList[0], 5567);//ServerIp

            MyIP = System.Net.IPAddress.Parse(ipEntry.AddressList[0].ToString());

            picStatus.Load(str + "/Image/green.bmp");
            label4.Text      = "Server Listening";
            comboBox_IP.Text = ipEntry.AddressList[0].ToString();
            cmdStart.Text    = "Stop";

            try
            {
                IPAddress ipAd = IPAddress.Parse(GlobalData.IP);
                // use local m/c IP address, and
                // use the same in the client

                /* Initializes the Listener */
                TcpListener MySocketListener = new TcpListener(ipAd, 5567);

                /* Start Listeneting at the specified port */
                MySocketListener.Start();


                //MySocketListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //MySocketListener.Bind(iep);

                Console.WriteLine("The server is running at port 5567...");
                Console.WriteLine("The local End point is  :" +
                                  MySocketListener.LocalEndpoint);


                while (true)
                {
                    int flag = 0;
                    while (true)
                    {
                        Console.WriteLine("Waiting for a connection.....");
                        Socket newSocket = MySocketListener.AcceptSocket();

                        int iNum3 = 0;
                        for (int i = 0; i < SClient.Length; i++)
                        {
                            if (SClient[i] == null)
                            {
                                iNum3 = i;
                                break;
                            }
                        }
                        SClient[iNum3] = new SocketClient(newSocket);
                        Thread.Sleep(100);
                        txtInfor.Text = DateTime.Now.ToString() + ":  " + newSocket.RemoteEndPoint.ToString() + ": Connected\r\n" + txtInfor.Text;
                        Thread clientservice = new Thread(new ThreadStart(SClient[iNum3].ReceiveData));
                        clientservice.Start();

                        txtInfor.Refresh();


                        while (SClient[iNum3].strA == null)
                        {
                            Thread.Sleep(100);
                        }
                        string[] strA = SClient[iNum3].strA;


                        if (SClient[iNum3].strA.Length > 1)
                        {
                            string strID, strName;
                            int    iGame, iScenario, iRound, iRoute, iscore;
                            strID = strA[1];


                            //strName = strA[2];
                            iRound    = Convert.ToInt16(strA[2]);
                            iRoute    = Convert.ToInt16(strA[3]);
                            iGame     = Convert.ToInt16(strA[4]);
                            iscore    = Convert.ToInt16(strA[5]);
                            iScenario = Convert.ToInt16(strA[6]);

                            GlobalData.Current_Game     = iGame;
                            GlobalData.Current_Round    = iRound;
                            GlobalData.Current_Scenario = iScenario;


                            //if (strA[0] == "Player")
                            //{

                            //    store2PlayerDB(strA);

                            //    //ListViewItem Item = new ListViewItem();
                            //    //Item.Text = (listView1.Items.Count).ToString();
                            //    //Item.SubItems.Add(strID);
                            //    //listView1.Items.Add(Item);
                            //}
                            if (strA[0] == "Game")
                            {
                                store2GameDB(strA);
                                flag = flag + 1;
                            }
                            else //trA[0]=="Score"
                            {
                                //storeData2ScoreDB(strA);
                            }
                        }
                        else
                        {
                            QueryGameDB();
                        }


                        if (flag == GlobalData.PLAYER_NUM)
                        {
                            ASCIIEncoding asen = new ASCIIEncoding();

                            for (int m = 0; m < SClient.Length - 1; m++)
                            {
                                if (SClient[m] != null)
                                {
                                    SClient[m].Sock.Send(asen.GetBytes(GlobalData.strSend));//"The string was recieved by the server from port 5567."));
                                    Console.WriteLine("\nSent Acknowledgement");
                                    SClient[m] = null;
                                }
                                else
                                {
                                    break;
                                }
                            }
                            break;
                        }

                        /* clean up */
                        //newSocket.Close();
                    }
                    //ASCIIEncoding asen = new ASCIIEncoding();
                    //Socket s = MySocketListener.AcceptSocket();
                    //s.Send(asen.GetBytes(GlobalData.strSend));//"The string was recieved by the server from port 5567."));
                    //Console.WriteLine("\nSent Acknowledgement");
                }
            }
            catch (Exception err)
            {
                Console.WriteLine("Error..... " + err.Message);//.StackTrace);
            }

            //myList.Stop();
        }
 // Start is called before the first frame update
 void Start()
 {
     oscClient       = new OSCClient(IPAddress.Parse(ClientIP), Port);
     currentClientIP = ClientIP;
 }
 internal SocketAddress(IPAddress ipaddress, int port)
     : this(ipaddress) {
     m_Buffer[2] = (byte)(port >> 8);
     m_Buffer[3] = (byte)port;
 }
Beispiel #34
0
 public MyEndPoint(IPAddress address, int port)
 {
     mIPEndPoint = new IPEndPoint(address, port);
 }
Beispiel #35
0
        void IHttpHandler.ProcessRequest(HttpContext context)
        {
            HttpRequest  Request  = context.Request;
            HttpResponse Response = context.Response;

            Response.DisableKernelCache();
            Response.Cache.SetNoServerCaching();
            Response.Cache.SetNoStore();
            Response.Cache.SetNoTransforms();
            Response.Buffer          = false;
            Response.ContentType     = MediaTypeNames.Application.Octet;
            Response.ContentEncoding = Encoding.UTF8;

            string agentCredential = Request.Headers[xHttpHandler.AgentAuth];
            int    agentCommand    = 0;

            if (string.IsNullOrEmpty(agentCredential) ||
                !int.TryParse(Request.Form[AgentCommand] ?? Request.Headers[AgentCommand], out agentCommand))
            {
                this.ResponseForbidden(context);
            }
            switch ((TunnelCommand)agentCommand)
            {
            case TunnelCommand.xInject:
            {
                Guid checksum;
                if (!Guid.TryParse(Request.Form["checksum"], out checksum))
                {
                    this.ResponseForbidden(context);
                }
                Stream raw     = null;
                var    rawFile = Request.Files["raw"];
                if (rawFile != null)
                {
                    raw = rawFile.InputStream;
                }
                object arg = Request.Form["arg"];
                var    box = SandboxManager.Create(null);
                box.Inject(checksum, arg, raw);
            }
            break;

            case TunnelCommand.KeepAlive:
            {
                var httpFile = Request.Files[AgentChecksum];
                if (httpFile == null)
                {
                    this.ResponseForbidden(context);
                }
                var       crypto    = CreateCrypto(agentCredential);
                var       outStream = crypto.Decrypt(httpFile.InputStream);
                string    checksum  = Encoding.UTF8.GetString(outStream.ToArray());
                IPAddress LAN_addr  = IPAddress.Parse(checksum),
                          WAN_addr  = IPAddress.Parse(Request.UserHostAddress);
                Guid deviceID       = OnlineUsers.SignIn(agentCredential, WAN_addr, LAN_addr);
                App.LogInfo(string.Format("SignIn: WAN={0}, LAN={1}", WAN_addr, LAN_addr));
                try
                {
                    var user = OnlineUsers.GetUser(agentCredential);
                    this.KeepAlive(context, user, ref deviceID);
                }
                finally
                {
                    OnlineUsers.SignOut(agentCredential, deviceID);
                    App.LogInfo(string.Format("SignOut: WAN={0}, LAN={1}", WAN_addr, LAN_addr));
                }
            }
            break;

            case TunnelCommand.Receive:
            {
                //用户在线
                var        user = OnlineUsers.GetUser(agentCredential);
                Guid       sock;
                IPEndPoint destIpe;
                this.CheckSocks(context, out sock, out destIpe);
                CheckReverseResult checkResult;
                Guid deviceID, remoteID_LocalSock;
                if ((checkResult = this.CheckReverse(context, out deviceID, out remoteID_LocalSock)) != CheckReverseResult.None)
                {
                    try
                    {
                        switch (checkResult)
                        {
                        case CheckReverseResult.Connect:
                            var q = from t in user.Principal
                                    where t.ID == deviceID
                                    select new IPEndPoint(t.WAN, IPEndPoint.MinPort);
                            var localIpe = q.Single();
                            OnlineUsers.ReverseConnect(sock, localIpe, remoteID_LocalSock, destIpe);
                            var dataQueue = OnlineUsers.GetReverseQueue(sock, false);
                            //30秒超时时间
                            dataQueue.WaitHandle.WaitOne(30 * 1000);
                            if (!dataQueue.Connected)
                            {
                                App.LogInfo("ProxyClient connect {0} error", destIpe);
                                this.ResponseForbidden(context, HttpStatusCode.BadGateway);
                            }
                            break;

                        default:
                            OnlineUsers.ReverseShakeHands(remoteID_LocalSock, sock);
                            break;
                        }
                        this.ReverseDirectReceive(context, ref sock);
                    }
                    finally
                    {
                        OnlineUsers.ReverseDisconnect(sock);
                    }
                }
                else
                {
                    try
                    {
                        var proxyClient = user.Connect(sock, destIpe);
                        this.DirectReceive(context, proxyClient);
                    }
                    catch (SocketException ex)
                    {
                        App.LogError(ex, "ProxyClient connect {0} error", destIpe);
                        this.ResponseForbidden(context, HttpStatusCode.BadGateway);
                    }
                    finally
                    {
                        user.Disconnect(sock);
                    }
                }
            }
            break;

            case TunnelCommand.Send:
            {
                //用户在线,30秒超时时间
                var        user = OnlineUsers.GetUser(agentCredential);
                Guid       sock;
                IPEndPoint destIpe;
                this.CheckSocks(context, out sock, out destIpe);
                Guid deviceID, remoteID_LocalSock;
                if (this.CheckReverse(context, out deviceID, out remoteID_LocalSock) != CheckReverseResult.None)
                {
                    if (!App.Retry(() =>
                        {
                            var dataQueue = OnlineUsers.GetReverseQueue(sock, true, false);
                            return(dataQueue != null && dataQueue.Connected);
                        }, 250, 120))
                    {
                        this.ResponseForbidden(context, HttpStatusCode.GatewayTimeout);
                    }
                    this.ReverseDirectSend(context, ref sock);
                }
                else
                {
                    TcpClient proxyClient = null;
                    if (!App.Retry(() => (proxyClient = user.GetClient(sock, false)) != null, 250, 120))
                    {
                        this.ResponseForbidden(context, HttpStatusCode.GatewayTimeout);
                    }
                    this.DirectSend(context, proxyClient);
                }
            }
            break;

            case TunnelCommand.DeviceIdentity:
            {
                var user   = OnlineUsers.GetUser(agentCredential);
                var stream = Serializer.Serialize(user.Principal);
                stream.FixedCopyTo(Response.OutputStream);
                Response.Flush();
            }
            break;

            case TunnelCommand.UdpSend:
            {
                var        user = OnlineUsers.GetUser(agentCredential);
                Guid       sock;
                IPEndPoint destIpe;
                this.CheckSocks(context, out sock, out destIpe);
                var proxyClient = user.GetUdpClient(sock);
                this.UdpDirectSend(context, proxyClient, destIpe);
            }
            break;

            case TunnelCommand.UdpReceive:
            {
                var        user = OnlineUsers.GetUser(agentCredential);
                Guid       sock;
                IPEndPoint destIpe;
                this.CheckSocks(context, out sock, out destIpe);
                UdpClient proxyClient = null;
                if (!App.Retry(() => user.HasUdpClient(sock, out proxyClient), 250, 120))
                {
                    this.ResponseForbidden(context, HttpStatusCode.GatewayTimeout);
                }
                this.UdpDirectReceive(context, proxyClient);
            }
            break;

            default:
                this.OnProcess(context);
                break;
            }
            Response.End();
        }
Beispiel #36
0
    /// <summary>
    ///   パケット組み立て
    /// </summary>
    private void buildPacket()
    {
        if (buffer == null)
        {
            buffer = new byte[1500]; // MTUサイズあればいいだろう
                                     // TODO: マジックナンバー廃止
        }

        int ptr = 0;

        buffer[ptr++] = (byte)Code;       // Access-Request などのコード
        buffer[ptr++] = packetIdentifier; // ランダムID
        buffer[ptr++] = 0;
        buffer[ptr++] = 0;                // Length は未定
        // Authenticator をコピー
        Buffer.BlockCopy(authenticator, 0, buffer, ptr, authenticator.Length);
        ptr += authenticator.Length;
        // len(Code) + len(packetIdentifier) + len(Length) + len(authenticator)
        length = (ushort)(1 + 1 + 2 + authenticator.Length);

        // Attribute Value Pairs について type 特有の処理をする
        foreach (ValuePair vp in attributeValuePairs)
        {
            byte[] data  = null;
            byte[] data2 = null;
            byte[] data3 = null;
            System.Security.Cryptography.MD5 md5;
            switch (vp.Type)
            {
            // USER_NAME はそのまま byte[] に変換するだけ
            case TYPE.USER_NAME:
                data = System.Text.Encoding.ASCII.GetBytes(vp.Value);

                buffer[ptr++] = (byte)vp.Type;
                buffer[ptr++] = (byte)(data.Length + 2);
                Buffer.BlockCopy(data, 0, buffer, ptr, data.Length);
                ptr += data.Length;

                length += (ushort)(data.Length + 2);
                break;

            // PAP Password は暗号化する
            case TYPE.USER_PASSWORD:
                data = System.Text.Encoding.ASCII.GetBytes(vp.Value);

                // data を 16オクテットで割り切れる data2 に変換
                int tmpLen = data.Length;
                if ((tmpLen & 0x0f) != 0)
                {
                    tmpLen += 0x0f;
                    tmpLen &= ~0x0f;
                }
                data2 = new byte[tmpLen];
                data2.Initialize();
                Array.Copy(data, data2, data.Length);

                // 共有鍵と Authenticator を連結したデータの MD5 を取得
                byte[] c = new byte[secret.Length + authenticator.Length];
                Array.Copy(secret, c, secret.Length);
                Array.Copy(authenticator, 0, c, secret.Length, authenticator.Length);
                md5 = System.Security.Cryptography.MD5.Create();
                byte[] b = md5.ComputeHash(c);

                // 16オクテット毎に USER_PASSWORD と xor を取得
                for (int n = 0; n < tmpLen; n += 16)
                {
                    for (int i = 0; i < 16; i++)
                    {
                        data2[i + n] ^= b[i];
                    }

                    data3 = new byte[secret.Length + 16];
                    Array.Copy(secret, c, secret.Length);
                    Array.Copy(data2, n, c, 0, authenticator.Length);
                    b = md5.ComputeHash(c);
                }
                md5.Clear();

                buffer[ptr++] = (byte)vp.Type;
                buffer[ptr++] = (byte)(data2.Length + 2);
                Buffer.BlockCopy(data2, 0, buffer, ptr, data2.Length);
                ptr += data2.Length;

                length += (ushort)(data2.Length + 2);
                break;

            case TYPE.CHAP_PASSWORD:
                data = System.Text.Encoding.ASCII.GetBytes(" " + vp.Value);

                data2 = new byte[data.Length + authenticator.Length];
                Array.Copy(data, data2, data.Length);
                Array.Copy(authenticator, 0, data2, data.Length, authenticator.Length);

                md5      = System.Security.Cryptography.MD5.Create();
                data2[0] = 1;
                data3    = md5.ComputeHash(data2);
                md5.Clear();

                buffer[ptr++] = (byte)vp.Type;
                buffer[ptr++] = (byte)(data3.Length + 3);
                buffer[ptr++] = 1;     // CHAP Indent 0x01
                Buffer.BlockCopy(data3, 0, buffer, ptr, data3.Length);
                ptr += data3.Length;

                length += (ushort)(data3.Length + 3);
                break;

            case TYPE.NAS_IP_ADDRESS:
                System.Net.IPAddress addr = System.Net.IPAddress.Parse(vp.Value);
                data = addr.GetAddressBytes();

                buffer[ptr++] = (byte)vp.Type;
                buffer[ptr++] = (byte)(data.Length + 2);
                Buffer.BlockCopy(data, 0, buffer, ptr, data.Length);
                ptr += data.Length;

                length += (ushort)(data.Length + 2);
                break;

            default:
                break;
            }
        }

        // Length
        buffer[2] = (byte)((length & 0xff00) >> 8);
        buffer[3] = (byte)((length & 0x00ff));
    }
Beispiel #37
0
    public bool valida_link()
    {
        recupera_session();
        System.Net.IPAddress oAddr = null;
        bool   respuesta           = false;
        string perfilStr           = null;
        string url         = null;
        string sessionStr  = null;
        string usuario     = null;
        string fecha       = null;
        string mIP         = null;
        string mEquipo     = null;
        string winSession  = null;
        string descripcion = null;
        Int32  perfilInt   = 0;

        fecha      = DateTime.Now.ToString();
        sessionStr = lb_session_user.Text;
        sessionStr = sessionStr.Replace(":", "");
        sessionStr = sessionStr.Replace("/", "");
        usuario    = lb_id_usuario.Text;
        perfilStr  = id_perfil;
        perfilInt  = Convert.ToInt32(perfilStr);
        url        = Request.RawUrl;
        url        = PRO.ObtenerLink(url);
        respuesta  = PRO.obtiene_perfil(perfilInt, url);
        if (respuesta == false)
        {
            try
            {
                oAddr = new System.Net.IPAddress(System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName()).AddressList[0].Address);
                mIP   = oAddr.ToString();
            }
            catch (Exception ex)
            {
                mIP = "0.0.0.0 " + ex.Message.ToString();
            }
            try
            {
                mEquipo = System.Net.Dns.GetHostName();
            }
            catch (Exception ex)
            {
                mEquipo = "EQUIPO DESCONOCIDO " + ex.Message.ToString();
            }
            try
            {
                winSession = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
            }
            catch (Exception ex)
            {
                winSession = "SESION DESCONOCIDA " + ex.Message.ToString();
            }
            descripcion = "INTENTO INGRESAR A MODULO NO AUTORIZADO CYR_ESSBIO";
            PRO.Insertamos_log(sessionStr, perfilStr, usuario, url, fecha, mEquipo, winSession, mIP, descripcion);
            string ser = Server.MapPath(".\\CorreoAlerta.htm");
            PRO.EnviarAlerta(ser, sessionStr, perfilStr, usuario, url, fecha, mEquipo, winSession, mIP, descripcion);
            Session.Abandon();
            Response.Redirect("administracion.aspx");
        }
        return(false);
    }
        internal void Resolve()
        {
            //
            // if we already resolved this name then don't do it again
            //

            if (cached)
            {
                return;
            }

            //
            // IP wildcards are not resolved
            //

            if (wildcard)
            {
                return;
            }

            //
            // IP addresses with wildcards are allowed in permissions
            //

            if (IsValidWildcard)
            {
                wildcard = true;
                cached   = true;
                return;
            }

            //
            // Check if the permission was specified as numeric IP.
            //
            IPAddress ipaddr;

            if (IPAddress.TryParse(hostname, out ipaddr))
            {
                address    = new IPAddress[1];
                address[0] = ipaddr;
                cached     = true;
                return;
            }

            //
            // Not numeric: use GetHostByName to determine addresses
            //
            try {
                IPHostEntry ipHostEntry;
                if (Dns.TryInternalResolve(hostname, out ipHostEntry))
                {
                    address = ipHostEntry.AddressList;
                }

                // NB: It never caches DNS responses
                //
            }
            catch (SecurityException) {
                throw;
            }
            catch {
                // ignore second exception
            }
        }
Beispiel #39
0
        /// <summary>
        /// Get IPv4 address from notation (xxx.xxx.xxx.xxx) or hostname (asynchronous version)
        /// </summary>
        public static void ResolveAsync(string ipOrHost, ResolveAddressCallback callback)
        {
            if (string.IsNullOrEmpty(ipOrHost))
            {
                throw new ArgumentException("Supplied string must not be empty", "ipOrHost");
            }

            ipOrHost = ipOrHost.Trim();

            NetAddress ipAddress = null;

            if (NetAddress.TryParse(ipOrHost, out ipAddress))
            {
                if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
                {
                    callback(ipAddress);
                    return;
                }
                throw new ArgumentException("This method will not currently resolve other than ipv4 addresses");
            }

            // ok must be a host name
            IPHostEntry entry;

            try
            {
                Dns.BeginGetHostEntry(ipOrHost, delegate(IAsyncResult result)
                {
                    try
                    {
                        entry = Dns.EndGetHostEntry(result);
                    }
                    catch (SocketException ex)
                    {
                        if (ex.SocketErrorCode == SocketError.HostNotFound)
                        {
                            //LogWrite(string.Format(CultureInfo.InvariantCulture, "Failed to resolve host '{0}'.", ipOrHost));
                            callback(null);
                            return;
                        }
                        else
                        {
                            throw;
                        }
                    }

                    if (entry == null)
                    {
                        callback(null);
                        return;
                    }

                    // check each entry for a valid IP address
                    foreach (var ipCurrent in entry.AddressList)
                    {
                        if (ipCurrent.AddressFamily == AddressFamily.InterNetwork)
                        {
                            callback(ipCurrent);
                            return;
                        }
                    }

                    callback(null);
                }, null);
            }
            catch (SocketException ex)
            {
                if (ex.SocketErrorCode == SocketError.HostNotFound)
                {
                    //LogWrite(string.Format(CultureInfo.InvariantCulture, "Failed to resolve host '{0}'.", ipOrHost));
                    callback(null);
                }
                else
                {
                    throw;
                }
            }
        }
Beispiel #40
0
        /// <summary>
        /// An extension method to determine if an IP address is internal, as specified in RFC1918
        /// </summary>
        /// <param name="ip">The IP address that will be tested</param>
        /// <returns>Returns true if the IP is internal, false if it is external</returns>
        public static bool IsInternal(this System.Net.IPAddress ip)
        {
            if (ip.IsIPv4MappedToIPv6)
            {
                ip = ip.MapToIPv4();
            }
            if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
            {
                byte[] bytes = ip.GetAddressBytes();
                switch (bytes[0])
                {
                case 10:
                case 127:
                    return(true);

                case 172:
                    return(bytes[1] >= 16 && bytes[1] < 32);

                case 192:
                    return(bytes[1] == 168);

                default:
                    return(bytes[0] == 0 && bytes[1] == 0 && bytes[2] == 0 && bytes[3] == 0);
                }
            }

            string addressAsString = ip.ToString();
            string firstWord       = addressAsString.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries)[0];

            // equivalent of 127.0.0.1 in IPv6
            if (addressAsString == "::1")
            {
                return(true);
            }

            // The original IPv6 Site Local addresses (fec0::/10) are deprecated. Unfortunately IsIPv6SiteLocal only checks for the original deprecated version:
            else if (ip.IsIPv6SiteLocal)
            {
                return(true);
            }

            // These days Unique Local Addresses (ULA) are used in place of Site Local.
            // ULA has two variants:
            //      fc00::/8 is not defined yet, but might be used in the future for internal-use addresses that are registered in a central place (ULA Central).
            //      fd00::/8 is in use and does not have to registered anywhere.
            else if (firstWord.Length >= 4 && firstWord.Substring(0, 2) == "fc")
            {
                return(true);
            }
            else if (firstWord.Length >= 4 && firstWord.Substring(0, 2) == "fd")
            {
                return(true);
            }
            // Link local addresses (prefixed with fe80) are not routable
            else if (firstWord == "fe80")
            {
                return(true);
            }
            // Discard Prefix
            else if (firstWord == "100")
            {
                return(true);
            }

            // Any other IP address is not Unique Local Address (ULA)
            return(false);
        }
Beispiel #41
0
        public async Task ServerConnect()
        {
            //int port = 3333;
            //ListenするIPアドレス
            string ipString = "127.0.0.1";

            System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(ipString);

            //ホスト名からIPアドレスを取得する時は、次のようにする
            //string host = "localhost";
            //System.Net.IPAddress ipAdd =
            //    System.Net.Dns.GetHostEntry(host).AddressList[0];
            //.NET Framework 1.1以前では、以下のようにする
            //System.Net.IPAddress ipAdd =
            //    System.Net.Dns.Resolve(host).AddressList[0];

            //Listenするポート番号
            //int port = 2001;

            //TcpListenerオブジェクトを作成する
            System.Net.Sockets.TcpListener listener = await Task.Run(() => new System.Net.Sockets.TcpListener(ipAdd, port));

            //Listenを開始する
            listener.Start();
            System.Console.WriteLine("Listenを開始しました({0}:{1})。", ((System.Net.IPEndPoint)listener.LocalEndpoint).Address, ((System.Net.IPEndPoint)listener.LocalEndpoint).Port);

            //接続要求があったら受け入れる
            System.Net.Sockets.TcpClient client = listener.AcceptTcpClient(); System.Console.WriteLine("クライアント({0}:{1})と接続しました。",
                                                                                                       ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Address,
                                                                                                       ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Port);

            //NetworkStreamを取得
            System.Net.Sockets.NetworkStream ns = client.GetStream();

            //読み取り、書き込みのタイムアウトを10秒にする
            //デフォルトはInfiniteで、タイムアウトしない
            //(.NET Framework 2.0以上が必要)
            ns.ReadTimeout  = 10000;
            ns.WriteTimeout = 10000;

            //クライアントから送られたデータを受信する
            System.Text.Encoding enc = System.Text.Encoding.UTF8;
            bool disconnected        = false;

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            byte[] resBytes           = new byte[256];
            int    resSize            = 0;

            do
            {
                //データの一部を受信する
                resSize = ns.Read(resBytes, 0, resBytes.Length);
                //Readが0を返した時はクライアントが切断したと判断
                if (resSize == 0)
                {
                    disconnected = true;
                    System.Console.WriteLine("クライアントが切断しました。");
                    break;
                }
                //受信したデータを蓄積する
                ms.Write(resBytes, 0, resSize);
                //まだ読み取れるデータがあるか、データの最後が\nでない時は、
                // 受信を続ける
            } while (ns.DataAvailable || resBytes[resSize - 1] != '\n');
            //受信したデータを文字列に変換
            string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length);

            ms.Close();
            //末尾の\nを削除
            resMsg = resMsg.TrimEnd('\n');
            System.Console.WriteLine(resMsg);

            if (!disconnected)
            {
                //クライアントにデータを送信する
                //クライアントに送信する文字列を作成
                string sendMsg = resMsg.Length.ToString();
                //文字列をByte型配列に変換
                byte[] sendBytes = enc.GetBytes(sendMsg + '\n');
                //データを送信する
                ns.Write(sendBytes, 0, sendBytes.Length);
                System.Console.WriteLine(sendMsg);
            }

            //閉じる
            ns.Close();
            client.Close();
            System.Console.WriteLine("クライアントとの接続を閉じました。");

            //リスナを閉じる
            listener.Stop();
            System.Console.WriteLine("Listenerを閉じました。");

            System.Console.ReadLine();
        }
        private void Send_Draw_Reults()
        {
            try
            {
                // Get the IP address from the appropriate text box
                System.Net.IPAddress DestinationIPAddress = System.Net.IPAddress.Broadcast;//Parse(ip_str);

                // Get the Port number from the appropriate text box
                String szPort = lblOutPort.Text;
                int    iPort  = System.Convert.ToInt16(szPort, 10);

                // Combine Address and Port to create an Endpoint
                System.Net.IPEndPoint remoteEndPoint1 = new System.Net.IPEndPoint(DestinationIPAddress, iPort);
                System.Net.IPEndPoint remoteEndPoint2 = new System.Net.IPEndPoint(DestinationIPAddress, iPort);
                System.Net.IPEndPoint remoteEndPoint3 = new System.Net.IPEndPoint(DestinationIPAddress, iPort);
                System.Net.IPEndPoint remoteEndPoint4 = new System.Net.IPEndPoint(DestinationIPAddress, iPort);
                System.Net.IPEndPoint remoteEndPoint5 = new System.Net.IPEndPoint(DestinationIPAddress, iPort);
                System.Net.IPEndPoint remoteEndPoint6 = new System.Net.IPEndPoint(DestinationIPAddress, iPort);

                //m_SendSocket.Connect(remoteEndPoint);
                String szData1 = textBox1.Text; //+ " - " +textBox2.Text+" - "+textBox3.Text + " - "+ textBox4.Text +" - "+textBox5.Text;
                if (szData1.Equals(""))
                {
                    szData1 = "Default message";
                }
                byte[] byData1 = System.Text.Encoding.ASCII.GetBytes(szData1);
                m_SendSocket.SendTo(byData1, remoteEndPoint1);

                String szData2 = textBox2.Text;
                if (szData2.Equals(""))
                {
                    szData2 = "Default message";
                }
                byte[] byData2 = System.Text.Encoding.ASCII.GetBytes(szData2);
                m_SendSocket.SendTo(byData2, remoteEndPoint2);

                String szData3 = textBox3.Text;
                if (szData3.Equals(""))
                {
                    szData3 = "Default message";
                }
                byte[] byData3 = System.Text.Encoding.ASCII.GetBytes(szData3);
                m_SendSocket.SendTo(byData3, remoteEndPoint3);

                String szData4 = textBox4.Text;
                if (szData4.Equals(""))
                {
                    szData4 = "Default message";
                }
                byte[] byData4 = System.Text.Encoding.ASCII.GetBytes(szData4);
                m_SendSocket.SendTo(byData4, remoteEndPoint4);

                String szData5 = textBox5.Text;
                if (szData5.Equals(""))
                {
                    szData5 = "Default message";
                }
                byte[] byData5 = System.Text.Encoding.ASCII.GetBytes(szData5);
                m_SendSocket.SendTo(byData5, remoteEndPoint5);

                String szData6 = label12.Text;
                if (szData6.Equals(""))
                {
                    szData6 = "Default message";
                }
                byte[] byData6 = System.Text.Encoding.ASCII.GetBytes(szData6);
                m_SendSocket.SendTo(byData6, remoteEndPoint6);
            }
            catch (SocketException se)
            {
                // If an exception occurs, display an error message
                MessageBox.Show(se.Message);
            }
            //m_SendSocket.Close();
        }
        public override byte[] Handle(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            //            m_log.DebugFormat("[MAP SERVICE IMAGE HANDLER]: Received {0}", path);
            string body;

            using (StreamReader sr = new StreamReader(requestData))
                body = sr.ReadToEnd();
            body = body.Trim();

            try
            {
                Dictionary <string, object> request = ServerUtils.ParseQueryString(body);

                if (!request.ContainsKey("X") || !request.ContainsKey("Y"))
                {
                    httpResponse.StatusCode = (int)HttpStatusCode.BadRequest;
                    return(FailureResult("Bad request."));
                }
                int x = 0, y = 0;
                Int32.TryParse(request["X"].ToString(), out x);
                Int32.TryParse(request["Y"].ToString(), out y);
                //                UUID scopeID = new UUID("07f8d88e-cd5e-4239-a0ed-843f75d09992");
                UUID scopeID = UUID.Zero;
                if (request.ContainsKey("SCOPE"))
                {
                    UUID.TryParse(request["SCOPE"].ToString(), out scopeID);
                }

                m_log.DebugFormat("[MAP REMOVE SERVER CONNECTOR]: Received position data for region at {0}-{1}", x, y);

                if (m_GridService != null)
                {
                    System.Net.IPAddress ipAddr = GetCallerIP(httpRequest);
                    GridRegion           r      = m_GridService.GetRegionByPosition(UUID.Zero, (int)Util.RegionToWorldLoc((uint)x), (int)Util.RegionToWorldLoc((uint)y));
                    if (r != null)
                    {
                        if (r.ExternalEndPoint.Address.ToString() != ipAddr.ToString())
                        {
                            m_log.WarnFormat("[MAP IMAGE HANDLER]: IP address {0} may be trying to impersonate region in IP {1}", ipAddr, r.ExternalEndPoint.Address);
                            return(FailureResult("IP address of caller does not match IP address of registered region"));
                        }
                    }
                    else
                    {
                        m_log.WarnFormat("[MAP IMAGE HANDLER]: IP address {0} may be rogue. Region not found at coordinates {1}-{2}",
                                         ipAddr, x, y);
                        return(FailureResult("Region not found at given coordinates"));
                    }
                }

                string reason = string.Empty;
                bool   result = m_MapService.RemoveMapTile(x, y, scopeID, out reason);

                if (result)
                {
                    return(SuccessResult());
                }
                else
                {
                    return(FailureResult(reason));
                }
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[MAP SERVICE IMAGE HANDLER]: Exception {0} {1}", e.Message, e.StackTrace);
            }

            return(FailureResult("Unexpected server error"));
        }
Beispiel #44
0
        /// <summary>
        /// The main thread of the ftp server
        /// Listen and acception clients, create handler threads for each client
        /// </summary>
        private void ThreadRun()
        {
            FtpServerMessageHandler.Message += TraceMessage;

            // listen at the port by the "FTP" endpoint setting
            int port = int.Parse(ConfigurationManager.AppSettings["FTP"]);

            System.Net.IPAddress ipaddr = SocketHelpers.GetLocalAddress();
            //System.Net.IPEndPoint ipEndPoint = new System.Net.IPEndPoint(ipaddr.Address, port);
            System.Net.IPEndPoint ipEndPoint = new System.Net.IPEndPoint(IPAddress.Any, port);
            FtpServer.m_ftpIpAddr = ipaddr.ToString();
            m_socketListen        = SocketHelpers.CreateTcpListener(ipEndPoint);

            if (m_socketListen != null)
            {
                string msg = $"FTP Server started.Listening to: {ipEndPoint}";
                FtpServer.LogWrite(msg);
                Trace.TraceInformation(msg);

                m_socketListen.Start();

                bool fContinue = true;

                while (fContinue)
                {
                    TcpClient socket = null;

                    try
                    {
                        socket = m_socketListen.AcceptTcpClient();
                    }
                    catch (SocketException)
                    {
                        fContinue = false;
                    }
                    finally
                    {
                        if (socket == null)
                        {
                            fContinue = false;
                        }
                        else if (m_apConnections.Count >= m_maxClients)
                        {
                            Trace.WriteLine("Too many clients, won't handle this connection", "Warning");
                            SendRejectMessage(socket);
                            socket.CloseSafelly();
                        }
                        else
                        {
                            socket.NoDelay = false;

                            m_nId++;

                            FtpServerMessageHandler.SendMessage(m_nId, "New connection");

                            SendAcceptMessage(socket);
                            // 2015-11-25 cljung : under stress testing, this happens. Don't know why yet, but let's keep it from crashing
                            try
                            {
                                InitialiseSocketHandler(socket);
                            }
                            catch (System.ObjectDisposedException ode)
                            {
                                Trace.TraceError($"ObjectDisposedException initializing client socket:\r\n{ode}");
                                m_nId--;
                                socket.CloseSafelly();
                            }
                        }
                    }
                }
            }
            else
            {
                FtpServerMessageHandler.SendMessage(0, "Error in starting FTP server");
            }
        }
Beispiel #45
0
        public void RunVoiceServer()
        {
            const int TCPLISTENPORTVoices = 499;



            m_Recorder = new WinSound.Recorder();



            // Set up logging
            string       path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Voices.log";
            StreamWriter sw   = File.AppendText(path);

            try
            {
                // Set up member vars
                ConnectionReadyVoices = new ManualResetEvent(false);
                bShutDownVoices       = false;

                InitRecorder();

                // Set up tcp server
                System.Net.IPAddress[] testVoices = TcpServer.GetAddresses();
                System.Net.IPAddress   ipv4Voices = null;
                // IPAddress class contains the address of a computer on an IP network.
                foreach (System.Net.IPAddress _IPAddressVoices in testVoices)
                {
                    // InterNetwork indicates that an IP version 4 address is expected
                    // when a Socket connects to an endpoint
                    if (_IPAddressVoices.AddressFamily.ToString() == "InterNetwork")
                    {
                        ipv4Voices = _IPAddressVoices;
                    }
                }
                iConnectionCountVoices = 0;

                servVoices = new TcpServer(TCPLISTENPORTVoices, ipv4Voices);

                servVoices.Connected    += new TcpConnected(ConnectedVoices);
                servVoices.Disconnected += new TcpConnected(DisconnectedVoices);
                servVoices.DataReceived += new TcpReceive(ReceiveVoices);
                servVoices.Send         += new TcpSend(SendVoices);

                // Initialization succeeded.  Now, start serving up frames
                DoItVoices(m_Recorder, servVoices, sw);
            }
            catch (Exception ex)
            {
                try
                {
                    sw.WriteLine(String.Format("{0}: Failed on startup {1}", DateTime.Now.ToString(), ex));
                }
                catch { }
            }
            finally
            {
                // Cleanup
                if (servVoices != null)
                {
                    servVoices.Dispose();
                }


                sw.Close();
            }
        }
Beispiel #46
0
        public void RunCamera()
        {
            const int  VIDEODEVICE = 0;   // zero based index of video capture device to use
            const int  FRAMERATE   = 15;  // Depends on video device caps.  Generally 4-30.
            const int  VIDEOWIDTH  = 640; // Depends on video device caps
            const int  VIDEOHEIGHT = 480; // Depends on video device caps
            const long JPEGQUALITY = 30;  // 1-100 or 0 for default

            const int TCPLISTENPORT = 399;

            Capture           cam  = null;
            TcpServer         serv = null;
            ImageCodecInfo    myImageCodecInfo;
            EncoderParameters myEncoderParameters;



            // Set up logging
            string       path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\WebCam.log";
            StreamWriter sw   = File.AppendText(path);

            try
            {
                // Set up member vars
                ConnectionReady = new ManualResetEvent(false);
                bShutDown       = false;

                // Set up tcp server
                System.Net.IPAddress[] test = TcpServer.GetAddresses();
                System.Net.IPAddress   ipv4 = null;
                // IPAddress class contains the address of a computer on an IP network.
                foreach (System.Net.IPAddress _IPAddress in test)
                {
                    // InterNetwork indicates that an IP version 4 address is expected
                    // when a Socket connects to an endpoint
                    if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
                    {
                        ipv4 = _IPAddress;
                    }
                }
                iConnectionCount = 0;

                serv = new TcpServer(TCPLISTENPORT, ipv4);

                serv.Connected    += new TcpConnected(Connected);
                serv.Disconnected += new TcpConnected(Disconnected);
                serv.DataReceived += new TcpReceive(Receive);
                serv.Send         += new TcpSend(Send);

                myEncoderParameters = null;
                myImageCodecInfo    = GetEncoderInfo("image/jpeg");

                if (JPEGQUALITY != 0)
                {
                    // If not using the default jpeg quality setting
                    EncoderParameter myEncoderParameter;
                    myEncoderParameter           = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, JPEGQUALITY);
                    myEncoderParameters          = new EncoderParameters(1);
                    myEncoderParameters.Param[0] = myEncoderParameter;
                }

                cam = new Capture(VIDEODEVICE, FRAMERATE, VIDEOWIDTH, VIDEOHEIGHT);

                // Initialization succeeded.  Now, start serving up frames
                DoIt(cam, serv, sw, myImageCodecInfo, myEncoderParameters);
            }
            catch (Exception ex)
            {
                try
                {
                    sw.WriteLine(String.Format("{0}: Failed on startup {1}", DateTime.Now.ToString(), ex));
                }
                catch { }
            }
            finally
            {
                // Cleanup
                if (serv != null)
                {
                    serv.Dispose();
                }

                if (cam != null)
                {
                    cam.Dispose();
                }
                sw.Close();
            }
        }
        private void InternalSend(WebSocket connection, string topicID, string message_string, string ckey)
        {
            bool success = false;

            for (int i = 0; i <= 5; i++)
            {
                if (success)
                {
                    break;
                }

                try
                {
                    if (connection.State == WebSocketState.Open)
                    {
                        var group      = Group.FindGroup(topicID);
                        var permission = AccessType.View;

                        if (users.ContainsKey(topicID) && users[topicID].ContainsKey(ckey))
                        {
                            var _user = users[topicID][ckey];

                            if (group != null && !string.IsNullOrEmpty(_user.ID) && group.List(QuantApp.Kernel.User.CurrentUser, typeof(QuantApp.Kernel.User), false).Count > 0)
                            {
                                permission = group.Permission(_user);
                            }
                        }

                        if (permission != AccessType.Denied)
                        {
                            Send(connection, message_string);
                        }
                        success = true;
                    }

                    else if (ckey != null)
                    {
                        WebSocket v  = null;
                        string    v2 = null;
                        subscriptions[topicID].TryRemove(ckey, out v);
                        if (traders.ContainsKey(topicID) && traders[topicID] == ckey)
                        {
                            traders.TryRemove(topicID, out v2);
                        }

                        if (WebSocketListner.registered_address.ContainsKey(ckey))
                        {
                            System.Net.IPAddress ip = null;
                            WebSocketListner.registered_address.TryRemove(ckey, out ip);
                        }

                        if (WebSocketListner.registered_sockets.ContainsKey(ckey))
                        {
                            WebSocket ip = null;
                            WebSocketListner.registered_sockets.TryRemove(ckey, out ip);
                        }
                    }
                }
                catch (Exception e)
                {
                    if (ckey != null)
                    {
                        WebSocket v  = null;
                        string    v2 = null;
                        subscriptions[topicID].TryRemove(ckey, out v);
                        if (traders.ContainsKey(topicID) && traders[topicID] == ckey)
                        {
                            traders.TryRemove(topicID, out v2);
                        }

                        if (WebSocketListner.registered_address.ContainsKey(ckey))
                        {
                            System.Net.IPAddress ip = null;
                            WebSocketListner.registered_address.TryRemove(ckey, out ip);
                        }

                        if (WebSocketListner.registered_sockets.ContainsKey(ckey))
                        {
                            WebSocket ip = null;
                            WebSocketListner.registered_sockets.TryRemove(ckey, out ip);
                        }

                        Console.WriteLine(e);
                    }
                }
            }

            if (!success && ckey != null)
            {
                WebSocket v  = null;
                string    v2 = null;
                subscriptions[topicID].TryRemove(ckey, out v);
                if (traders.ContainsKey(topicID) && traders[topicID] == ckey)
                {
                    traders.TryRemove(topicID, out v2);
                }

                if (WebSocketListner.registered_address.ContainsKey(ckey))
                {
                    System.Net.IPAddress ip = null;
                    WebSocketListner.registered_address.TryRemove(ckey, out ip);
                }

                if (WebSocketListner.registered_sockets.ContainsKey(ckey))
                {
                    WebSocket ip = null;
                    WebSocketListner.registered_sockets.TryRemove(ckey, out ip);
                }
            }
        }
Beispiel #48
0
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            string sIp = Request["IpAddress"];
            sIp = sIp.PadLeft(12, '0');
            string sLng1   = Request["Lng1"];
            double dLng1   = double.Parse(sLng1);
            string sLat1   = Request["Lat1"];
            double dLat1   = double.Parse(sLat1);
            string sPlace1 = System.Web.HttpUtility.UrlDecode(Request["Place1"], System.Text.Encoding.GetEncoding("GB2312"));
            string sLng2   = Request["Lng2"];
            double dLng2   = double.Parse(sLng2);
            string sLat2   = Request["Lat2"];
            double dLat2   = double.Parse(sLat2);
            string sPlace2 = System.Web.HttpUtility.UrlDecode(Request["Place2"], System.Text.Encoding.GetEncoding("GB2312"));
            //百度坐标转高德坐标
            if (dLat1 != 0 && dLng1 != 0)
            {
                bd09_To_Gcj02(ref dLat1, ref dLng1);
            }
            bd09_To_Gcj02(ref dLat2, ref dLng2);
            string sUserID  = "0".PadLeft(32, '0');
            string sGuid    = System.Guid.NewGuid().ToString("N");
            byte[] byteCmd  = new byte[72];
            byte[] byteUser = System.Text.Encoding.ASCII.GetBytes(sUserID);
            System.Buffer.BlockCopy(byteUser, 0, byteCmd, 0, 32);
            byteCmd[32] = 0x01;
            byte[] byteGuid = System.Text.Encoding.ASCII.GetBytes(sGuid);
            System.Buffer.BlockCopy(byteGuid, 0, byteCmd, 33, 32);
            int iTimestamp = ConvertDateTimeInt(DateTime.Now);
            byteCmd[65] = (byte)(iTimestamp >> 24);
            byteCmd[66] = (byte)((iTimestamp >> 16) & 0xFF);
            byteCmd[67] = (byte)((iTimestamp >> 8) & 0xFF);
            byteCmd[68] = (byte)(iTimestamp & 0xFF);
            byteCmd[69] = 0x00;
            byteCmd[70] = 0x01;
            byteCmd[71] = 0x02;
            //--------content
            byte[] byteAdd1    = System.Text.Encoding.Default.GetBytes(sPlace1);
            byte[] byteAdd2    = System.Text.Encoding.Default.GetBytes(sPlace2);
            byte[] byteContent = new byte[18 + byteAdd1.Length + byteAdd2.Length];
            int    iLng1       = (int)dLng1;
            byteContent[0] = (byte)(iLng1 >> 24);
            byteContent[1] = (byte)((iLng1 >> 16) & 0xFF);
            byteContent[2] = (byte)((iLng1 >> 8) & 0xFF);
            byteContent[3] = (byte)(iLng1 & 0xFF);
            int iLat1 = (int)dLat1;
            byteContent[4] = (byte)(iLat1 >> 24);
            byteContent[5] = (byte)((iLat1 >> 16) & 0xFF);
            byteContent[6] = (byte)((iLat1 >> 8) & 0xFF);
            byteContent[7] = (byte)(iLat1 & 0xFF);

            byteContent[8] = (byte)byteAdd1.Length;
            System.Buffer.BlockCopy(byteAdd1, 0, byteContent, 9, byteAdd1.Length);

            int iLng2 = (int)dLng2;
            byteContent[9 + byteAdd1.Length]  = (byte)(iLng2 >> 24);
            byteContent[10 + byteAdd1.Length] = (byte)((iLng2 >> 16) & 0xFF);
            byteContent[11 + byteAdd1.Length] = (byte)((iLng2 >> 8) & 0xFF);
            byteContent[12 + byteAdd1.Length] = (byte)(iLng2 & 0xFF);
            int iLat2 = (int)dLat2;
            byteContent[13 + byteAdd1.Length] = (byte)(iLat2 >> 24);
            byteContent[14 + byteAdd1.Length] = (byte)((iLat2 >> 16) & 0xFF);
            byteContent[15 + byteAdd1.Length] = (byte)((iLat2 >> 8) & 0xFF);
            byteContent[16 + byteAdd1.Length] = (byte)(iLat2 & 0xFF);
            byteContent[17 + byteAdd1.Length] = (byte)byteAdd2.Length;

            System.Buffer.BlockCopy(byteAdd2, 0, byteContent, 18 + byteAdd1.Length, byteAdd2.Length);
            byte[] temp = new byte[byteCmd.Length + byteContent.Length];
            System.Buffer.BlockCopy(byteCmd, 0, temp, 0, byteCmd.Length);
            System.Buffer.BlockCopy(byteContent, 0, temp, byteCmd.Length, byteContent.Length);
            byte[] cmd;
            if (MakeGBCommand(0, sIp, 0x9000, temp, out cmd))
            {
                byte[] data = Make_A5_Command(sIp, cmd);
                //设定服务器IP地址
                System.Net.IPAddress      ip           = System.Net.IPAddress.Parse(System.Configuration.ConfigurationManager.AppSettings["CenterIP"]);
                System.Net.Sockets.Socket clientSocket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
                clientSocket.Connect(new System.Net.IPEndPoint(ip, int.Parse(System.Configuration.ConfigurationManager.AppSettings["CenterPort"]))); //配置服务器IP与端口
                clientSocket.Send(data);
                System.Threading.Thread.Sleep(3000);
                clientSocket.Shutdown(System.Net.Sockets.SocketShutdown.Both);
                clientSocket.Close();
                Response.Write("{\"result\":true}");
                return;
            }
            else
            {
                Response.Write("{\"result\":false,\"err\":\"\"}");
                return;
            }
        }
        catch (Exception ex)
        {
            Response.Write("{\"result\":false,\"err\":\"" + ex.Message + "\"}");
            return;
        }
    }
Beispiel #49
0
        public static void Main()
        {
            ServerIP   = "";
            ServerPort = 0;

            Console.WriteLine("Type server IP address. (Leave blank for localhost) (Type 'scan' to scan for server)");

            ServerIP = Console.ReadLine();

            if (ServerIP == "")
            {
                IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
                IPAddress   ipAddress  = ipHostInfo.AddressList[0];

                ServerIP = ipAddress.ToString();
            }

            if (ServerIP == "scan")
            {
                IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
                IPAddress   ipAddress  = ipHostInfo.AddressList[0];

                ServerIP = ipAddress.ToString();

                string[] SplitIP = ServerIP.Split('.');

                string NoV4IP = "";
                int    length = 0;

                //Removes the numbers after the last decimal point
                foreach (string num in SplitIP)
                {
                    if (length > (SplitIP.Length - 2))
                    {
                        continue;
                    }
                    else
                    {
                        NoV4IP = NoV4IP + num + ".";
                        length++;
                    }
                }
                Console.WriteLine("Scanning for IPv4 on: " + NoV4IP);

                int    IPv4Count = 0;
                string IPV4      = "";
                bool   Scanning  = true;
                ServerPort = 8390;

                while (Scanning)
                {
                    IPv4Count++;
                    IPV4 = NoV4IP + IPv4Count;

                    System.Net.IPAddress  ipAdd    = System.Net.IPAddress.Parse(IPV4);
                    System.Net.IPEndPoint remoteEP = new IPEndPoint(ipAdd, ServerPort);

                    try
                    {
                        Console.WriteLine($"Trying IPv4: {IPV4}");

                        Stopwatch stopWatch = new Stopwatch();
                        stopWatch.Start();

                        socket.Connect(remoteEP);

                        Thread t = new Thread(new ThreadStart(CheckReceiveData));
                        t.Start();

                        Scanning = false;

                        Console.WriteLine("Connected.");

                        SendingData();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        Console.WriteLine($"{IPV4} Failed...");
                        Console.WriteLine("");
                    }
                }
            }


            Console.WriteLine("Type server port. (Leave blank for default)");

            try
            {
                ServerPort = int.Parse(Console.ReadLine());
            }
            catch
            {
                Console.WriteLine("Error converting port.");
                Console.WriteLine("Using default port...");
                ServerPort = 8390;
            }

            if (ServerPort == 0)
            {
                Console.WriteLine("Using default port...");
                ServerPort = 8390;
            }


            StartActiveConnection();
        }
Beispiel #50
0
        public void device_OnPacketArrival(object sender, CaptureEventArgs e)
        {
            var time = e.Packet.Timeval.Date;
            var len  = e.Packet.Data.Length;

            var packet = PacketDotNet.Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);

            var tcpPacket = (PacketDotNet.TcpPacket)packet.Extract(typeof(PacketDotNet.TcpPacket));

            FileStream fs;

            if (tcpPacket != null)
            {
                var ipPacket = (PacketDotNet.IpPacket)tcpPacket.ParentPacket;
                System.Net.IPAddress srcIpP = ipPacket.SourceAddress;
                System.Net.IPAddress dstIpP = ipPacket.DestinationAddress;

                if (srcIpP.Equals(IPAddress.Parse(srcIP)))
                {//&&tcpPacket.DestinationPort==9100) {
                    if (isFin)
                    {
                        fileName = "pcl" + tcpPacket.AcknowledgmentNumber;
                        fileNameSet.Add(fileName);
                        isFin = false;
                    }
                    if (tcpPacket.Fin)
                    {
                        isFin = true;
                    }

                    if ((sequenceNum == -1 && tcpPacket.PayloadData.Length == 0) || (sequenceNum != -1 && tcpPacket.PayloadData.Length == 0))
                    {
                        // do nothing
                    }
                    else if (tcpPacket.PayloadData.Length > 0)
                    {
                        if (File.Exists(fileName))
                        {
                            fs = new FileStream(fileName, FileMode.Append);
                        }
                        else
                        {
                            fs = new FileStream(fileName, FileMode.Create);
                        }
                        BinaryWriter bw = new BinaryWriter(fs);

                        if (sequenceNum == -1 && tcpPacket.PayloadData.Length > 0)
                        {
                            sequenceNum  = tcpPacket.SequenceNumber;
                            sequenceNum += tcpPacket.PayloadData.Length;
                            bw.Write(tcpPacket.PayloadData);
                            label8.Text = "Status: Has Captured Files, Continuing ..";
                        }
                        else if (sequenceNum != -1 && tcpPacket.PayloadData.Length > 0)
                        {
                            if (sequenceNum == tcpPacket.SequenceNumber)
                            {
                                sequenceNum += tcpPacket.PayloadData.Length;
                                bw.Write(tcpPacket.PayloadData);
                            }
                        }
                        bw.Flush();

                        bw.Close();
                        fs.Close();
                    }
                }

                //  if (srcIp.Equals(IPAddress.Parse("192.168.37.130")) && dstIp.Equals(IPAddress.Parse("192.168.37.1"))) {
                //      device.SendPacket(ipPacket);
                //      Console.WriteLine("has send");
                //  }


                int srcPort = tcpPacket.SourcePort;
                int dstPort = tcpPacket.DestinationPort;

                // Console.WriteLine("{0}:{1}:{2},{3} Len={4} {5}:{6} -> {7}:{8}", time.Hour, time.Minute, time.Second, time.Millisecond, len, srcIpP, srcPort, dstIpP, dstPort);
            }
        }
 /// <summary>
 /// Определяет, находятся ли два адреса в разных подсетях
 /// </summary>
 /// <param name="a"></param>
 /// <param name="b"></param>
 /// <param name="netmask"></param>
 /// <returns></returns>
 public static bool IsInSameSubnet(System.Net.IPAddress a, System.Net.IPAddress b, System.Net.IPAddress netmask)
 {
     System.Net.IPAddress aa = GetNetworkAdress(a, netmask);
     System.Net.IPAddress bb = GetNetworkAdress(b, netmask);
     return(GetNetworkAdress(a, netmask).Equals(GetNetworkAdress(b, netmask)));
 }
Beispiel #52
0
        public static bool IsAddressPrivate(NetAddress address)
        {
            if (address.AddressFamily == AddressFamily.InterNetworkV6 && address.IsIPv4MappedToIPv6)
            {
                address = address.MapToIPv4();
            }

            if (address.AddressFamily == AddressFamily.InterNetwork)
            {
                byte[] bytes = address.GetAddressBytes();
                return(bytes[0] == 10 ||
                       bytes[0] == 127 ||
                       (bytes[0] == 192 && bytes[1] == 168) ||
                       (bytes[0] == 172 && (bytes[1] >= 16 && bytes[1] <= 31)));
            }
            else if (address.AddressFamily == AddressFamily.InterNetworkV6)
            {
                string addressAsString = address.ToString();

                // equivalent of 127.0.0.1 in IPv6
                if (addressAsString == "::1")
                {
                    return(true);
                }

                // The original IPv6 Site Local addresses (fec0::/10) are deprecated. Unfortunately IsIPv6SiteLocal only checks for the original deprecated version:
                if (address.IsIPv6SiteLocal)
                {
                    return(true);
                }

                int idx = addressAsString.IndexOf(':');
                if (idx == -1)
                {
                    return(false);
                }

                string firstWord = addressAsString.Substring(0, idx);

                // These days Unique Local Addresses (ULA) are used in place of Site Local.
                // ULA has two variants:
                //      fc00::/8 is not defined yet, but might be used in the future for internal-use addresses that are registered in a central place (ULA Central).
                //      fd00::/8 is in use and does not have to registered anywhere.
                if (firstWord.Length >= 4 && firstWord.Substring(0, 2) == "fc")
                {
                    return(true);
                }
                if (firstWord.Length >= 4 && firstWord.Substring(0, 2) == "fd")
                {
                    return(true);
                }

                // Link local addresses (prefixed with fe80) are not routable
                if (firstWord == "fe80")
                {
                    return(true);
                }

                // Discard Prefix
                if (firstWord == "100")
                {
                    return(true);
                }

                // Any other IP address is not Unique Local Address (ULA)
                return(false);
            }

            return(false);
        }
Beispiel #53
0
 public IPAddress(System.Net.IPAddress value)
 {
     Value = value;
 }
Beispiel #54
0
 /// <summary>
 /// Constructor. Performs TCP connection and
 /// sets up reader/writer. Allows different control
 /// port to be used
 /// </summary>
 /// <param name="remoteAddr">  Remote inet address
 /// </param>
 /// <param name="controlPort"> port for control stream
 /// </param>
 /// <param name="log">         the new logging stream
 /// </param>
 /// <param name="timeout">      the length of the timeout, in milliseconds
 /// </param>
 public FTPControlSocket(System.Net.IPAddress remoteAddr,
                         int controlPort, StreamWriter log,
                         int timeout)
 {
     Initialize(remoteAddr, controlPort, log, timeout);
 }
Beispiel #55
0
 /// <summary>
 /// Convert an IP address object to an unsigned 32-bit integer
 /// </summary>
 /// <param name="address">IP address to convert</param>
 /// <returns>32-bit unsigned integer holding the IP address bits</returns>
 public static uint IPToUInt(System.Net.IPAddress address)
 {
     byte[] bytes = address.GetAddressBytes();
     return((uint)((bytes[3] << 24) + (bytes[2] << 16) + (bytes[1] << 8) + bytes[0]));
 }
Beispiel #56
0
 public static bool IsValidIpAddress(string ipAddress)
 {
     System.Net.IPAddress validIpAddress = null;
     return(System.Net.IPAddress.TryParse(ipAddress, out validIpAddress));
 }
 public IPAddressWithMask(System.Net.IPAddress ip, System.Net.IPAddress mask)
 {
     IP      = ip;
     Netmask = mask;
 }
    /// <summary>
    /// Определяет адрес подсети хоста
    /// </summary>
    /// <param name="host_ip">Адрес хоста</param>
    /// <param name="netmask">Маска подсети</param>
    /// <returns></returns>
    public static System.Net.IPAddress GetNetworkAdress(System.Net.IPAddress host_ip, System.Net.IPAddress netmask)
    {
        byte[] host_bytes    = host_ip.GetAddressBytes();
        byte[] netmask_bytes = netmask.GetAddressBytes();

        if (host_bytes.Length != netmask_bytes.Length)
        {
            throw new ArgumentException("Lengths of IP address and subnet mask do not match");
        }

        byte[] network_byte = new byte[host_bytes.Length];

        for (int i = 0; i < host_bytes.Length; i++)
        {
            network_byte[i] = (byte)(host_bytes[i] & netmask_bytes[i]);
        }

        return(new System.Net.IPAddress(network_byte));
    }
        private async Task Receive(WebSocket socket, Action <WebSocketReceiveResult, int, byte[]> handleMessage)
        {
            while (socket.State == WebSocketState.Open)
            {
                try
                {
                    int maxSize      = 1024 * 2000000;
                    int bufferSize   = 500;
                    int increaseSize = 1024 * 10;
                    var buffer       = new byte[bufferSize];
                    var offset       = 0;
                    var free         = buffer.Length;
                    WebSocketReceiveResult result = null;
                    int counter = 0;
                    while (true)
                    {
                        result = await socket.ReceiveAsync(new ArraySegment <byte>(buffer, offset, free), cancellationToken : CancellationToken.None);

                        offset += result.Count;
                        free   -= result.Count;
                        if (result.EndOfMessage)
                        {
                            break;
                        }

                        if (free == 0)
                        {
                            if (counter > 5)
                            {
                                increaseSize = 1024 * 100;
                            }

                            else if (counter > 10)
                            {
                                increaseSize = 1024 * 1000;
                            }

                            else if (counter > 20)
                            {
                                increaseSize = 1024 * 10000;
                            }

                            else if (counter > 30)
                            {
                                increaseSize = 1024 * 100000;
                            }

                            else if (counter > 40)
                            {
                                increaseSize = 1024 * 1000000;
                            }
                            // No free space
                            // Resize the outgoing buffer
                            var newSize = buffer.Length + increaseSize;
                            // Console.WriteLine("more data: " + offset + " " + newSize);

                            // Check if the new size exceeds a

                            // It should suit the data it receives
                            // This limit however has a max value of 2 billion bytes (2 GB)
                            if (newSize > maxSize)
                            {
                                throw new Exception("Maximum size exceeded");
                            }

                            var newBuffer = new byte[newSize];
                            Array.Copy(buffer, 0, newBuffer, 0, offset);
                            buffer = newBuffer;
                            free   = buffer.Length - offset;
                            counter++;
                        }
                    }

                    try
                    {
                        handleMessage(result, offset, buffer);
                    }
                    catch (Exception t)
                    {
                        Console.WriteLine(t);
                    }
                }
                catch (Exception e)
                {
                    var id = WebSocketListner.manager.GetId(socket);
                    if (WebSocketListner.registered_id_workflows.ContainsKey(id))
                    {
                        var wid = WebSocketListner.registered_id_workflows[id];
                        try
                        {
                            var wsp_ais = QuantApp.Kernel.M.Base(wid)[x => true].FirstOrDefault() as Workflow;
                            foreach (var fid in wsp_ais.Agents)
                            {
                                var f = F.Find(fid).Value;
                                f.RemoteStop();
                            }
                        }
                        catch {}

                        string none = "";
                        WebSocketListner.registered_id_workflows.TryRemove(id, out none);

                        if (WebSocketListner.registered_workflows_id.ContainsKey(wid))
                        {
                            WebSocketListner.registered_workflows_id.TryRemove(wid, out none);
                        }
                    }

                    if (WebSocketListner.registered_address.ContainsKey(id))
                    {
                        System.Net.IPAddress ip = null;
                        WebSocketListner.registered_address.TryRemove(id, out ip);
                    }

                    break;
                }
            }
        }
 /// <summary>
 /// Определяет, находятся ли два адреса в разных подсетях
 /// </summary>
 /// <param name="other"></param>
 /// <returns></returns>
 public bool IsInSameSubnet(System.Net.IPAddress other)
 {
     return(IsInSameSubnet(IP, other, Netmask));
 }