Search code examples
c#socketstcp

What IP do I need to use to communicate over LAN using Sockets in C#?


I'm currently trying to make an app wherein 2 devices communicate over a network. I'm using Sockets in C# for this. I've figured out how you connect to localhost, however, to communicate over a network, I'm not sure what IP to use.

As far as I know, to communicate with localhost, it seems like you just do this:

IPAddress IP = Dns.GetHostEntry("localhost").AddressList[0];

Or...

IPAddress IP = Dns.GetHostEntry(Dns.GetHostName()).AddressList[0];

Which I think returns the same value: 127.0.0.1, and that works great.

So to connect over the network, I thought I might use the server's public IP. If I ping it from the client, it echoes, so I thought there wouldn't be a problem.

However, when trying to use it by putting it as a string into 'IPAddress.Parse("XXXX");' I get the socket exception: "The requested address is not valid in its context". It throws that exception on Server.Start(); therefore it's not an issue with receiving the connection from the client or anything like that.

I'm not sure why. I couldn't find any concise fix or tutorial for this. Or maybe my wording was off, in any case, any help would be appreciated. Is there another specific IP I need to use, or another method to do this entirely?


Solution

  • If both devices are in the same Network you can use the Broadcast address of the Network to send UDP Packages to all Devices in the Network.

    If you have a dedicated Server for this, you have to address the Server, where your Socket listener is running on.

    Maybe checkout this tutorial to get an idea how it yould work:

    Asynchronous Server Socket Example

    If i missunderstood your context don´t hestitate to correct me.