How to get IP addresses of all devices in local network with Unity UNET in C#?

岁酱吖の 提交于 2019-11-29 08:44:37

There are two way to do this:

1.UDP

It's a long process but can be done with UDP.

1.First thing to do is to get your local IP Address. If your local ip is 192.168.1.13, you have to take out the last octet which is 13 and replace it with 255.

2.Start a UDP server in all games and listen to IPAddress.Any with any port you want. It is recommended to go with port >=9000. The ports below are usually used by some other Apps. If anything is received from client, send something back to the client to let the client know that you are available.

3.To search for game, create a UDP client and send something to that IP address from #1 which ends with 255, then listen to listen to IPAddress.Any to see if there is response. If response/message is received from any server, store the IP from which the message is received from to an array or List.

4.You can then use those stored IP from #3 to find all available devices on your network.

Here is a working example.

The bad side about this is that it won't work if you have the free version of Unity. There is a restriction that requires you to have Unity Pro in order to use any raw socket API from C#. No longer true with Unity 5 and above. This can now be used in Unity 5 and up without a pro license.


2.NetworkDiscovery

The good news is that Unity made this easier for you in version 5.3 or so. I can't remember what version but make sure to have the latest version. You don't need to use Unity Pro for this to work.

You can use NetworkDiscovery class to do this in new version of Unity. Simply call NetworkDiscovery.StartAsServer() to broadcasting messages to clients. On the client side, you can listen to the Broadcast by calling NetworkDiscovery.StartAsClient(). You can use the OnReceivedBroadcast(string fromAddress, string data); to see which device you received from. It couldn't get easier than this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!