• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# IPAddress类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中IPAddress的典型用法代码示例。如果您正苦于以下问题:C# IPAddress类的具体用法?C# IPAddress怎么用?C# IPAddress使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



IPAddress类属于命名空间,在下文中一共展示了IPAddress类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: ParseGatewayAddressesFromRouteFile

        // /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;
        }
开发者ID:ChuangYang,项目名称:corefx,代码行数:29,代码来源:StringParsingHelpers.Addresses.cs


示例2: Send

    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));
    }
开发者ID:ibebbs,项目名称:Rxx,代码行数:7,代码来源:ObservablePing.cs


示例3: UDPListener

 public UDPListener(int portToListen, IPAddress ip, double time)
 {
     _port = portToListen;
     _endPoint = new IPEndPoint(ip, portToListen);
     _client = new UdpClient(_endPoint);
     _timeToWait = time;
 }
开发者ID:renato-scaroni,项目名称:mac499,代码行数:7,代码来源:UDPListener.cs


示例4: GetHostName

        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;
        }
开发者ID:atanasmihaylov,项目名称:lanscan,代码行数:28,代码来源:DnsResolverBase.cs


示例5: InternalSendAsync

        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);
        }
开发者ID:IharBury,项目名称:corefx,代码行数:34,代码来源:Ping.Unix.cs


示例6: GetGatewayAddresses

        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;
        }
开发者ID:noahfalk,项目名称:corefx,代码行数:26,代码来源:OsxIpInterfaceProperties.cs


示例7: Init

 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);
 }
开发者ID:wuhuichun,项目名称:Frame,代码行数:7,代码来源:SocketClient.cs


示例8: Dns_GetHostEntryAsync_AnyIPAddress_Fail

        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));
        }
开发者ID:shmao,项目名称:corefx,代码行数:7,代码来源:GetHostEntryTest.cs


示例9: Ctor_BytesScopeId_Success

 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);
 }
开发者ID:noahfalk,项目名称:corefx,代码行数:7,代码来源:IPAddressTest.cs


示例10: SetServerIp

 public static void SetServerIp(string ip)
 {
     IPAddress serverIp;
     var done = IPAddress.TryParse(ip, out serverIp);
     if (done)
         _serverIp = serverIp;
 }
开发者ID:jericho17,项目名称:BallsTestTask,代码行数:7,代码来源:IpHelper.cs


示例11: Main

 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(
 }
开发者ID:cpm2710,项目名称:cellbank,代码行数:7,代码来源:Program.cs


示例12: TestIPAddressConstructor

	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));
	}
开发者ID:jjenki11,项目名称:blaze-chem-rendering,代码行数:30,代码来源:TestIPAddress.cs


示例13: StartConnection

        /// <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);

                }

            }
        }
开发者ID:cpm2710,项目名称:cellbank,代码行数:33,代码来源:WebSocketServer.cs


示例14: Create

 public static IPConfiguration Create(IPAddress address, IPAddress mask)
 {
     return new IPConfiguration
            {
                Address = address,
                Mask = mask
            };
 }
开发者ID:davidbetz,项目名称:netrouter,代码行数:8,代码来源:IPConfiguration.cs


示例15: ConnectCore

        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();
        }
开发者ID:geoffkizer,项目名称:corefx,代码行数:8,代码来源:TCPClient.Unix.netstandard17.cs


示例16: setBroadcastIPs

 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);
     }
 }
开发者ID:Seraphli,项目名称:TheInsectersWar,代码行数:8,代码来源:zzBroadcastSender.cs


示例17: InitiateSocket

 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);
 }
开发者ID:sysexits,项目名称:2DRoguelike,代码行数:8,代码来源:UDPClient.cs


示例18: SendObservable

    /// <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));
    }
开发者ID:ibebbs,项目名称:Rxx,代码行数:14,代码来源:PingExtensions.cs


示例19: DemoMain

	public DemoMain(IPAddress ip, int port, int bufferSize, int maxUserCount)
	{
		_serverEndPoint = new IPEndPoint(ip, port);
		 
		
		_listenArgs = new SocketAsyncEventArgs();
		_listenArgs.Completed += StartReceiving;
	}
开发者ID:hebbaixue99,项目名称:XJDemoServer,代码行数:8,代码来源:DemoMain.cs


示例20: Start

    /// <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);
    }
开发者ID:ibebbs,项目名称:Rxx,代码行数:24,代码来源:ObservableTcpListener.cs



注:本文中的IPAddress类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# IPAddressPool类代码示例发布时间:2022-05-24
下一篇:
C# IOwinRequest类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap