// /proc/net/route contains some information about gateway addresses,
        // and separates the information about by each interface.
        internal static List<GatewayIPAddressInformation> ParseGatewayAddressesFromRouteFile(string filePath, string interfaceName)
        {
            if (!File.Exists(filePath))
            {
                throw ExceptionHelper.CreateForInformationUnavailable();
            }

            List<GatewayIPAddressInformation> collection = new List<GatewayIPAddressInformation>();
            // Columns are as follows (first-line header):
            // Iface  Destination  Gateway  Flags  RefCnt  Use  Metric  Mask  MTU  Window  IRTT
            string[] fileLines = File.ReadAllLines(filePath);
            foreach (string line in fileLines)
            {
                if (line.StartsWith(interfaceName))
                {
                    StringParser parser = new StringParser(line, '\t', skipEmpty: true);
                    parser.MoveNext();
                    parser.MoveNextOrFail();
                    string gatewayIPHex = parser.MoveAndExtractNext();
                    long addressValue = Convert.ToInt64(gatewayIPHex, 16);
                    IPAddress address = new IPAddress(addressValue);
                    collection.Add(new SimpleGatewayIPAddressInformation(address));
                }
            }

            return collection;
        }
Beispiel #2
0
    public static IObservable<PingReply> Send(IPAddress address)
    {
      Contract.Requires(address != null);
      Contract.Ensures(Contract.Result<IObservable<PingReply>>() != null);

      return Observable2.UsingHot(new Ping(), ping => ping.SendObservable(address));
    }
Beispiel #3
0
        private async void InternalSendAsync(IPAddress address, byte[] buffer, int timeout, PingOptions options)
        {
            AsyncOperation asyncOp = _asyncOp;
            SendOrPostCallback callback = _onPingCompletedDelegate;

            PingReply pr = null;
            Exception pingException = null;

            try
            {
                if (RawSocketPermissions.CanUseRawSockets())
                {
                    pr = await SendIcmpEchoRequestOverRawSocket(address, buffer, timeout, options).ConfigureAwait(false);
                }
                else
                {
                    pr = await SendWithPingUtility(address, buffer, timeout, options).ConfigureAwait(false);
                }
            }
            catch (Exception e)
            {
                pingException = e;
            }

            // At this point, either PR has a real PingReply in it, or pingException has an Exception in it.
            var ea = new PingCompletedEventArgs(
                pr,
                pingException,
                false,
                asyncOp.UserSuppliedState);

            Finish();
            asyncOp.PostOperationCompleted(callback, ea);
        }
Beispiel #4
0
        /// <summary>
        /// 启动等待连接
        /// </summary>
        public void StartConnection()
        {
            serverListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);  // Start the socket

            string[] ip = WebSocketProtocol.GetInstance.ServerId.Split('.');
            IPAddress localIp = new IPAddress(new byte[] { Convert.ToByte(ip[0]), Convert.ToByte(ip[1]), Convert.ToByte(ip[2]), Convert.ToByte(ip[3]) });
            serverListener.Bind(new IPEndPoint(localIp, WebSocketProtocol.GetInstance.ServerPort));

            serverListener.Listen(WebSocketProtocol.GetInstance.ConnectionsCount);
            while (true)
            {
                //等待客户端请求
                Socket sc = serverListener.Accept();
                if (sc != null)
                {
                    Thread.Sleep(100);
                    ClientSocketInstance ci = new ClientSocketInstance();
                    ci.ClientSocket = sc;
                    //初始化三个事件
                    ci.NewUserConnection += new ClientSocketEvent(Ci_NewUserConnection);
                    ci.ReceiveData += new ClientSocketEvent(Ci_ReceiveData);
                    ci.DisConnection += new ClientSocketEvent(Ci_DisConnection);
                    //开始与客户端握手[握手成功,即可通讯了]
                    ci.ClientSocket.BeginReceive(ci.receivedDataBuffer, 0, ci.receivedDataBuffer.Length, 0, new AsyncCallback(ci.StartHandshake), ci.ClientSocket.Available);
                    listConnection.Add(ci);

                }

            }
        }
Beispiel #5
0
 public void Init(string host, int port)
 {
     // 创建
     m_Ip = IPAddress.Parse(host);
     m_Ipe = new IPEndPoint(m_Ip, port);
     m_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 }
Beispiel #6
0
 public static void Ctor_BytesScopeId_Success(byte[] address, long scopeId)
 {
     IPAddress ip = new IPAddress(address, scopeId);
     Assert.Equal(address, ip.GetAddressBytes());
     Assert.Equal(scopeId, ip.ScopeId);
     Assert.Equal(AddressFamily.InterNetworkV6, ip.AddressFamily);
 }
