本文整理汇总了C#中IPAddress类的典型用法代码示例。如果您正苦于以下问题:C# IPAddress类的具体用法?C# IPAddress怎么用?C# IPAddress使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
IPAddress类属于命名空间,在下文中一共展示了IPAddress类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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;
}
示例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));
}
示例3: UDPListener
public UDPListener(int portToListen, IPAddress ip, double time)
{
_port = portToListen;
_endPoint = new IPEndPoint(ip, portToListen);
_client = new UdpClient(_endPoint);
_timeToWait = time;
}
示例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;
}
示例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);
}
示例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;
}
示例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);
}
示例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));
}
示例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);
}
示例10: SetServerIp
public static void SetServerIp(string ip)
{
IPAddress serverIp;
var done = IPAddress.TryParse(ip, out serverIp);
if (done)
_serverIp = serverIp;
}
示例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(
}
示例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));
}
示例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);
}
}
}
示例14: Create
public static IPConfiguration Create(IPAddress address, IPAddress mask)
{
return new IPConfiguration
{
Address = address,
Mask = mask
};
}
示例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();
}