Hello there.
For some tests, I need to be able to connect from a device (= android/ios) to another (= android/ios) without Internet ; basically, a device will active his hotspot wifi and the other ones will connect to this hotspot. I need these phones to be able to detect the others (and also find a server but for now, I just want them to see all devices on their local network).
To do that, I use the C# class “Ping”. But apparently, I do it wrong 'cause it just doesn’t work I just try to send a ping on 255.255.255.255 to see if, at least, one device send me a pong…
Here is my (entire) code :
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
public class LanManager {
public List<KeyValuePair<string, int>> _addresses { get; private set; }
// Addresse that the ping will reach
public string addressToBroadcast = "255.255.255.255";
public int timeout = 1000;
public LanManager() {
_addresses = new List<KeyValuePair<string,int>>();
}
public void SendPing() {
_addresses.Clear();
System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
// 128 TTL and DontFragment
PingOptions pingOption = new PingOptions(128, true);
// Once the ping has reached his target (or has timed out), call this function
ping.PingCompleted += ping_PingCompleted;
byte[] buffer = Encoding.ASCII.GetBytes("ping");
// Do not block the main thread
ping.SendAsync(addressToBroadcast, timeout, buffer, pingOption, addressToBroadcast);
}
private void ping_PingCompleted(object sender, PingCompletedEventArgs e) {
string address = (string)e.UserState;
// For debug purpose
_addresses.Add(new KeyValuePair<string, int>("127.0.0.1", 26000));
if (e.Cancelled) {
Debug.Log("Ping Canceled!");
}
if (e.Error != null) {
Debug.Log(e.Error);
}
displayReply(e.Reply);
}
private void displayReply(PingReply reply) {
if (reply != null) {
if (reply.Status == IPStatus.Success) {
Debug.Log("Pong from " + reply.Address);
}
} else {
Debug.Log("No reply");
}
}
}
I know I’m doing something wrong about the address, because if I set a real address (like 192.168.1.48, which his my address or even if I set the printer’s address), I get a pong. But I need to be able to detect any devices on the current local network.
PS: I don’t want to use a Master Server !! The purpose of this is to be able to play a game without any connection and on a mobile phone (which will not start a Master Server).
Thank you !
Sbizz.