Beispiel #7
0
 static void Main(string[] args)
 {
     Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     string[] ip = WebSocketProtocol.GetInstance.ServerId.Split('.');
     IPAddress localIp = new IPAddress(new byte[] { Convert.ToByte(ip[0]), Convert.ToByte(ip[1]), Convert.ToByte(ip[2]),Convert.ToByte(ip[3]) });
     serverListener.Bind(
 }
Beispiel #8
0
        public async Task Dns_GetHostEntryAsync_AnyIPAddress_Fail(IPAddress address)
        {
            string addressString = address.ToString();

            await Assert.ThrowsAsync<ArgumentException>(() => Dns.GetHostEntryAsync(address));
            await Assert.ThrowsAsync<ArgumentException>(() => Dns.GetHostEntryAsync(addressString));
        }
        private static unsafe GatewayIPAddressInformationCollection GetGatewayAddresses(int interfaceIndex)
        {
            HashSet<IPAddress> addressSet = new HashSet<IPAddress>();
            if (Interop.Sys.EnumerateGatewayAddressesForInterface((uint)interfaceIndex,
                (gatewayAddressInfo) =>
                {
                    byte[] ipBytes = new byte[gatewayAddressInfo->NumAddressBytes];
                    fixed (byte* ipArrayPtr = ipBytes)
                    {
                        Buffer.MemoryCopy(gatewayAddressInfo->AddressBytes, ipArrayPtr, ipBytes.Length, ipBytes.Length);
                    }
                    IPAddress ipAddress = new IPAddress(ipBytes);
                    addressSet.Add(ipAddress);
                }) == -1)
            {
                throw new NetworkInformationException(SR.net_PInvokeError);
            }

            GatewayIPAddressInformationCollection collection = new GatewayIPAddressInformationCollection();
            foreach (IPAddress address in addressSet)
            {
                collection.InternalAdd(new SimpleGatewayIPAddressInformation(address));
            }

            return collection;
        }
Beispiel #10
0
 public UDPListener(int portToListen, IPAddress ip)
 {
     _port = portToListen;
     _endPoint = new IPEndPoint(ip, portToListen);
     _client = new UdpClient(_endPoint);
     _timeToWait = defaultTimeOut;
 }
Beispiel #11
0
 public static void SetServerIp(string ip)
 {
     IPAddress serverIp;
     var done = IPAddress.TryParse(ip, out serverIp);
     if (done)
         _serverIp = serverIp;
 }
Beispiel #12
0
 public UDPListener(int portToListen, IPAddress ip, double time)
 {
     _port = portToListen;
     _endPoint = new IPEndPoint(ip, portToListen);
     _client = new UdpClient(_endPoint);
     _timeToWait = time;
 }
        public string GetHostName(IPAddress address)
        {
            if (address == null)
            {
                throw new ArgumentNullException("address");
            }

            var result = m_hostNames.GetOrAdd(address.Value, x =>
            {
                var arpaUrl = DnsHelper.GetArpaUrl(address);
                var response = Query(arpaUrl, QType.PTR, QClass.IN);
                if (response.Error.Length > 0 || response.header.ANCOUNT != 1)
                {
                    return null;
                }

                var ptrAnswer = response.Answers.FirstOrDefault();
                if (ptrAnswer == null)
                {
                    return null;
                }

                var ptrRecord = (PTRRecord)ptrAnswer.RECORD;
                var hostName = ptrRecord.PTRDNAME.Trim(new[] { '.' });
                return hostName;
            });
            return result;
        }
	public void TestIPAddressConstructor()
	{
		IPAddress ip=null;
		try
		{
			ip=new IPAddress(-1);
			Fail("IPAddress(-1) should throw an ArgumentOutOfRangeException");
		}
		catch(ArgumentOutOfRangeException)
		{
			//  OK !
		}
		try
		{
			ip=new IPAddress(0x00000001FFFFFFFF);
			Fail("IPAddress(0x00000001FFFFFFFF) should throw an ArgumentOutOfRangeException");
		}
		catch(ArgumentOutOfRangeException)
		{
			//  OK !
		}
		AssertEquals ("IPAddress.Any.Address == 0l", IPAddress.Any.Address, 
						(long) 0);
		AssertEquals ("IPAddress.Broadcast.Address == 0xFFFFFFFF", 
			IPAddress.Broadcast.Address, 
			(long) 0xFFFFFFFF);
		AssertEquals ("IPAddress.Loopback.Address == loopback", 
			IPAddress.Loopback.Address, 
			IPAddress.HostToNetworkOrder(0x7f000001));
	}
Beispiel #15
0
    /// <summary>
    /// Asynchronously attempts to send an Internet Control Message Protocol (ICMP) echo message to the computer that has the specified <see cref="IPAddress"/>, and receive a corresponding ICMP echo reply message from that computer.
    /// </summary>
    /// <param name="ping">The object that sends the ICMP echo message.</param>
    /// <param name="address">An <see cref="IPAddress"/> that identifies the computer that is the destination for the ICMP echo message.</param>
    /// <returns>A hot observable containing a <see cref="PingReply"/> instance that provides information about the ICMP echo reply message, if one was received, or describes the reason for the failure if no message was received.</returns>
    public static IObservable<PingReply> SendObservable(this Ping ping, IPAddress address)
    {
      Contract.Requires(ping != null);
      Contract.Requires(address != null);
      Contract.Ensures(Contract.Result<IObservable<PingReply>>() != null);

      return CreatePingObservable(ping, token => ping.SendAsync(address, token));
    }
Beispiel #16
0
	public DemoMain(IPAddress ip, int port, int bufferSize, int maxUserCount)
	{
		_serverEndPoint = new IPEndPoint(ip, port);
		 
		
		_listenArgs = new SocketAsyncEventArgs();
		_listenArgs.Completed += StartReceiving;
	}
Beispiel #17
0
    /// <summary>
    /// Returns an observable of concurrent TCP connections.  (See the remarks section for important details about the concurrent behavior.)
    /// </summary>
    /// <remarks>
    /// <alert type="warning">
    /// <see cref="Start(IPEndPoint)"/> returns an observable that may send notifications concurrently.  This behavior allows 
    /// observers to receive multiple clients concurrently, as is common in hosting scenarios; however, it violates an important contract 
    /// in Rx.  The Rx Design Guidelines document states that Rx operators assume notifications are sent in a serialized fashion.  The only 
    /// methods that do not conflict with this guideline and are safe to call on the observable that is returned by 
    /// <see cref="Start(IPEndPoint)"/> are <strong>Subscribe</strong> and <strong>Synchronize</strong>.  Do not attempt to use 
    /// any other Rx operators unless the observable is synchronized first.
    /// </alert>
    /// </remarks>
    /// <param name="address">The local IP address on which to listen for clients.</param>
    /// <param name="port">The local port number on which to listen for clients.</param>
    /// <returns>An observable of concurrent TCP connections.</returns>
    public static IObservable<TcpClient> Start(IPAddress address, int port)
    {
      Contract.Requires(address != null);
      Contract.Requires(port >= IPEndPoint.MinPort && port <= IPEndPoint.MaxPort);
      Contract.Ensures(Contract.Result<IObservable<TcpClient>>() != null);

      return Start(address, port, ConcurrencyEnvironment.DefaultMaximumConcurrency);
    }
 public THEClient(int bufferSize = 1024)
 {
     this.bufferSize = bufferSize;
     buffer = new byte[bufferSize];
     state = State.Resting;
     THEServerAddress = null;
     useSendAsync = true;
 }
		internal PingReply (IPAddress address, byte [] buffer, PingOptions options, long roundtripTime, IPStatus status)
		{
			this.address = address;
			this.buffer = buffer;
			this.options = options;
			this.rtt = roundtripTime;
			this.status = status;
		}
Beispiel #20
0
 public void InitiateSocket(string ipAddr, int port = 41234)
 {
     Debug.Log("ip = " + ipAddr);
     if(sock == null)
         sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
     endpoint_addr = IPAddress.Parse(ipAddr);
     endpoint = new IPEndPoint(endpoint_addr, port);
 }
 public void setBroadcastIPs(IPAddress[] pIPs)
 {
     mIPEndPoints = new IPEndPoint[pIPs.Length];
     for (int i = 0; i < pIPs.Length;++i )
     {
         mIPEndPoints[i] = new IPEndPoint(pIPs[i], mPort);
     }
 }
        private void ConnectCore(IPAddress[] addresses, int port)
        {
            StartConnectCore(addresses, port);
            Task t = ConnectCorePrivate(addresses, port, (s, a, p) => { s.Connect(a, p); return Task.CompletedTask; });

            Debug.Assert(t.IsCompleted);
            t.GetAwaiter().GetResult();
        }
Beispiel #23
0
	public	void	StartListenTo( string addr, int port ) {
		address = IPAddress.Parse( addr );
		listener = new TcpListener( address, port );
		
		listener.Start();
		
		listener.BeginAcceptSocket( new AsyncCallback(OnConnectHandler), null );
	}
Beispiel #24
0
 public static IPConfiguration Create(IPAddress address, IPAddress mask)
 {
     return new IPConfiguration
            {
                Address = address,
                Mask = mask
            };
 }
Beispiel #25
0
 public void CloseConnection()
 {
     socket.Close();
     thread.Abort();
     isConnected = false;
     socket = null;
     ipAdress = null;
 }
        /// <summary>
        /// Requests a remote host connection asynchronously.
        /// </summary>
        /// <param name="client">The TCP client to be connected.</param>
        /// <param name="address">The IP address of the remote host.</param>
        /// <param name="port">The port number of the remote host.</param>
        /// <returns>An observable containing a single notification when <paramref name="client"/> is connected.</returns>
        public static IObservable<Unit> ConnectObservable(this TcpClient client, IPAddress address, int port)
        {
            Contract.Requires(client != null);
            Contract.Requires(address != null);
            Contract.Requires(port >= IPEndPoint.MinPort && port <= IPEndPoint.MaxPort);
            Contract.Ensures(Contract.Result<IObservable<Unit>>() != null);

            return client.ConnectAsync(address, port).ToObservable();
        }
 public THEServer(IPEndPoint ipEndPoint, int bufferSize = 1024)
 {
     this.localAddress = ipEndPoint.Address;
     this.port = ipEndPoint.Port;
     this.bufferSize = bufferSize;
     myListener = new TcpListener(this.localAddress, port);
     state = State.Resting;
     allowConnect = false;
 }
Beispiel #28
0
 public Task ConnectAsync(IPAddress address, int port)
 {
     return Task.Factory.FromAsync(
         (targetAddess, targetPort, callback, state) => ((TcpClient)state).BeginConnect(targetAddess, targetPort, callback, state),
         asyncResult => ((TcpClient)asyncResult.AsyncState).EndConnect(asyncResult),
         address,
         port,
         state: this);
 }
Beispiel #29
0
		public PortForwading()
		{
			internalIP = IPAddress.None;
			internalPort = 0;
			externalPort = 0;
			protocol = ProtocolType.Unspecified;
			description = "(Unknown)";
			enabled = false;
		}
Beispiel #30
0
		public static bool IPMatch(string val, IPAddress ip, ref bool valid)
		{
			valid = true;

			string[] split = val.Split('.');

			for (int i = 0; i < 4; ++i)
			{
				int lowPart, highPart;

				if (i >= split.Length)
				{
					lowPart = 0;
					highPart = 255;
				}
				else
				{
					string pattern = split[i];

					if (pattern == "*")
					{
						lowPart = 0;
						highPart = 255;
					}
					else
					{
						lowPart = 0;
						highPart = 0;

						bool highOnly = false;
						int lowBase = 10;
						int highBase = 10;

						for (int j = 0; j < pattern.Length; ++j)
						{
							char c = pattern[j];

							if (c == '?')
							{
								if (!highOnly)
								{
									lowPart *= lowBase;
									lowPart += 0;
								}

								highPart *= highBase;
								highPart += highBase - 1;
							}
							else if (c == '-')
							{
								highOnly = true;
								highPart = 0;
							}
							else if (c == 'x' || c == 'X')
							{
								lowBase = 16;
								highBase = 16;
							}
							else if (c >= '0' && c <= '9')
							{
								int offset = c - '0';

								if (!highOnly)
								{
									lowPart *= lowBase;
									lowPart += offset;
								}

								highPart *= highBase;
								highPart += offset;
							}
							else if (c >= 'a' && c <= 'f')
							{
								int offset = 10 + (c - 'a');

								if (!highOnly)
								{
									lowPart *= lowBase;
									lowPart += offset;
								}

								highPart *= highBase;
								highPart += offset;
							}
							else if (c >= 'A' && c <= 'F')
							{
								int offset = 10 + (c - 'A');

								if (!highOnly)
								{
									lowPart *= lowBase;
									lowPart += offset;
								}

								highPart *= highBase;
								highPart += offset;
							}
							else
							{
								valid = false; //high & lowpart would be 0 if it got to here.
							}
						}
					}
				}

				int b = (byte)(GetAddressValue(ip) >> (i * 8));

				if (b < lowPart || b > highPart)
				{
					return false;
				}
			}

			return true;
		}
Beispiel #31
0
 public void Send(IPAddress address, int port, byte[] data, int index, int count)
 {
     this.Send(new IPEndPoint(address, port), data, index, count);
 }
Beispiel #32
0
 public virtual void Connect(IPAddress addr, int port)
 {
 }
Beispiel #33
0
		public static bool IPMatch(string val, IPAddress ip)
		{
			bool valid = true;

			return IPMatch(val, ip, ref valid);
		}
Beispiel #34
0
		public static void Intern(ref IPAddress ipAddress)
		{
			ipAddress = Intern(ipAddress);
		}
 /// <summary>
 /// Initializes a new instance of the <see cref="FactoryOrchestratorVersionMismatchException"/> class.
 /// </summary>
 /// <param name="ip">The ip address of the Service.</param>
 /// <param name="serviceVersion">The service version.</param>
 public FactoryOrchestratorVersionMismatchException(IPAddress ip, string serviceVersion) : base(string.Format(CultureInfo.CurrentCulture, Resources.FactoryOrchestratorVersionMismatchException, ip?.ToString(), serviceVersion))
 {
     ServiceVersion = serviceVersion;
     ClientVersion  = FactoryOrchestratorClient.GetClientVersionString();
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="FactoryOrchestratorConnectionException"/> class.
 /// </summary>
 /// <param name="ip">IP address the client is attempting to communicate with.</param>
 public FactoryOrchestratorConnectionException(IPAddress ip) : base(string.Format(CultureInfo.CurrentCulture, Resources.FactoryOrchestratorConnectionException, ip?.ToString()))
 {
 }
Beispiel #37
0
        private async Task MulticastInterface_Set_Helper(int interfaceIndex)
        {
            IPAddress multicastAddress = IPAddress.Parse("239.1.2.3");
            string    message          = "hello";
            int       port;

            using (Socket receiveSocket = CreateBoundUdpSocket(out port),
                   sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                receiveSocket.ReceiveTimeout = 1000;
                receiveSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(multicastAddress, interfaceIndex));

                sendSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, IPAddress.HostToNetworkOrder(interfaceIndex));

                var receiveBuffer = new byte[1024];
                var receiveTask   = receiveSocket.ReceiveAsync(new ArraySegment <byte>(receiveBuffer), SocketFlags.None);

                for (int i = 0; i < TestSettings.UDPRedundancy; i++)
                {
                    sendSocket.SendTo(Encoding.UTF8.GetBytes(message), new IPEndPoint(multicastAddress, port));
                }

                var cts = new CancellationTokenSource();
                Assert.True(await Task.WhenAny(receiveTask, Task.Delay(30_000, cts.Token)) == receiveTask, "Waiting for received data timed out");
                cts.Cancel();

                int    bytesReceived   = await receiveTask;
                string receivedMessage = Encoding.UTF8.GetString(receiveBuffer, 0, bytesReceived);

                Assert.Equal(receivedMessage, message);
            }
        }
Beispiel #38
0
        public static void Picking()
        {
            ScanCmdPacket ScanCmdPack = new ScanCmdPacket();
            ScanEchoPacket ScanEchoPack = new ScanEchoPacket();
            MachIDCmdPacket MachIDCmdPack = new MachIDCmdPacket();
            MachIDEchoPacket MachIDEchoPack = new MachIDEchoPacket();
            MachConnectCmdPacket MachConnectCmdPack = new MachConnectCmdPacket();
            MachConnectEchoPacket MachConnectEchoPack = new MachConnectEchoPacket();
            MachDataCmdPacket MachDataCmdPack = new MachDataCmdPacket();
            MachDataEchoPacket MachDataEchoPack = new MachDataEchoPacket();
            //MachConnectCmdPacket[] PassWord = new MachConnectCmdPacket[1];
            //MachDataCmdPacket[] DataBuf = new MachDataCmdPacket[1];
            MachConnectCmdPack.Password = new char[60];
            MachDataCmdPack.DataBuf = new byte[800];

            LaserPACKET LaserPack = new LaserPACKET(); //Data Package

            #region package initialize

            ScanCmdPack.ID = 0x0;
            ScanCmdPack.Sz = 0x0;
            ScanCmdPack.Cmd = 0x20;
            ScanCmdPack.Count = 0x0;
            ScanCmdPack.Sum = 0xe0;

            //   MachIDCmdPacket
            MachIDCmdPack.ID = 0x0;
            MachIDCmdPack.Sz = 0x0;
            MachIDCmdPack.Cmd = 0x21;
            MachIDCmdPack.Count = 0x0;
            MachIDCmdPack.Sum = 0xdf;

            //   MachConnectCmdPacket
            MachConnectCmdPack.ID = 1;
            MachConnectCmdPack.Sz = 0x4a;
            MachConnectCmdPack.Cmd = 0x22;
            MachConnectCmdPack.Count = 0;
            MachConnectCmdPack.DataSz = 0x42;
            MachConnectCmdPack.DataCmd0 = 0x03;
            MachConnectCmdPack.DataCmd1 = 0;
            MachConnectCmdPack.Part = 0;
            MachConnectCmdPack.ver1 = 4;
            MachConnectCmdPack.ver2 = 3;
            MachConnectCmdPack.BugFix = 7;
            MachConnectCmdPack.TypeID = 0x10;
            MachConnectCmdPack.SubTypeID = 0xa0;
            Array.Clear(MachConnectCmdPack.Password, 0x00, 60);
            for (int i = 0; i < 4; i++)
            {
                MachConnectCmdPack.Password[i] = '0';
            }
            //+ Array.ConvertAll<char, int>(MachConnectCmdPack.Password, value => Convert.ToInt32(value));
            MachConnectCmdPack.Sum = (byte)0xd0;

            //   MachDataCmdPacket
            MachDataCmdPack.ID = 1;
            MachDataCmdPack.Sz = 0x330;
            MachDataCmdPack.Cmd = 0x01;
            MachDataCmdPack.Count = 0x00;
            MachDataCmdPack.DataSz = 0x328;
            MachDataCmdPack.DataCmd0 = 0x50;
            MachDataCmdPack.DataCmd1 = 0;
            MachDataCmdPack.Part = 0;
            MachDataCmdPack.Code = 0xa000;
            MachDataCmdPack.Len = 0x320;
            //memset((char*)MachDataCmdPack.DataBuf, 0x00, sizeof(DataSent));
            Array.Clear(MachDataCmdPack.DataBuf, 0, 800);
            MachDataCmdPack.Sum = (byte)0x8d;
            Console.WriteLine(MachDataCmdPack.Sum);

            #endregion
            //PackageSetting(ref ScanCmdPack, ref MachIDCmdPack, ref MachConnectCmdPack, ref MachDataCmdPack);

            //設定本機IP位址,可用IPAddress.Any自行尋找,或直接使用IPAddress.Parse("X.X.X.X")設定
            IPAddress localAddress = IPAddress.Parse("10.1.10.210");
            IPAddress destAddress = IPAddress.Parse("10.1.10.200");
            ushort portNumber = 0x869C;
            try
            {
                localAddress = IPAddress.Parse(Form1.localIP);
                //如果為傳送端,使用IPAddress.Parse("X.X.X.X")設定
                destAddress = IPAddress.Parse(Form1.lasorIP);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.GetType().FullName);
                Console.WriteLine(ex.Message);
                Form1.textMessage += "\r\n" + ex.Message;
                Form1.ResetThread();
            }

            //*******************選擇是否為傳送端*******************//
            bool udpSender = true;

            //預設byte陣列數量
            int bufferSize = 512;

            //初始化物件
            UdpClient udpSocket = null; //UDP instance的宣告(類似初始化)
            byte[] sendBuffer = new byte[bufferSize], receiveBuffer = new byte[bufferSize];  //為了暫時存放序列化資料的變數
            int byteSize; //為顯示傳送出去封包大小而宣告的變數
            ushort cmdState = 0;

            List<string> mpBuffer = new List<string>(); //為一次存取所有資料的暫存變數
            long records = 0;
            

            try
            {    
                while (true)
                {
                    if(flagflag == 0)
                    {
                        break;
                    }

                    if (udpSender == false)
                    {
                        udpSocket = new UdpClient(new IPEndPoint(localAddress, portNumber));
                    }
                    else
                    {
                        udpSocket = new UdpClient(new IPEndPoint(localAddress, 0));
                    }


                    if (udpSender == true)
                    {
                        udpSocket.Connect(destAddress, portNumber);
                        Console.WriteLine("Connect() is OK...");
                    }

                    udpSocket.Client.ReceiveTimeout = 200; //等待訊息接收時間上限

                    if (udpSender == true)
                    {
                        if (cmdState == 0)
                        {
                            Console.WriteLine("Sending the first requested number of packets to the destination, Send()...");

                            MemoryStream stream = new MemoryStream();
                            BinaryWriter bw = new BinaryWriter(stream);
                            Console.WriteLine(ScanCmdPack.Sum);
                            bw.Write(ScanCmdPack.ID);
                            bw.Write(ScanCmdPack.Sz);
                            bw.Write(ScanCmdPack.Cmd);
                            bw.Write(ScanCmdPack.Count);
                            bw.Write(ScanCmdPack.Sum);

                            sendBuffer = stream.ToArray();
                            byteSize = udpSocket.Send(sendBuffer, sendBuffer.Length);
                            cmdState = (ushort)ME.scan;

                            Console.WriteLine("Sent {0} bytes to {1}", byteSize, destAddress.ToString());
                            stream.Close();
                            udpSender = false;
                            Console.WriteLine("Change to receiving mode");
                        }

                        if (cmdState == (ushort)ME.scanE)
                        {
                            Console.WriteLine("Sending the second requested number of packets to the destination, Send()...");

                            MemoryStream stream = new MemoryStream();
                            BinaryWriter bw = new BinaryWriter(stream);
                            Console.WriteLine(ScanCmdPack.Sum);
                            bw.Write(MachIDCmdPack.ID);
                            bw.Write(MachIDCmdPack.Sz);
                            bw.Write(MachIDCmdPack.Cmd);
                            bw.Write(MachIDCmdPack.Count);
                            bw.Write(MachIDCmdPack.Sum);
                            Console.WriteLine("sfgvafgv {0}", MachIDCmdPack.Sum);

                            sendBuffer = stream.ToArray();
                            byteSize = udpSocket.Send(sendBuffer, sendBuffer.Length);
                            cmdState = (ushort)ME.machid;

                            Console.WriteLine("Sent {0} bytes to {1}", byteSize, destAddress.ToString());
                            stream.Close();
                            udpSender = false;
                            Console.WriteLine("Change to receiving mode");
                        }

                        if (cmdState == (ushort)ME.machidE)
                        {
                            Console.WriteLine("Sending the third requested number of packets to the destination, Send()...");

                            MemoryStream stream = new MemoryStream();
                            BinaryWriter bw = new BinaryWriter(stream);
                            Console.WriteLine(ScanCmdPack.Sum);
                            bw.Write(MachConnectCmdPack.ID);
                            bw.Write(MachConnectCmdPack.Sz);
                            bw.Write(MachConnectCmdPack.Cmd);
                            bw.Write(MachConnectCmdPack.Count);
                            bw.Write(MachConnectCmdPack.DataSz);
                            bw.Write(MachConnectCmdPack.DataCmd0);
                            bw.Write(MachConnectCmdPack.DataCmd1);
                            bw.Write(MachConnectCmdPack.Part);
                            bw.Write(MachConnectCmdPack.ver1);
                            bw.Write(MachConnectCmdPack.ver2);
                            bw.Write(MachConnectCmdPack.BugFix);
                            bw.Write(MachConnectCmdPack.TypeID);
                            bw.Write(MachConnectCmdPack.SubTypeID);
                            //bw.Write(MachConnectCmdPack.Password);
                            bw.Write(MachConnectCmdPack.Password);
                            bw.Write(MachConnectCmdPack.Sum);

                            sendBuffer = stream.ToArray();
                            byteSize = udpSocket.Send(sendBuffer, sendBuffer.Length);
                            cmdState = (ushort)ME.machcon;

                            Console.WriteLine("Sent {0} bytes to {1}", byteSize, destAddress.ToString());
                            stream.Close();
                            udpSender = false;
                            Console.WriteLine("Change to receiving mode");
                        }

                        if (cmdState == (ushort)ME.machconE)
                        {
                            Form1.textMessage += "\r\nPicking...";
                            Console.WriteLine("Sending the forth requested number of packets to the destination, Send()...");

                            MemoryStream stream = new MemoryStream();
                            BinaryWriter bw = new BinaryWriter(stream);
                            Console.WriteLine(MachDataCmdPack.Sum);

                            bw.Write(MachDataCmdPack.ID);
                            bw.Write(MachDataCmdPack.Sz);
                            bw.Write(MachDataCmdPack.Cmd);
                            bw.Write(MachDataCmdPack.Count);
                            bw.Write(MachDataCmdPack.DataSz);
                            bw.Write(MachDataCmdPack.DataCmd0);
                            bw.Write(MachDataCmdPack.DataCmd1);
                            bw.Write(MachDataCmdPack.Part);
                            bw.Write(MachDataCmdPack.Code);
                            bw.Write(MachDataCmdPack.Len);
                            //bw.Write(MachDataCmdPack.DataBuf);
                            bw.Write(MachDataCmdPack.DataBuf);
                            bw.Write(MachDataCmdPack.Sum);


                            sendBuffer = stream.ToArray();
                            Console.WriteLine(sendBuffer);
                            byteSize = udpSocket.Send(sendBuffer, sendBuffer.Length);
                            cmdState = (ushort)ME.machdata;

                            Console.WriteLine("Sent {0} bytes to {1}", byteSize, destAddress.ToString());
                            stream.Close();
                            udpSender = false;
                            Console.WriteLine("Change to receiving mode");
                        }

                        if (cmdState == (ushort)ME.machdataE)
                        {
                            Console.WriteLine("Receive successfully, keep receiving.");
                            cmdState = (ushort)ME.machconE;
                        }
                        udpSocket.Close();
                    }
                    else
                    {
                        IPEndPoint senderEndPoint = new IPEndPoint(localAddress, 0);
                        Console.WriteLine("Receiving datagrams in a little time...");

                        if (cmdState == (ushort)ME.scan)
                        {
                            try
                            {
                                receiveBuffer = udpSocket.Receive(ref senderEndPoint);
                                cmdState = (ushort)ME.scanE;
                                Console.WriteLine("It is {0} bytes from {1}", receiveBuffer.Length, senderEndPoint.ToString());

                                MemoryStream stream = new MemoryStream(receiveBuffer);
                                BinaryReader br = new BinaryReader(stream);

                                ScanEchoPack.ID = BitConverter.ToUInt16(br.ReadBytes(2), 0);//反序列化
                                Console.WriteLine("Receive ID = {0}", ScanEchoPack.ID);

                                ScanEchoPack.Sz = BitConverter.ToUInt16(br.ReadBytes(2), 0);
                                Console.WriteLine("Receive Sz = {0}", ScanEchoPack.Sz);

                                ScanEchoPack.Cmd = br.ReadByte();
                                Console.WriteLine("Receive Cmd = {0}", ScanEchoPack.Cmd);

                                ScanEchoPack.Count = BitConverter.ToUInt16(br.ReadBytes(2), 0);
                                Console.WriteLine("Receive Count = {0}", ScanEchoPack.Count);

                                ScanEchoPack.Sum = br.ReadByte();
                                Console.WriteLine("Receive Sum = {0}", ScanEchoPack.Sum);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.GetType().FullName);
                                Console.WriteLine(ex.Message);
                                Form1.textMessage += "\r\n" + ex.Message;
                                cmdState = 0;
                            }
                            udpSender = true;
                        }

                        if (cmdState == (ushort)ME.machid)
                        {
                            try
                            {
                                receiveBuffer = udpSocket.Receive(ref senderEndPoint);

                                cmdState = (ushort)ME.machidE;
                                Console.WriteLine("It is {0} bytes from {1}", receiveBuffer.Length, senderEndPoint.ToString());

                                MemoryStream stream = new MemoryStream(receiveBuffer);
                                BinaryReader br = new BinaryReader(stream);

                                MachIDEchoPack.ID = BitConverter.ToUInt16(br.ReadBytes(2), 0);
                                Console.WriteLine("Receive ID = {0}", MachIDEchoPack.ID);

                                MachIDEchoPack.Sz = BitConverter.ToUInt16(br.ReadBytes(2), 0);
                                Console.WriteLine("Receive Sz = {0}", MachIDEchoPack.Sz);

                                MachIDEchoPack.Cmd = br.ReadByte();
                                Console.WriteLine("Receive Cmd = {0}", MachIDEchoPack.Cmd);

                                MachIDEchoPack.Count = BitConverter.ToUInt16(br.ReadBytes(2), 0);
                                Console.WriteLine("Receive Count = {0}", MachIDEchoPack.Count);

                                MachIDEchoPack.ID0 = br.ReadByte();
                                Console.WriteLine("Receive ID0 = {0}", MachIDEchoPack.ID0);

                                MachIDEchoPack.Ver1 = br.ReadByte();
                                Console.WriteLine("Receive Ver1 = {0}", MachIDEchoPack.Ver1);

                                MachIDEchoPack.Ver2 = br.ReadByte();
                                Console.WriteLine("Receive Ver2 = {0}", MachIDEchoPack.Ver2);

                                MachIDEchoPack.BugFix = BitConverter.ToUInt16(br.ReadBytes(2), 0);
                                Console.WriteLine("Receive BugFix = {0}", MachIDEchoPack.BugFix);

                                MachIDEchoPack.TypeID = br.ReadByte();
                                Console.WriteLine("Receive TypeID = {0}", MachIDEchoPack.TypeID);

                                MachIDEchoPack.SubTypeID = br.ReadByte();
                                Console.WriteLine("Receive SubTypeID = {0}", MachIDEchoPack.SubTypeID);

                                MachIDEchoPack.UserDef = br.ReadBytes(60);
                                Console.WriteLine("Receive UserDef");

                                MachIDEchoPack.Sum = br.ReadByte();
                                Console.WriteLine("Receive Sum = {0}", MachIDEchoPack.Sum);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.GetType().FullName);
                                Console.WriteLine(ex.Message);
                                Form1.textMessage += "\r\n" + ex.Message;
                                cmdState = (ushort)ME.scanE;
                            }
                            udpSender = true;
                        }

                        if (cmdState == (ushort)ME.machcon)
                        {
                            try
                            {
                                receiveBuffer = udpSocket.Receive(ref senderEndPoint);
                                cmdState = (ushort)ME.machconE;
                                Console.WriteLine("It is {0} bytes from {1}", receiveBuffer.Length, senderEndPoint.ToString());

                                MemoryStream stream = new MemoryStream(receiveBuffer);
                                BinaryReader br = new BinaryReader(stream);

                                MachConnectEchoPack.ID = BitConverter.ToUInt16(br.ReadBytes(2), 0);
                                Console.WriteLine("Receive ID = {0}", MachConnectEchoPack.ID);

                                MachConnectEchoPack.Sz = BitConverter.ToUInt16(br.ReadBytes(2), 0);
                                Console.WriteLine("Receive Sz = {0}", MachConnectEchoPack.Sz);

                                MachConnectEchoPack.Cmd = br.ReadByte();
                                Console.WriteLine("Receive Cmd = {0}", MachConnectEchoPack.Cmd);

                                MachConnectEchoPack.Count = BitConverter.ToUInt16(br.ReadBytes(2), 0);
                                Console.WriteLine("Receive Count = {0}", MachConnectEchoPack.Count);

                                MachConnectEchoPack.DataSz = BitConverter.ToUInt16(br.ReadBytes(2), 0);
                                Console.WriteLine("Receive DataSz = {0}", MachConnectEchoPack.DataSz);

                                MachConnectEchoPack.DataCmd0 = br.ReadByte();
                                Console.WriteLine("Receive DataCmd0 = {0}", MachConnectEchoPack.DataCmd0);

                                MachConnectEchoPack.DataCmd1 = br.ReadByte();
                                Console.WriteLine("Receive DataCmd1 = {0}", MachConnectEchoPack.DataCmd1);

                                MachConnectEchoPack.Part = BitConverter.ToUInt16(br.ReadBytes(4), 0);
                                Console.WriteLine("Receive Part = {0}", MachConnectEchoPack.Part);

                                MachConnectEchoPack.Security = BitConverter.ToUInt16(br.ReadBytes(2), 0);
                                Console.WriteLine("Receive Security = {0}", MachConnectEchoPack.Security);

                                MachConnectEchoPack.MachID = BitConverter.ToUInt16(br.ReadBytes(2), 0);
                                Console.WriteLine("Receive MachID = {0}", MachConnectEchoPack.MachID);

                                MachConnectEchoPack.Sum = br.ReadByte();
                                Console.WriteLine("Receive Sum = {0}", MachIDEchoPack.Sum);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.GetType().FullName);
                                Console.WriteLine(ex.Message);
                                Form1.textMessage += "\r\n" + ex.Message;
                                cmdState = (ushort)ME.machidE;
                            }
                            udpSender = true;
                        }

                        if (cmdState == (ushort)ME.machdata)
                        {
                            try
                            {
                                receiveBuffer = udpSocket.Receive(ref senderEndPoint);
                                cmdState = (ushort)ME.machdataE;
                                Console.WriteLine("It is {0} bytes from {1}", receiveBuffer.Length, senderEndPoint.ToString());

                                MemoryStream stream = new MemoryStream(receiveBuffer);
                                BinaryReader br = new BinaryReader(stream);

                                MachDataEchoPack.ID = BitConverter.ToUInt16(br.ReadBytes(2), 0);
                                Console.WriteLine("Receive ID = {0}", MachDataEchoPack.ID);

                                MachDataEchoPack.Sz = BitConverter.ToUInt16(br.ReadBytes(2), 0);
                                Console.WriteLine("Receive Sz = {0}", MachDataEchoPack.Sz);

                                MachDataEchoPack.Cmd = br.ReadByte();
                                Console.WriteLine("Receive Cmd = {0}", MachDataEchoPack.Cmd);

                                MachDataEchoPack.Count = BitConverter.ToUInt16(br.ReadBytes(2), 0);
                                Console.WriteLine("Receive Count = {0}", MachDataEchoPack.Count);

                                MachDataEchoPack.DataSz = BitConverter.ToUInt16(br.ReadBytes(2), 0);
                                Console.WriteLine("Receive DataSz = {0}", MachDataEchoPack.DataSz);

                                MachDataEchoPack.DataCmd0 = br.ReadByte();
                                Console.WriteLine("Receive DataCmd0 = {0}", MachDataEchoPack.DataCmd0);

                                MachDataEchoPack.DataCmd1 = br.ReadByte();
                                Console.WriteLine("Receive DataCmd1 = {0}", MachDataEchoPack.DataCmd1);

                                MachDataEchoPack.Part = BitConverter.ToUInt32(br.ReadBytes(4), 0);
                                Console.WriteLine("Receive Part = {0}", MachDataEchoPack.Part);

                                MachDataEchoPack.Code = BitConverter.ToUInt32(br.ReadBytes(4), 0);
                                Console.WriteLine("Receive Code = {0}", MachDataEchoPack.Code);

                                MachDataEchoPack.Len = BitConverter.ToUInt32(br.ReadBytes(4), 0);
                                Console.WriteLine("Receive Len = {0}", MachDataEchoPack.Len);

                                MachDataEchoPack.ActctLen = BitConverter.ToUInt32(br.ReadBytes(4), 0);
                                Console.WriteLine("Receive ActctLen = {0}", MachDataEchoPack.ActctLen);

                                MachDataEchoPack.DataBuf = br.ReadBytes(532);
                                Console.WriteLine("Receive DataBuf");

                                MachDataEchoPack.Sum = br.ReadByte();
                                Console.WriteLine("Receive Sum = {0}", MachDataEchoPack.Sum);

                                LaserPack = (LaserPACKET)ByteToStruct(MachDataEchoPack.DataBuf, typeof(LaserPACKET));
                                
                                byte start = 0;
                                if (MachDataEchoPack.DataBuf[96] == 0xFC) { start = 1; } else { start = 0; }
                                mpBuffer.Add(
                                    DateTime.Now.ToString("HH: mm:ss.ffffzzz") + "," +
                                    BitConverter.ToInt32(MachDataEchoPack.DataBuf, 100).ToString() + "," +
                                    BitConverter.ToInt32(MachDataEchoPack.DataBuf, 104).ToString() + "," +
                                    BitConverter.ToInt32(MachDataEchoPack.DataBuf, 108).ToString() + "," +
                                    BitConverter.ToDouble(MachDataEchoPack.DataBuf, 316).ToString() + "," +
                                    start.ToString()
                                    );
                                
                                Thread.Sleep(10);
                                records++;
                                if (records % 500 == 0)
                                {
                                    Form1.textMessage += "\r\nPicking...(have picked above " + records.ToString() + " records)";
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.GetType().FullName);
                                Console.WriteLine(ex.Message);
                                Form1.textMessage += "\r\n" + ex.Message;
                                cmdState = (ushort)ME.machconE;
                            }
                            udpSender = true;
                        }
                        udpSocket.Close();
                    }
                }
            }
            catch (SocketException err)
            {
                Console.WriteLine("Socket error occurred: {0}", err.Message);
                Console.WriteLine("Stack: {0}", err.StackTrace);
                Form1.textMessage += "\r\nIP or Port " + err.Message;
                Form1.ResetThread();
            }
            catch (Exception err)
            {
                Form1.textMessage += "\r\n" + err.Message;
                Form1.ResetThread();
            }
            finally
            {
                if (udpSocket != null)
                {
                    // Free up the underlying network resources
                    Console.WriteLine("Closing the socket...");
                    // udpSocket.Close();
                }
                //初始化檔案
                try
                {
                    string path = @Form1.localPath;
                    if (!Directory.Exists(Path.GetDirectoryName(path)))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(path));
                    }
                    FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
                    TextWriter sw = new StreamWriter(fs);

                    sw.WriteLine("Time,x,y,z,Speed,Cycle Start");
                    foreach (string eachLine in mpBuffer)
                    {
                        sw.WriteLine("{0}", eachLine);
                    }
                    sw.Close();
                    Form1.textMessage += "\r\nTotal records: " + records.ToString();
                }
                catch (Exception ex)
                {
                    if (!Directory.Exists(Path.GetDirectoryName(@"C:\temp\temp.csv")))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(@"C:\temp\temp.csv"));
                    }
                    FileStream fs = new FileStream(@"C:\temp\temp.csv", FileMode.OpenOrCreate);
                    TextWriter sw = new StreamWriter(fs);

                    sw.WriteLine("Time,x,y,z,Speed,Cycle Start");
                    foreach (string eachLine in mpBuffer)
                    {
                        sw.WriteLine("{0}", eachLine);
                    }
                    sw.Close();
                    
                    Form1.textMessage += "\r\n" + ex.Message + ", 已先暫存到C:\\temp\\temp.csv";
                    Form1.textMessage += "\r\nTotal records: " + records.ToString();
                }
                
            }
        }
Beispiel #39
0
 /// <summary>
 /// Binds the underlying Socket to the supplied IPAddress. The port is
 /// assigned by the socket. Use this method if you want to bind the 
 /// socket for a client who needs to receive messages back from a
 /// endpoint.
 /// </summary>
 /// <param name="address">The address to bind to.</param>
 public void Bind(IPAddress address)
 {
     this.Bind(address, 0);
 }
Beispiel #40
0
        /// <summary>
        /// Binds the underlying Socket to the supplied IPAddress and Port. If
        /// setting up a socket as a listener, this is the method to use. Use
        /// IPAddress.Any to bind to all local addresses.
        /// </summary>
        /// <param name="address">The address to bind to.</param>
        /// <param name="port">The port to bind to.</param>
        public void Bind(IPAddress address, int port)
        {
            this.socket.Bind(new IPEndPoint(address, port));

            this.ReceiveFrom();
        }
Beispiel #41
0
		public static bool IPMatchCIDR(string cidr, IPAddress ip)
		{
			if (ip == null || ip.AddressFamily == AddressFamily.InterNetworkV6)
			{
				return false; //Just worry about IPv4 for now
			}

			/*
            string[] str = cidr.Split( '/' );

            if ( str.Length != 2 )
            return false;

            /* **************************************************
            IPAddress cidrPrefix;

            if ( !IPAddress.TryParse( str[0], out cidrPrefix ) )
            return false;
            * */

			/*
            string[] dotSplit = str[0].Split( '.' );

            if ( dotSplit.Length != 4 )		//At this point and time, and for speed sake, we'll only worry about IPv4
            return false;

            byte[] bytes = new byte[4];

            for ( int i = 0; i < 4; i++ )
            {
            byte.TryParse( dotSplit[i], out bytes[i] );
            }

            uint cidrPrefix = OrderedAddressValue( bytes );

            int cidrLength = Utility.ToInt32( str[1] );
            //The below solution is the fastest solution of the three

            */

			byte[] bytes = new byte[4];
			string[] split = cidr.Split('.');
			bool cidrBits = false;
			int cidrLength = 0;

			for (int i = 0; i < 4; i++)
			{
				int part = 0;

				int partBase = 10;

				string pattern = split[i];

				for (int j = 0; j < pattern.Length; j++)
				{
					char c = pattern[j];

					if (c == 'x' || c == 'X')
					{
						partBase = 16;
					}
					else if (c >= '0' && c <= '9')
					{
						int offset = c - '0';

						if (cidrBits)
						{
							cidrLength *= partBase;
							cidrLength += offset;
						}
						else
						{
							part *= partBase;
							part += offset;
						}
					}
					else if (c >= 'a' && c <= 'f')
					{
						int offset = 10 + (c - 'a');

						if (cidrBits)
						{
							cidrLength *= partBase;
							cidrLength += offset;
						}
						else
						{
							part *= partBase;
							part += offset;
						}
					}
					else if (c >= 'A' && c <= 'F')
					{
						int offset = 10 + (c - 'A');

						if (cidrBits)
						{
							cidrLength *= partBase;
							cidrLength += offset;
						}
						else
						{
							part *= partBase;
							part += offset;
						}
					}
					else if (c == '/')
					{
						if (cidrBits || i != 3) //If there's two '/' or the '/' isn't in the last byte
						{
							return false;
						}

						partBase = 10;
						cidrBits = true;
					}
					else
					{
						return false;
					}
				}

				bytes[i] = (byte)part;
			}

			uint cidrPrefix = OrderedAddressValue(bytes);

			return IPMatchCIDR(cidrPrefix, ip, cidrLength);
		}
