2

I developing an app that connects devices on the same network.

Any devices can be the server, I want clients to be able to find the server automatically without users having to enter the IP address of the server manually.

This is how I plan to do it:

  1. Find the IP of the client, eg 192.168.0.2
  2. Loop through 192.168.0.(0->255)
  3. Try to connect with all those IPs until the connection success

Is that the right way? Can I do it faster? Do IP on the same network always in the range of x.x.x.(0->255)?

I'm using both Java and JavaScript(Node.js) if that is relevance.

leloctai
  • 191
  • 3
  • 14
  • 1
    As @GhostCat writes, broadcast will hit every machine on a LAN, but it also interrupts every machine on a LAN, and that is not necessarily desirable. To solve that problem, you have multicast, which is a broadcast to a group of machine that listen for packets sent to a multicast group. It is a selective for of broadcast. If you have hosts subscribe to a multicast group, then only those hosts are interrupted with the multicast traffic. The server could subscribe to a multicast group. – Ron Maupin Feb 07 '17 at 15:02

2 Answers2

5

One option here: instead of "iterating" the address range and sending individual packets to each address; you could consider sending a broadcast to the whole subnet.

In other words: your client just shouts "I am here"; the server "hears" that and responds; similar to how protocols like DHCP work.

Edit on the comment on how to react to "broadcast not answered":

Actually, you are now coming closer to those topics that make "distributed" computing hard. There are many problems that could kick in; and many different solutions to them.

It starts with: do you go with one broadcast; or instead try multiple times?! And maybe increase the delays between subsequent broadcasts?

Thing is: nobody here can tell you that. The answers very much depend on your "domain", and what makes the most sense to the users of your application.

My suggestion here: look into existing open source products that do similar things; and study what kind of problems they identified; and how they deal with that. I know, this is pretty broad; but that "broadness" comes out of "the overall subject is really broad".

Community
  • 1
  • 1
GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • Thanks you for your answer. I'm trying to implement this. But there a thing, how long should I wait before deciding there're no server? Will this kind of thing take milliseconds or seconds? – leloctai Feb 07 '17 at 14:46
  • Did you find a way to do this? obv under a common LAN setup. – omarojo Apr 06 '17 at 23:57
0

udp broadcast is how my client finds my server on the local network. the server sends back the port number the socket server is using for connections

when the server is running, the response is near instant, so I only have a 2 second timeout, and only try once

Sam
  • 51
  • 1
  • 8