networking
c# Getting your machine’s IP addresses.
by brian on Mar.17, 2009, under .NET, c#, c# coding GUI, coding, networking
Here is the simple way to get all of the IP addresses for you machine. This code filters out everything but IPv4 address, but to truly get everything just remove the if statement.
string hostName = Dns.GetHostName();
var addrs = Dns.GetHostAddresses(hostName);
bool hasIP = false;
for (int i = 0; i < addrs.Length; i++)
{
IPAddress addr = addrs[i];
if (addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
si.DataIP = addr.ToString();
hasIP = true;
break;
}
}
c# non-blocking sockets
by brian on Sep.15, 2008, under .NET, c#, networking
There doesn’t seem to be much written on blocking socket with c#. So I’ll write a very short piece, and I’ll only concentrate on client sockets.
Creating a socket is easy here is how:
using System.Net.Sockets; //... // Creating a connection Socket client; client = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); client.Connect(hostName, port); client.Blocking = false; // This needs to be done after Connect or it will error out.
Here’s how to write data to the socket
// Writing information to the socket
byte[] buffer = ASCIIEncoding.ASCII.GetBytes(messageText);
foreach (byte c in buffer)
{
SocketError err = SocketError.WouldBlock;
// need to try again if the socket would have blocked
while ( err == SocketError.WouldBlock )
{
// this version of Send must be used or an exception would be thrown, which I feel is a pain
// to deal with -- this way you can see handle the error appropriately.
client.Send(buffer, 0, 1, SocketFlags.None, out err );
}
if ( err != SocketError.Success )
{
// handle error
break;
}
}
And now code to read from a non-blocking socket
// Reading from the socket
// this loop keeps going until there is a socket error or a '0' byte is read which
// in this example marks the end of the message
System.Text.StringBuilder message = new System.Text.StringBuilder();
while ( true )
{
byte c = 0;
int bytesRead;
SocketError err;
// read a character.
bytesRead = client.Receive(buffer, 0, 1, SocketFlags.None, out err );
// checking what happened
if ( SocketError.Success == err )
{
// read a byte! Let's process it
if ( bytesRead > 0 )
{
// found a null character -- in this case it makes the end of a message.
if (c == 0)
{
// null terminated message received
break;
}
else
message.Append((char)c);
}
}
}
else if ( SocketError.WouldBlock != err )
{
break;
}
}
