Tomas Pangonis Tomas Pangonis -4 years ago 99
C# Question

Connecting to another PC in LAN via sockets in C#

So I'm trying to connect to another PC via TCP protocol using sockets, 192.168.1.72 is another PC's address, however, I'm not relly sure im going the right road. I have server also oon different computer, and theese two programs seem to work well on same computer, when in line with

_clientSocket.Connect();
, i use
IPAdress.Loopback
instead o
host
. Am I doint the right aproach, or should i look elsewhere, and if i am, how can i make this function work, because now it simply crashes and indicates there is something wrong with
host
declaration

private static void LoopConnect()
{
IPAddress host = new IPAddress(Encoding.ASCII.GetBytes("192.168.1.72"));


int attempts = 0;

while(!_clientSocket.Connected)
{
try
{
attempts++;
_clientSocket.Connect(host, 100);
}
catch (SocketException)
{
Console.Clear();
Console.WriteLine("Connection attempts: " + attempts.ToString());

}
}
Console.Clear();
Console.WriteLine("Connected");


}

Answer Source

If you supply the IP adddress as a string, you need to use the static Parse method:

IPAddress host = IPAddress.Parse("192.168.1.72");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download