本文整理汇总了C#中System.Net.IPEndPoint.Serialize方法的典型用法代码示例。如果您正苦于以下问题:C# IPEndPoint.Serialize方法的具体用法?C# IPEndPoint.Serialize怎么用?C# IPEndPoint.Serialize使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.IPEndPoint
的用法示例。
在下文中一共展示了IPEndPoint.Serialize方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: PingHost
/// <summary>
/// Ping the given host
/// </summary>
/// <param name="ip">The IP to ping</param>
/// <param name="timeout">The timeout of the operation</param>
/// <returns>True/false wether the host is alive or not</returns>
public bool PingHost( IPAddress ip, int timeout )
{
EndPoint remote = new IPEndPoint( ip, 8 );
SocketAddress sa = remote.Serialize();
// send the echo request
sock.SendTo( IcmpPacket.CreatePacket().GetBytes(), remote );
sock.SetSocketOption( SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout, timeout );
bool recv = false;
byte[] bytes = new byte[MAX_ACCEPTED];
while(!recv)
{
if( sock.ReceiveFrom( bytes, ref remote ) == SOCK_ERROR )
{
sock.Close();
break; // not alive
}
else
{
recv = true;
}
}
sock.Close();
return recv;
}
示例2: CreateSockaddrStructure
/// <summary>
/// Creates an unmanaged sockaddr structure to pass to a WinAPI function.
/// </summary>
/// <param name="ipEndPoint">IP address and port number</param>
/// <returns>a handle for the structure. Use the AddrOfPinnedObject Method to get a stable pointer to the object. </returns>
/// <remarks>When the handle goes out of scope you must explicitly release it by calling the Free method; otherwise, memory leaks may occur. </remarks>
public static GCHandle CreateSockaddrStructure(IPEndPoint ipEndPoint) {
SocketAddress socketAddress = ipEndPoint.Serialize();
// use an array of bytes instead of the sockaddr structure
byte[] sockAddrStructureBytes = new byte[socketAddress.Size];
GCHandle sockAddrHandle = GCHandle.Alloc(sockAddrStructureBytes, GCHandleType.Pinned);
for (int i = 0; i < socketAddress.Size; ++i) {
sockAddrStructureBytes[i] = socketAddress[i];
}
return sockAddrHandle;
}
示例3: GetSockaddrBytes
/// <summary>
/// This routine converts an IPEndPoint into a byte array that represents the
/// underlying sockaddr structure of the correct type. Currently this routine
/// supports only IPv4 and IPv6 socket address structures.
/// </summary>
/// <param name="endPoint">IPEndPoint to convert to a binary form</param>
/// <returns>Binary array of the serialized socket address structure</returns>
public static byte[] GetSockaddrBytes( IPEndPoint endPoint )
{
SocketAddress socketAddress = endPoint.Serialize();
byte[] sockaddrBytes;
sockaddrBytes = new byte[socketAddress.Size];
for( int i = 0 ; i < socketAddress.Size ; i++ )
{
sockaddrBytes[i] = socketAddress[i];
}
return sockaddrBytes;
}
示例4: Write
public void Write(IPEndPoint value)
{
SocketAddress socketAddress = value.Serialize();
byte[] socketAddressBytes = new byte[28];
for (int i = 0; i < socketAddress.Size; i++)
{
socketAddressBytes[i] = socketAddress[i];
}
this.Write(socketAddressBytes);
}
示例5: GetBytes
/// <summary>
/// This routine converts an IPEndPoint into a byte array that represents the
/// underlying sockaddr structure of the correct type. Currently this routine
/// supports IPv4 and IPv6 socket address structures. A sockaddr structure
/// InterNetwork (v4) could be { 2, 0, 0, 156, 207, 46, 197, 32, 0, 0, 0, 0, 0, 0, 0, 0 }.
/// The first two bytes represents the address family, the next two bytes the
/// port number in big-endian. The next 4 bytes are reserved for the ip-address.
///
/// The in6_addr structure represents an IPv6 internet address. This
/// InterNetwork (v6) structure is longer and holds a 16 byte long ip-address.
///
/// This method will always return 32 bytes, padding from the right with zeros.
/// </summary>
/// <param name="endPoint">IPEndPoint to convert to a binary form</param>
/// <returns>Binary array of the serialized socket address structure</returns>
public static byte[] GetBytes(IPEndPoint endPoint)
{
SocketAddress socketAddress = endPoint.Serialize();
byte[] sockaddrBytes = new byte[socketAddress.Size];
for (int i = 0; i < socketAddress.Size; i++)
{
sockaddrBytes[i] = socketAddress[i];
}
byte[] buffer = new byte[32];
Array.Copy(sockaddrBytes, buffer, socketAddress.Size);
return buffer;
}
示例6: Ctor_LongInt
public void Ctor_LongInt ()
{
IPEndPoint ep = new IPEndPoint (0, 80);
Assert.AreEqual (new IPAddress (0), ep.Address, "Address");
Assert.AreEqual (AddressFamily.InterNetwork, ep.AddressFamily, "AddressFamily");
Assert.AreEqual (80, ep.Port, "Port");
Assert.Throws<ArgumentNullException> (delegate {
ep.Create (null);
}, "Create(null)");
// note: documented as ArgumentException
Assert.Throws<ArgumentOutOfRangeException> (delegate {
SocketAddress sa = new SocketAddress (AddressFamily.InterNetwork, 1);
Assert.IsTrue (sa.Size < 8, "Size");
ep.Create (sa);
}, "Create(bad-size)");
Assert.Throws<ArgumentException> (delegate {
SocketAddress sa = new SocketAddress (AddressFamily.InterNetworkV6);
Assert.IsTrue (sa.Size >= 8, "SizeV6");
ep.Create (sa);
}, "Create(InterNetworkV6)");
Assert.Throws<ArgumentException> (delegate {
SocketAddress sa = new SocketAddress (AddressFamily.Unknown);
ep.Create (sa);
}, "Create(Unknown)");
Assert.Throws<ArgumentException> (delegate {
SocketAddress sa = new SocketAddress (AddressFamily.Unspecified);
ep.Create (sa);
}, "Create(Unspecified)");
EndPoint ep2 = ep.Create (new SocketAddress (AddressFamily.InterNetwork));
Assert.IsFalse (ep.Equals (null), "Equals(null)");
Assert.IsTrue (ep.Equals (ep), "Equals(self)");
Assert.IsFalse (ep.Equals (ep2), "Equals(Create)");
Assert.AreEqual ("InterNetwork:16:{0,80,0,0,0,0,0,0,0,0,0,0,0,0}", ep.Serialize ().ToString (), "Serialize");
Assert.AreEqual ("0.0.0.0:80", ep.ToString (), "ToString");
}
示例7: TryConnect
public static bool TryConnect(string ipString, int port)
{
if (!Initialized)
{
var wsaData = new WSAData();
if (WSAStartup(0x0202, out wsaData) != 0) return false;
m_Buffer = typeof(SocketAddress).GetField("m_Buffer", (BindingFlags.Instance | BindingFlags.NonPublic));
Initialized = true;
}
IPAddress address;
if (!IPAddress.TryParse(ipString, out address)) return false;
if (!((port >= 0) && (port <= 0xffff))) return false;
var remoteEP = new IPEndPoint(address, port);
SocketAddress socketAddress = remoteEP.Serialize();
IntPtr m_Handle = WSASocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, IntPtr.Zero, 0, 1 /*overlapped*/);
if (m_Handle == new IntPtr(-1)) return false;
new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, remoteEP.Address.ToString(), remoteEP.Port).Demand();
var buf = (byte[])m_Buffer.GetValue(socketAddress);
bool result = (WSAConnect(m_Handle, buf, socketAddress.Size, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero) == 0);
closesocket(m_Handle);
return result;
}
示例8:
/// <summary>
/// Map the intercepted IPEndPoint to the LspSession.
/// </summary>
/// <param name="index">Intercepted IPEndPoint. </param>
/// <param name="transportType">Tcp or Udp</param>
/// <returns>Mapped LspSession</returns>
private LspSessionInfoCollection this[IPEndPoint index, StackTransportType transportType]
{
get
{
string strKey = transportType.ToString() + index.Serialize().ToString();
if (sessionMap.ContainsKey(strKey))
{
return sessionMap[strKey];
}
else
{
return null;
}
}
set
{
string strKey = transportType.ToString() + index.Serialize().ToString();
sessionMap[strKey] = value;
}
}
示例9: Ctor_IPAddressInt
public void Ctor_IPAddressInt ()
{
Assert.Throws<ArgumentNullException> (delegate {
new IPEndPoint (null, 80);
}, "IPEndPoint(null,int)");
IPAddress a = new IPAddress (new byte [16]);
Assert.AreEqual (AddressFamily.InterNetworkV6, a.AddressFamily, "IPAddress.AddressFamily");
IPEndPoint ep = new IPEndPoint (a, 0);
Assert.IsTrue (Object.ReferenceEquals (a, ep.Address), "Address");
Assert.AreEqual (AddressFamily.InterNetworkV6, ep.AddressFamily, "AddressFamily");
Assert.AreEqual (0, ep.Port, "Port");
Assert.Throws<ArgumentException> (delegate {
SocketAddress sa = new SocketAddress (AddressFamily.InterNetwork);
ep.Create (sa);
}, "Create(InterNetwork)");
Assert.Throws<ArgumentException> (delegate {
SocketAddress sa = new SocketAddress (AddressFamily.Unknown);
ep.Create (sa);
}, "Create(Unknown)");
Assert.Throws<ArgumentException> (delegate {
SocketAddress sa = new SocketAddress (AddressFamily.Unspecified);
ep.Create (sa);
}, "Create(Unspecified)");
EndPoint ep2 = ep.Create (new SocketAddress (AddressFamily.InterNetworkV6));
Assert.IsFalse (ep.Equals (null), "Equals(null)");
Assert.IsTrue (ep.Equals (ep), "Equals(self)");
Assert.IsTrue (ep.Equals (ep2), "Equals(Create)");
Assert.AreEqual ("InterNetworkV6:28:{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}", ep.Serialize ().ToString (), "Serialize");
// Assert.AreEqual ("0000:0000:0000:0000:0000:0000:0.0.0.0:0", ep.ToString (), "ToString");
}
示例10: Disconnect
/// <summary>
/// Disconnect the remote EndPoint, and clean up the resources.
/// </summary>
/// <param name="localEndpoint">SDK listening endpoint</param>
/// <param name="remoteEndpoint">the endpoint of real remote client</param>
/// <param name="transportType">Tcp or Udp</param>
internal void Disconnect(IPEndPoint localEndpoint, IPEndPoint remoteEndpoint,
StackTransportType transportType)
{
if (disposed)
{
return;
}
IPEndPoint connectableEndpoint = GetConnectableEndpoint(localEndpoint);
string strKey = transportType.ToString() + connectableEndpoint.Serialize().ToString();
if (sessionMap.ContainsKey(strKey))
{
Dictionary<string, IPEndPoint> endPointMap =
sessionMap[strKey].endPoints;
strKey = remoteEndpoint.Serialize().ToString();
if (transportType == StackTransportType.Udp)
{
endPointMap.Remove(strKey);
}
else
{
//For tcp, each endpoint-to-endpoint pair has two records in the dictionary.
IPEndPoint mappedEndpoint = endPointMap[strKey];
endPointMap.Remove(strKey);
endPointMap.Remove(mappedEndpoint.Serialize().ToString());
}
}
}
示例11: CreateAndSerialize
public void CreateAndSerialize()
{
SocketAddress addr = endPoint1.Serialize ();
EndPoint endPoint3 = endPoint2.Create (addr);
Assert.IsTrue (endPoint1.Equals (endPoint3), "#1");
IPAddress ipAddress = IPAddress.Parse ("255.255.255.255");
IPEndPoint endPoint4 = new IPEndPoint (ipAddress, MyMaxPort);
addr = endPoint4.Serialize ();
EndPoint endPoint5 = endPoint2.Create(addr);
Assert.IsTrue (endPoint4.Equals (endPoint5), "#2");
Assert.AreEqual (endPoint5.ToString (), "255.255.255.255:" + MyMaxPort, "#3");
}
示例12: Connect
public void Connect ()
{
/* If result.EndPoint is non-null,
* this is the standard one-address
* connect attempt. Otherwise
* Addresses must be non-null and
* contain a list of addresses to try
* to connect to; the first one to
* succeed causes the rest of the list
* to be ignored.
*/
if (result.EndPoint != null) {
try {
if (!result.Sock.Blocking) {
int success;
result.Sock.Poll (-1, SelectMode.SelectWrite, out success);
if (success == 0) {
result.Sock.seed_endpoint = result.EndPoint;
result.Sock.connected = true;
} else {
result.Complete (new SocketException (success));
return;
}
} else {
result.Sock.seed_endpoint = result.EndPoint;
result.Sock.Connect (result.EndPoint);
result.Sock.connected = true;
}
} catch (Exception e) {
result.Complete (e);
return;
}
result.Complete ();
} else if (result.Addresses != null) {
int error = (int) SocketError.InProgress; // why?
foreach(IPAddress address in result.Addresses) {
IPEndPoint iep = new IPEndPoint (address, result.Port);
SocketAddress serial = iep.Serialize ();
Socket.Connect_internal (result.Sock.socket, serial, out error);
if (error == 0) {
result.Sock.connected = true;
result.Sock.seed_endpoint = iep;
result.Complete ();
return;
} else if (error != (int)SocketError.InProgress &&
error != (int)SocketError.WouldBlock) {
continue;
}
if (!result.Sock.Blocking) {
int success;
result.Sock.Poll (-1, SelectMode.SelectWrite, out success);
if (success == 0) {
result.Sock.connected = true;
result.Sock.seed_endpoint = iep;
result.Complete ();
return;
}
}
}
result.Complete (new SocketException (error));
} else {
result.Complete (new SocketException ((int)SocketError.AddressNotAvailable));
}
}
示例13: QueryRoutingInterface
private static IPEndPoint QueryRoutingInterface(Socket socket, IPEndPoint remoteEndPoint) {
SocketAddress address = remoteEndPoint.Serialize();
byte[] remoteAddrBytes = new byte[address.Size];
for (int i = 0; i < address.Size; i++) {
remoteAddrBytes[i] = address[i];
}
byte[] outBytes = new byte[remoteAddrBytes.Length];
socket.IOControl(IOControlCode.RoutingInterfaceQuery, remoteAddrBytes, outBytes);
for (int i = 0; i < address.Size; i++) {
address[i] = outBytes[i];
}
EndPoint ep = remoteEndPoint.Create(address);
return (IPEndPoint)ep;
}
示例14: sortIpAddressList
public string sortIpAddressList(string IPAddressList)
{
//---------------------------------------------------------------
//If the input is nothing, return nothing
//---------------------------------------------------------------
if(IPAddressList == null || IPAddressList.Length == 0)
{
return string.Empty;
}
//---------------------------------------------------------------
//The input string is supposed to be a list of IPAddress strings
//separated by a semicolon
//---------------------------------------------------------------
string[] IPAddressStrings = IPAddressList.Split(new char[] {';'});
if(IPAddressStrings.Length > MAX_IPADDRESS_LIST_LENGTH)
{
throw new ArgumentException(string.Format(
SR.GetString(SR.net_max_ip_address_list_length_exceeded),
MAX_IPADDRESS_LIST_LENGTH), "IPAddressList");
}
//----------------------------------------------------------------
//If there are no separators, just return the original string
//----------------------------------------------------------------
if(IPAddressStrings.Length == 1)
{
return IPAddressList;
}
//----------------------------------------------------------------
//Parse the strings into Socket Address buffers
//----------------------------------------------------------------
SocketAddress[] SockAddrIn6List = new SocketAddress[IPAddressStrings.Length];
for(int i = 0; i < IPAddressStrings.Length; i++)
{
//Trim leading and trailing spaces
IPAddressStrings[i] = IPAddressStrings[i].Trim();
if(IPAddressStrings[i].Length == 0)
throw new ArgumentException(SR.GetString(SR.dns_bad_ip_address), "IPAddressList");
SocketAddress saddrv6 = new SocketAddress(AddressFamily.InterNetworkV6,
SocketAddress.IPv6AddressSize);
//Parse the string to a v6 address structure
SocketError errorCode =
UnsafeNclNativeMethods.OSSOCK.WSAStringToAddress(
IPAddressStrings[i],
AddressFamily.InterNetworkV6,
IntPtr.Zero,
saddrv6.m_Buffer,
ref saddrv6.m_Size );
if(errorCode != SocketError.Success)
{
//Could not parse this into a SOCKADDR_IN6
//See if we can parse this into s SOCKEADDR_IN
SocketAddress saddrv4 = new SocketAddress(AddressFamily.InterNetwork, SocketAddress.IPv4AddressSize);
errorCode =
UnsafeNclNativeMethods.OSSOCK.WSAStringToAddress(
IPAddressStrings[i],
AddressFamily.InterNetwork,
IntPtr.Zero,
saddrv4.m_Buffer,
ref saddrv4.m_Size );
if(errorCode != SocketError.Success)
{
//This address is neither IPv4 nor IPv6 string throw
throw new ArgumentException(SR.GetString(SR.dns_bad_ip_address), "IPAddressList");
}
else
{
//This is a valid IPv4 address. We need to map this to a mapped v6 address
IPEndPoint dummy = new IPEndPoint(IPAddress.Any, 0);
IPEndPoint IPv4EndPoint = (IPEndPoint)dummy.Create(saddrv4);
byte[] IPv4AddressBytes = IPv4EndPoint.Address.GetAddressBytes();
byte[] IPv6MappedAddressBytes = new byte[16]; //IPv6 is 16 bytes address
for(int j = 0; j < 10; j++) IPv6MappedAddressBytes[j] = 0x00;
IPv6MappedAddressBytes[10] = 0xFF;
IPv6MappedAddressBytes[11] = 0xFF;
IPv6MappedAddressBytes[12] = IPv4AddressBytes[0];
IPv6MappedAddressBytes[13] = IPv4AddressBytes[1];
IPv6MappedAddressBytes[14] = IPv4AddressBytes[2];
IPv6MappedAddressBytes[15] = IPv4AddressBytes[3];
IPAddress v6Address = new IPAddress(IPv6MappedAddressBytes);
IPEndPoint IPv6EndPoint = new IPEndPoint(v6Address, IPv4EndPoint.Port);
saddrv6 = IPv6EndPoint.Serialize();
}
}
//At this point,we have SOCKADDR_IN6 buffer
//add them to the list
SockAddrIn6List[i] = saddrv6;
}
//----------------------------------------------------------------
//All the IPAddress strings are parsed into
//either a native v6 address or mapped v6 address
//The Next step is to prepare for calling the WSAIOctl
//By creating a SOCKET_ADDRESS_LIST
//----------------------------------------------------------------
//.........这里部分代码省略.........
示例15: Main
/// <summary>
/// Test TCP client
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
Console.WriteLine("TCP client.");
Console.WriteLine();
Console.WriteLine("|--- \"exit\" to exit. ---|");
Console.WriteLine("|--- \"start {cn}\" to start {cn} number of connections.---|");
Console.WriteLine();
Console.Write("Please enter remote address and port: ");
bool portReady = false;
string line = Console.ReadLine();
// input management stuff. boring.
while (line != "exit")
{
if (!portReady)
{
try
{
string[] ss = line.Split(':');
port = int.Parse(ss[1]);
IPAddress add = IPAddress.Parse(ss[0]);
clientEndpoint = new IPEndPoint(add, port);
address = clientEndpoint.Serialize().ToString();
if (port > short.MaxValue || port < 2)
{
Console.WriteLine("Invalid port.");
Console.Write("Please enter remote address and port: ");
}
else
{
Start();
portReady = true;
}
}
catch
{
Console.WriteLine("Invalid address.");
Console.Write("Please enter remote address and port: ");
}
}
else
{
if (line.StartsWith("start "))
{
int count = 0;
try
{
count = int.Parse(line.Substring("start ".Length));
}
catch { }
Console.WriteLine("Starting " + count + " connections.");
for (int i = 0; i < count; i++)
{
// this starts another connection
Start();
}
}
else
{
try
{
byte[] bytes = Encoding.UTF8.GetBytes(line + "\n");
lock (socketList)
{
foreach (SocketInfo info in socketList)
{
info.socket.Send(bytes, bytes.Length, SocketFlags.None);
}
}
}
catch
{
Console.WriteLine("Unable to send data. Connection lost.");
}
}
}
line = Console.ReadLine();
}
Console.Write("Shutting down client... ");
try
{
lock (socketList)
{
for (int i = socketList.Count - 1; i >= 0; i--)
{
try {
socketList[i].socket.Shutdown(SocketShutdown.Both);
socketList[i].socket.Close();
} catch {}
socketList.RemoveAt(i);
}
}
}
catch { }
Console.WriteLine("Bye.");
//.........这里部分代码省略.........