Beispiel #42
0
        static void Main(string[] args)
        {
            int t = 0;

            while (true)
            {
                try
                {
                    IPAddress serverip = IPAddress.Parse("127.0.0.1");

                    IPEndPoint ServerEndPoint = new IPEndPoint(serverip, 1234);

                    Socket socket = new Socket(serverip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                    socket.Connect(ServerEndPoint);


                    string message_to_send;

                    while (true)
                    {
                        Console.Write("Enter the message to send to the server: (quit to exit) ");
                        message_to_send = Console.ReadLine();
                        if (message_to_send.ToLower() == "quit")
                        {
                            Environment.Exit(0);
                        }
                        if (message_to_send == "")
                        {
                            Console.WriteLine("Please enter a valid message ..."); continue;
                        }
                        else
                        {
                            break;
                        }
                    }

                    byte[] message_to_send_in_bytes = Encoding.ASCII.GetBytes(message_to_send);
                    int    byteSent = socket.Send(message_to_send_in_bytes);


                    byte[] message_received = new byte[1024];


                    int byteReceived = socket.Receive(message_received);
                    Console.Write("Message received from the server");

                    Console.WriteLine(Encoding.ASCII.GetString(message_received, 0, byteReceived));


                    socket.Shutdown(SocketShutdown.Both);
                    socket.Close();
                }

                catch (Exception e)
                {
                    Console.WriteLine("Could not coonect to the server. Trying to recconect in 2 seconds ..."); Thread.Sleep(2000); t++;
                    if (t == 3)
                    {
                        Console.WriteLine("Could not coonect to the server. Try again later ..."); Console.ReadKey(); Environment.Exit(0);
                    }
                }
            }


            Console.ReadKey();
        }
Beispiel #43
0
 public MasterServer(IPAddress ip, int port)
     : this(new IPEndPoint(ip, port))
 {
 }
Beispiel #44
0
        // if you add code that needs a data socket, i.e. a PASV or PORT command required,
        // call this function to do the dirty work. It sends the PASV or PORT command,
        // parses out the port and ip info and opens the appropriate data socket
        // for you. The socket variable is private Socket data_socket. Once you
        // are done with it, be sure to call CloseDataSocket()
        private void OpenDataSocket()
        {
            if (passive_mode)       // #######################################
            {
                string[] pasv;
                string   server;
                int      port;

                Connect();
                SendCommand("PASV");
                ReadResponse();
                if (response != 227)
                {
                    Fail();
                }

                try
                {
                    int i1, i2;

                    i1   = responseStr.IndexOf('(') + 1;
                    i2   = responseStr.IndexOf(')') - i1;
                    pasv = responseStr.Substring(i1, i2).Split(',');
                }
                catch (Exception)
                {
                    Disconnect();
                    throw new Exception("Malformed PASV response: " + responseStr);
                }

                if (pasv.Length < 6)
                {
                    Disconnect();
                    throw new Exception("Malformed PASV response: " + responseStr);
                }

                server = String.Format("{0}.{1}.{2}.{3}", pasv[0], pasv[1], pasv[2], pasv[3]);
                port   = (int.Parse(pasv[4]) << 8) + int.Parse(pasv[5]);

                try
                {
#if (FTP_DEBUG)
                    Console.WriteLine("Data socket: {0}:{1}", server, port);
#endif
                    CloseDataSocket();

#if (FTP_DEBUG)
                    Console.WriteLine("Creating socket...");
#endif
                    data_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

#if (FTP_DEBUG)
                    Console.WriteLine("Resolving host");
#endif

                    data_ipEndPoint = new IPEndPoint(Dns.GetHostByName(server).AddressList[0], port);


#if (FTP_DEBUG)
                    Console.WriteLine("Connecting..");
#endif
                    data_sock.Connect(data_ipEndPoint);

#if (FTP_DEBUG)
                    Console.WriteLine("Connected.");
#endif
                }
                catch (Exception ex)
                {
                    throw new Exception("Failed to connect for data transfer: " + ex.Message);
                }
            }
            else        // #######################################
            {
                Connect();

                try
                {
#if (FTP_DEBUG)
                    Console.WriteLine("Data socket (active mode)");
#endif
                    CloseDataSocket();

#if (FTP_DEBUG)
                    Console.WriteLine("Creating listening socket...");
#endif
                    listening_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

#if (FTP_DEBUG)
                    Console.WriteLine("Binding it to local address/port");
#endif
                    // for the PORT command we need to send our IP address; let's extract it
                    // from the LocalEndPoint of the main socket, that's already connected
                    string sLocAddr = main_sock.LocalEndPoint.ToString();
                    int    ix       = sLocAddr.IndexOf(':');
                    if (ix < 0)
                    {
                        throw new Exception("Failed to parse the local address: " + sLocAddr);
                    }
                    string sIPAddr = sLocAddr.Substring(0, ix);
                    // let the system automatically assign a port number (setting port = 0)
                    System.Net.IPEndPoint localEP = new IPEndPoint(IPAddress.Parse(sIPAddr), 0);

                    listening_sock.Bind(localEP);
                    sLocAddr = listening_sock.LocalEndPoint.ToString();
                    ix       = sLocAddr.IndexOf(':');
                    if (ix < 0)
                    {
                        throw new Exception("Failed to parse the local address: " + sLocAddr);
                    }
                    int nPort = int.Parse(sLocAddr.Substring(ix + 1));
#if (FTP_DEBUG)
                    Console.WriteLine("Listening on {0}:{1}", sIPAddr, nPort);
#endif
                    // start to listen for a connection request from the host (note that
                    // Listen is not blocking) and send the PORT command
                    listening_sock.Listen(1);
                    string sPortCmd = string.Format("PORT {0},{1},{2}",
                                                    sIPAddr.Replace('.', ','),
                                                    nPort / 256, nPort % 256);
                    SendCommand(sPortCmd);
                    ReadResponse();
                    if (response != 200)
                    {
                        Fail();
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Failed to connect for data transfer: " + ex.Message);
                }
            }
        }
Beispiel #45
0
		public static long GetLongAddressValue(IPAddress address)
		{
#pragma warning disable 618
			return address.Address;
#pragma warning restore 618
		}
Beispiel #46
0
 public static void writeUInt(MemoryStream data, uint tmpvalue)
 {
     tmpvalue = (uint)IPAddress.HostToNetworkOrder((int)tmpvalue);
     byte[] nowData = BitConverter.GetBytes(tmpvalue);
     data.Write(nowData, 0, sizeof(uint));
 }
Beispiel #47
0
 /// <summary>
 /// 连接到远程主机。
 /// </summary>
 /// <param name="ipAddress">远程主机的 IP 地址。</param>
 /// <param name="port">远程主机的端口号。</param>
 public void Connect(IPAddress ipAddress, int port)
 {
     Connect(ipAddress, port, null);
 }
Beispiel #48
0
		public static int GetAddressValue(IPAddress address)
		{
#pragma warning disable 618
			return (int)address.Address;
#pragma warning restore 618
		}
Beispiel #49
0
        public MainWindowViewModel()
        {
            var listenEndPoint    = new IPEndPoint(IPAddress.Any, 8167);
            var broadcastEndPoint = new IPEndPoint(IPAddress.Parse("192.168.0.255"), 8167);

            _messenger = new QCMessenger(listenEndPoint, broadcastEndPoint);

            Nickname     = $"Guest_{new Random().Next()%1000}";
            _OldNickname = Nickname;
            Topic        = "Unset";

            SendMessageCommand = new DelegateCommand(async() =>
            {
                if (MessageText == "")
                {
                    return;
                }
                if (SelectedChannel.ChannelType == ChannelType.Public || SelectedChannel.ChannelType == ChannelType.Const)
                {
                    await _messenger.SendAsync(new PublicMessage(SelectedChannel.Id, String.IsNullOrWhiteSpace(SnoopName) ? Nickname : SnoopName, MessageText));
                }
                else
                {
                    await _messenger.SendAsync(new PrivateMessage(String.IsNullOrWhiteSpace(SnoopName) ? Nickname : SnoopName, SelectedChannel.Id, MessageText));
                }
                MessageText = string.Empty;
            });
            AddChannelCommand = new DelegateCommand(async() =>
            {
                if (NewChannelName == "" || Channels.Any(channel => channel.Id == NewChannelName))
                {
                    return;
                }
                Channels.Add(new ChannelViewModel(NewChannelName, ChannelType.Public));
                SelectedChannel = Channels.Last();
                await _messenger.SendAsync(new ConnectMessage(NewChannelName, Nickname));
                NewChannelName = string.Empty;
            });
            RemoveChannelCommand = new DelegateCommand <ChannelViewModel>(async ch =>
            {
                if (ch.Id == "#Main")
                {
                    return;
                }
                SelectedChannel = Channels.First();
                Channels.Remove(ch);
                await _messenger.SendAsync(new ExitMessage(ch.Id, Nickname));
            });
            ChangeTopicCommand = new DelegateCommand(async() => await _messenger.SendAsync(new TopicMessage(Topic, Nickname)));
            ChangeNameCommand  = new DelegateCommand(async() =>
            {
                await _messenger.SendAsync(new RenameMessage(_OldNickname, Nickname));
                _OldNickname = Nickname;
            });
            AddPrivateChatCommand = new DelegateCommand <User>(u =>
            {
                if (Channels.Any(ch => ch.Id == u.Name))
                {
                    return;
                }
                Channels.Add(new ChannelViewModel(u.Name, ChannelType.Private));
            });
        }
Beispiel #50
0
 public DhcpOption(int code, IPAddress ipaddress)
     : this()
 {
     this._Code  = code;
     this._bytes = ipaddress.GetAddressBytes();
 }
 public ApplicationUser(string userName, string ipAddress, string idNumber)
 {
     this.UserName  = userName;
     this.IpAddress = IPAddress.Parse(ipAddress);
 }
Beispiel #52
0
 public Server(String _host, int _port)
 {
     port = _port;
     host = _host;
     listenSocket.Bind(new IPEndPoint(IPAddress.Parse(host), port));
 }
Beispiel #53
0
 bool IDatabase.UpdateLoginEntry(uint AccountId, IPAddress address)
 {
     return(UpdateLoginEntry(AccountId, address));
 }
Beispiel #54
0
 public void Send(IPAddress address, int port, byte [] data)
 {
     this.Send(new IPEndPoint(address, port), data, 0, data.Length);
 }
        private SocksHttpWebResponse InternalGetResponse()
        {
            Uri requestUri = RequestUri;

            int       redirects            = 0;
            const int maxAutoredirectCount = 10;

            while (redirects++ < maxAutoredirectCount)
            {
                // Loop while redirecting

                var proxyUri  = Proxy.GetProxy(requestUri);
                var ipAddress = GetProxyIpAddress(proxyUri);
                var response  = new List <byte>();

                using (var client = new TcpClient(ipAddress.ToString(), proxyUri.Port))
                {
                    int timeout = Timeout;
                    if (timeout == 0)
                    {
                        timeout = 30 * 1000;
                    }
                    client.ReceiveTimeout = timeout;
                    client.SendTimeout    = timeout;
                    var networkStream = client.GetStream();
                    // auth
                    var buf = new byte[300];
                    Console.WriteLine(proxyUri.Scheme);
                    buf[0] = 0x05; // Version
                    buf[1] = 0x01; // NMETHODS
                    buf[2] = 0x00; // No auth-method
                    networkStream.Write(buf, 0, 3);

                    networkStream.Read(buf, 0, 2);
                    if (buf[0] != 0x05)
                    {
                        throw new IOException("Invalid Socks Version");
                    }
                    if (buf[1] == 0xff)
                    {
                        throw new IOException("Socks Server does not support no-auth");
                    }
                    if (buf[1] != 0x00)
                    {
                        throw new Exception("Socks Server did choose bogus auth");
                    }

                    // connect
                    var destIP = Dns.GetHostEntry(requestUri.DnsSafeHost).AddressList[0];
                    var index  = 0;
                    buf[index++] = 0x05; // version 5 .
                    buf[index++] = 0x01; // command = connect.
                    buf[index++] = 0x00; // Reserve = must be 0x00
                    if (!_isGetIPFromProxyServer)
                    {
                        buf[index++] = 0x01; //  Ipv4 address.
                        var rawBytes = destIP.GetAddressBytes();
                        rawBytes.CopyTo(buf, index);
                        index += (ushort)rawBytes.Length;
                    }
                    else
                    {
                        buf[index++] = 0x03; // Convert to ip from proxy server
                                             // Maybe Cannot Convert.
                        byte[] addBytes = Encoding.ASCII.GetBytes(requestUri.DnsSafeHost);
                        if (addBytes.Length > 255)
                        {
                            throw new IOException("Invalid Host");
                        }
                        byte[] addBytesLength = BitConverter.GetBytes(addBytes.Length);
                        addBytesLength.CopyTo(buf, index);
                        index += addBytesLength.Length;
                        addBytes.CopyTo(buf, index);
                        index += addBytes.Length;
                    }
                    var portBytes = BitConverter.GetBytes(Uri.UriSchemeHttps == requestUri.Scheme ? 443 : 80);
                    for (var i = portBytes.Length - 3; i >= 0; i--)
                    {
                        buf[index++] = portBytes[i];
                    }


                    networkStream.Write(buf, 0, index);

                    networkStream.Read(buf, 0, 4);
                    if (buf[0] != 0x05)
                    {
                        throw new IOException("Invalid Socks Version");
                    }
                    if (buf[1] != 0x00)
                    {
                        throw new IOException($"Socks Error {buf[1]:X}");
                    }

                    var rdest = string.Empty;
                    switch (buf[3])
                    {
                    case 0x01:     // IPv4
                        networkStream.Read(buf, 0, 4);
                        var v4 = BitConverter.ToUInt32(buf, 0);
                        rdest = new IPAddress(v4).ToString();
                        break;

                    case 0x03:     // Domain name
                        networkStream.Read(buf, 0, 1);
                        if (buf[0] == 0xff)
                        {
                            throw new IOException("Invalid Domain Name");
                        }
                        networkStream.Read(buf, 1, buf[0]);
                        rdest = Encoding.ASCII.GetString(buf, 1, buf[0]);
                        break;

                    case 0x04:     // IPv6
                        var octets = new byte[16];
                        networkStream.Read(octets, 0, 16);
                        rdest = new IPAddress(octets).ToString();
                        break;

                    default:
                        throw new IOException("Invalid Address type");
                    }
                    networkStream.Read(buf, 0, 2);
                    var rport = (ushort)IPAddress.NetworkToHostOrder((short)BitConverter.ToUInt16(buf, 0));

                    Stream readStream = null;
                    if (Uri.UriSchemeHttps == requestUri.Scheme)
                    {
                        var ssl = new SslStream(networkStream);
                        ssl.AuthenticateAsClient(requestUri.DnsSafeHost);
                        readStream = ssl;
                    }
                    else
                    {
                        readStream = networkStream;
                    }

                    string requestString = BuildHttpRequestMessage(requestUri);

                    var request = Encoding.ASCII.GetBytes(requestString);
                    readStream.Write(request, 0, request.Length);
                    readStream.Flush();

                    var buffer = new byte[client.ReceiveBufferSize];

                    var readlen = 0;
                    do
                    {
                        readlen = readStream.Read(buffer, 0, buffer.Length);
                        response.AddRange(buffer.Take(readlen));
                    } while (readlen != 0);

                    readStream.Close();
                }

                var webResponse = new SocksHttpWebResponse(requestUri, response.ToArray());

                if (webResponse.StatusCode == HttpStatusCode.Moved || webResponse.StatusCode == HttpStatusCode.MovedPermanently)
                {
                    string redirectUrl = webResponse.Headers["Location"];
                    if (string.IsNullOrEmpty(redirectUrl))
                    {
                        throw new WebException("Missing location for redirect");
                    }

                    requestUri = new Uri(requestUri, redirectUrl);
                    if (AllowAutoRedirect)
                    {
                        continue;
                    }
                    return(webResponse);
                }

                if ((int)webResponse.StatusCode < 200 || (int)webResponse.StatusCode > 299)
                {
                    throw new WebException(webResponse.StatusDescription, null, WebExceptionStatus.UnknownError, webResponse);
                }

                return(webResponse);
            }

            throw new WebException("Too many redirects", null, WebExceptionStatus.ProtocolError, SocksHttpWebResponse.CreateErrorResponse(HttpStatusCode.BadRequest));
        }
Beispiel #56
0
 public static void addBigEndian(ref List <byte> list, IPAddress v)
 {
     list.AddRange(v.GetAddressBytes());
 }
Beispiel #57
0
        public void MulticastInterface_Set_InvalidIndex_Throws()
        {
            int interfaceIndex = 31415;

            using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                Assert.Throws <SocketException>(() =>
                                                s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, IPAddress.HostToNetworkOrder(interfaceIndex)));
            }
        }
Beispiel #58
0
		public static bool IPMatchClassC(IPAddress ip1, IPAddress ip2)
		{
			return (GetAddressValue(ip1) & 0xFFFFFF) == (GetAddressValue(ip2) & 0xFFFFFF);
		}
        /// <summary>
        /// Connects to an endpoint.
        /// </summary>
        public async Task <bool> BeginConnect(Uri endpointUrl, EventHandler <SocketAsyncEventArgs> callback, object state)
        {
            if (endpointUrl == null)
            {
                throw new ArgumentNullException("endpointUrl");
            }

            if (m_socket != null)
            {
                throw new InvalidOperationException("The socket is already connected.");
            }

            // Get DNS host information.
            IPAddress[] hostAdresses = await Dns.GetHostAddressesAsync(endpointUrl.DnsSafeHost);

            // try IPv4 and IPv6 address
            IPAddress addressV4 = null;
            IPAddress addressV6 = null;

            foreach (IPAddress address in hostAdresses)
            {
                if (address.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    if (addressV6 == null)
                    {
                        addressV6 = address;
                    }
                }
                if (address.AddressFamily == AddressFamily.InterNetwork)
                {
                    if (addressV4 == null)
                    {
                        addressV4 = address;
                    }
                }
                if ((addressV4 != null) && (addressV6 != null))
                {
                    break;
                }
            }

            SocketError error = SocketError.NotInitialized;
            TaskCompletionSource <SocketError> tcs = new TaskCompletionSource <SocketError>();
            SocketAsyncEventArgs argsV4            = null;
            SocketAsyncEventArgs argsV6            = null;

            m_socketResponses = 0;

            lock (m_socketLock)
            {
                // ensure a valid port.
                int port = endpointUrl.Port;

                if (port <= 0 || port > UInt16.MaxValue)
                {
                    port = Utils.UaTcpDefaultPort;
                }

                // create sockets if IP address was provided
                if (addressV6 != null)
                {
                    argsV6                = new SocketAsyncEventArgs();
                    argsV6.UserToken      = state;
                    m_socketV6            = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
                    argsV6.RemoteEndPoint = new IPEndPoint(addressV6, port);
                    m_socketResponses++;
                    argsV6.Completed += (o, e) =>
                    {
                        lock (m_socketLock)
                        {
                            m_socketResponses--;
                            if (m_socketV6 != null)
                            {
                                if (m_socket == null &&
                                    (m_socketResponses == 0 || e.SocketError == SocketError.Success))
                                {
                                    m_socket = m_socketV6;
                                    tcs.SetResult(e.SocketError);
                                }
                                else
                                {
                                    m_socketV6.Dispose();
                                    e.UserToken = null;
                                }
                                m_socketV6 = null;
                            }
                            else
                            {
                                e.UserToken = null;
                            }
                        }
                    };
                    argsV6.Completed += callback;
                }
                if (addressV4 != null)
                {
                    argsV4                = new SocketAsyncEventArgs();
                    argsV4.UserToken      = state;
                    m_socketV4            = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    argsV4.RemoteEndPoint = new IPEndPoint(addressV4, port);
                    m_socketResponses++;
                    argsV4.Completed += (o, e) =>
                    {
                        lock (m_socketLock)
                        {
                            m_socketResponses--;
                            if (m_socketV4 != null)
                            {
                                if (m_socket == null &&
                                    (m_socketResponses == 0 || e.SocketError == SocketError.Success))
                                {
                                    m_socket = m_socketV4;
                                    tcs.SetResult(e.SocketError);
                                }
                                else
                                {
                                    m_socketV4.Dispose();
                                    e.UserToken = null;
                                }
                                m_socketV4 = null;
                            }
                            else
                            {
                                e.UserToken = null;
                            }
                        }
                    };
                    argsV4.Completed += callback;
                }

                bool connectV6Sync = true;
                bool connectV4Sync = true;
                if (m_socketV6 != null)
                {
                    connectV6Sync = !m_socketV6.ConnectAsync(argsV6);
                    if (connectV6Sync)
                    {
                        // I/O completed synchronously
                        callback(this, argsV6);
                        error = argsV6.SocketError;
                    }
                }
                if (m_socketV4 != null && error != SocketError.Success)
                {
                    connectV4Sync = !m_socketV4.ConnectAsync(argsV4);
                    if (connectV4Sync)
                    {
                        // I/O completed synchronously
                        callback(this, argsV4);
                        error = argsV4.SocketError;
                    }
                }

                if (connectV4Sync && connectV6Sync)
                {
                    return((error == SocketError.Success) ? true : false);
                }
            }

            error = await tcs.Task;

            return((error == SocketError.Success) ? true : false);
        }
Beispiel #60
-1
 private ArpData(string deviceID, IPAddress ipAddress, MacAddress macAddress, SystemModule module)
 {
     _deviceID = deviceID;
     _ttl = 3000;
     IP = ipAddress;
     Mac = macAddress;
     _module = module;
 }