Windows phone a socket operation encountered a dead network - windows-phone-7

I am trying to get the IP address of networks like Wi-Fi,Data Network. I use the following class to find the IP.
public class MyIPAddress
{
Action<IPAddress> FoundCallback;
UdpAnySourceMulticastClient MulticastSocket;
const int PortNumber = 50000; // pick a number, any number
string MulticastMessage = "FIND-MY-IP-PLEASE" + new Random().Next().ToString();
public void Find(Action<IPAddress> callback)
{
FoundCallback = callback;
MulticastSocket = new UdpAnySourceMulticastClient(IPAddress.Parse("239.255.255.250"), PortNumber);
MulticastSocket.BeginJoinGroup((result) =>
{
try
{
MulticastSocket.EndJoinGroup(result);
GroupJoined(result);
}
catch (Exception ex)
{
// Debug.WriteLine("EndjoinGroup exception {0}", ex.Message);
// This can happen eg when wifi is off
FoundCallback(null);
}
},
null);
}
void callback_send(IAsyncResult result)
{
}
byte[] MulticastData;
bool keepsearching;
void GroupJoined(IAsyncResult result)
{
MulticastData = Encoding.UTF8.GetBytes(MulticastMessage);
keepsearching = true;
MulticastSocket.BeginSendToGroup(MulticastData, 0, MulticastData.Length, callback_send, null);
while (keepsearching)
{
try
{
byte[] buffer = new byte[MulticastData.Length];
MulticastSocket.BeginReceiveFromGroup(buffer, 0, buffer.Length, DoneReceiveFromGroup, buffer);
}
catch (Exception ex)
{
// Debug.WriteLine("Stopped Group read due to " + ex.Message);
keepsearching = false;
}
}
}
void DoneReceiveFromGroup(IAsyncResult result)
{
string str = "";
IPEndPoint where;
int responselength = MulticastSocket.EndReceiveFromGroup(result, out where);
byte[] buffer = result.AsyncState as byte[];
if (responselength == MulticastData.Length && buffer.SequenceEqual(MulticastData))
{
str = where.Address.ToString();
keepsearching = false;
FoundCallback(where.Address);
}
Console.WriteLine(str);
}
}
I was successful to find out the IP address of connected Wi-Fi. I turn off Wi-Fi and turn on the Data Connection. I am not able to get the IP address of connected network. I got the error ** a socket operation encountered a dead network**. I have also refer this question A socket operation encountered a dead network. How can I solve this problem ?

Question is a bit old, but answer may be useful for someone:
You get this error, because your MyIPAddress class can only find a local IP (the address inside your internal WiFi network, behind router). To get an external IP address you should call an external server that will tell you your IP (eg. whatismyip.com).

Related

Xamarin: multiple request network pop ups in android 10, when try to connect to wifi in IOT module

I am working on an IOT module with wifi connection,I am testing using a samsung with android 10.
The chip is a ESP8266.The Wi-Fi signal, does not have an internet connection.
the project is developed in xamarin.
The problem, is when I try to connect to the device's signal. When I'm making the connection request, multiple pop ups appear in the device, requesting the connection, and it does not wait until it is connected, immediately the device launches the connection requests again and again, finally crash.
when i'm debugging, the NetworkAvailable runs, but even the phone does not finish connecting to the signal, the phone lunch a new request network again, don't wait until you are actually connected, and I don't know why multiple requests are launched.
Here is my code.
public async Task<bool> Connect(string WiFiName, string WifiPassword)
{
bool result = false;
var formattedSsid = $"\"{WiFiName}\"";
var formattedPassword = $"\"{WifiPassword}\"";
try
{
AutoResetEvent autoResetEvent = new AutoResetEvent(false);
var wifiNetworkSpecifier = new WifiNetworkSpecifier.Builder()
.SetSsid(WiFiName)
.SetWpa2Passphrase(WifiPassword)
.Build();
var networkRequest = new NetworkRequest.Builder()
.AddTransportType(TransportType.Wifi) // we want WiFi
.SetNetworkSpecifier(wifiNetworkSpecifier) // we want _our_ network
.Build();
UnregisterNetworkCallback(_networkCallback);
_networkCallback = new NetworkCallback()
{
NetworkAvailable = network =>
{
result = true;
autoResetEvent.Set(); //signal
},
NetworkUnavailable = () =>
{
result = false;
autoResetEvent.Set(); //signal
},
};
connectivityManager.RequestNetwork(networkRequest, _networkCallback);
autoResetEvent.WaitOne();
}
catch (Exception e)
{
Crashes.TrackError(e);
}
finally
{
}
return result;
}
private void UnregisterNetworkCallback(NetworkCallback _networkCallback)
{
if (_networkCallback != null)
{
try
{
_connectivityManager.UnregisterNetworkCallback(_networkCallback);
}
catch (Exception) {
} finally
{
_networkCallback = null;
}
}
}
public class NetworkCallback : ConnectivityManager.NetworkCallback
{
public Action<Network> NetworkAvailable { get; set; }
public Action NetworkUnavailable { get; set; }
public NetworkCallback()
{
}
public override void OnAvailable(Network network)
{
try
{
WiFiAndroid.connectivityManager.BindProcessToNetwork(null);
WiFiAndroid.connectivityManager.BindProcessToNetwork(network);
}
catch (Exception ex)
{
var error = ex;
}
}
public override void OnUnavailable()
{
base.OnUnavailable();
NetworkUnavailable?.Invoke();
}
}
the image, is the request that is throw over and over again.

Impossible to send a packet Exception When pinging in windows mobile apps code(.net compact)

I am facing this exception "Impossible to send packets" when i am pinging www.google.com in my windows mobile app code (.netcf c#). But, pinging with localhost(127.0.0.1) gives the success result.
How to get resolve from this problem?
Here is my code..
public bool PingTest()
{
int packet=32;
IPHostEntry hostEnt = Dns.GetHostEntry("www.google.com");
IPAddress ip = hostEnt.AddressList[0];
PingOptions options = new PingOptions();
options.Ttl = 128;
options.DontFragment = false;
//Debug.WriteLine("Ip address: " + ip.Address);
Byte[] pkt= new Byte[packet];
Ping ping = new Ping();
try
{
//const string adr = "216.58.197.78";
PingReply pingReply = ping.Send(ip, pkt, 1000, options);
if (pingReply.Status == IPStatus.Success)
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
Debug.WriteLine("The UnHandled Exception is: " + ex.Message);
return false;
}
}

How can I find the IP address of connected network in windows phone?

I am trying to find the IP address of connected network in windows phone. I was successful to find out the IP address of connected Wi-Fi. I have used the following class to find the IP address.
public class MyIPAddress
{
Action<IPAddress> FoundCallback;
UdpAnySourceMulticastClient MulticastSocket;
const int PortNumber = 50000; // pick a number, any number
string MulticastMessage = "FIND-MY-IP-PLEASE" + new Random().Next().ToString();
public void Find(Action<IPAddress> callback)
{
FoundCallback = callback;
MulticastSocket = new UdpAnySourceMulticastClient(IPAddress.Parse("239.255.255.250"), PortNumber);
MulticastSocket.BeginJoinGroup((result) =>
{
try
{
MulticastSocket.EndJoinGroup(result);
GroupJoined(result);
}
catch (Exception ex)
{
// Debug.WriteLine("EndjoinGroup exception {0}", ex.Message);
// This can happen eg when wifi is off
FoundCallback(null);
}
},
null);
}
void callback_send(IAsyncResult result)
{
}
byte[] MulticastData;
bool keepsearching;
void GroupJoined(IAsyncResult result)
{
MulticastData = Encoding.UTF8.GetBytes(MulticastMessage);
keepsearching = true;
MulticastSocket.BeginSendToGroup(MulticastData, 0, MulticastData.Length, callback_send, null);
while (keepsearching)
{
try
{
byte[] buffer = new byte[MulticastData.Length];
MulticastSocket.BeginReceiveFromGroup(buffer, 0, buffer.Length, DoneReceiveFromGroup, buffer);
}
catch (Exception ex)
{
// Debug.WriteLine("Stopped Group read due to " + ex.Message);
keepsearching = false;
}
}
}
void DoneReceiveFromGroup(IAsyncResult result)
{
string str = "";
IPEndPoint where;
int responselength = MulticastSocket.EndReceiveFromGroup(result, out where);
byte[] buffer = result.AsyncState as byte[];
if (responselength == MulticastData.Length && buffer.SequenceEqual(MulticastData))
{
str = where.Address.ToString();
keepsearching = false;
FoundCallback(where.Address);
}
Console.WriteLine(str);
}
}
So by using the above class I can find the IP address of connected Wi-Fi. Now I am try to find the address of network which is connected by Data Connection. In my windows phone I goto Settings --> System --> Cellular and turn on data connection on.
How can I get the IP address of Cellular Network(Data Connection)? Is there any API for that?
you can try this ....
it will work fine for many networks unlike your code which will work only on wifi network due to multicast IP
it will provide you the ip address of the phone ...
public static IPAddress Find()
{
List<string> ipAddresses = new List<string>();
var hostnames = NetworkInformation.GetHostNames();
foreach (var hn in hostnames)
{
if (hn.IPInformation != null)
{
string ipAddress = hn.DisplayName;
ipAddresses.Add(ipAddress);
}
}
IPAddress address = IPAddress.Parse(ipAddresses[0]);
return address;
}

Unity3d server auto discover, LAN only

I need to implement a game with a server in a local network, with no Internet access.
Provided that I can handle the connections and network communication between clients and server if they are connected, I'd like to know if there's a elegant way to make clients discover server's address at startup.
I'm providing my approach as an answer, in order to share the knowledge, but it would be nice to see if there is a more elegant/automatic approach.
Clients will use a specific port to connect to the game server. I implemented a UDP multicast in a different port so clients can get server's IP.
The following code is for both server and client, written in Unity Javascript. On the server side, it will start sending multicast messages every second at port 5100. Clients will listen to the same port, until they detect a new message. Then they identify sender's IP and establish a client-server connection the Unity3d way.
private var server_port : int = 5000;
private var server_ip : String;
// multicast
private var startup_port : int = 5100;
private var group_address : IPAddress = IPAddress.Parse ("224.0.0.224");
private var udp_client : UdpClient;
private var remote_end : IPEndPoint;
function Start ()
{
// loaded elsewhere
if (station_id == "GameServer")
StartGameServer ();
else
StartGameClient ();
}
function StartGameServer ()
{
// the Unity3d way to become a server
init_status = Network.InitializeServer (10, server_port, false);
Debug.Log ("status: " + init_status);
StartBroadcast ();
}
function StartGameClient ()
{
// multicast receive setup
remote_end = IPEndPoint (IPAddress.Any, startup_port);
udp_client = UdpClient (remote_end);
udp_client.JoinMulticastGroup (group_address);
// async callback for multicast
udp_client.BeginReceive (new AsyncCallback (ServerLookup), null);
MakeConnection ();
}
function MakeConnection ()
{
// continues after we get server's address
while (!server_ip)
yield;
while (Network.peerType == NetworkPeerType.Disconnected)
{
Debug.Log ("connecting: " + server_ip +":"+ server_port);
// the Unity3d way to connect to a server
var error : NetworkConnectionError;
error = Network.Connect (server_ip, server_port);
Debug.Log ("status: " + error);
yield WaitForSeconds (1);
}
}
/******* broadcast functions *******/
function ServerLookup (ar : IAsyncResult)
{
// receivers package and identifies IP
var receiveBytes = udp_client.EndReceive (ar, remote_end);
server_ip = remote_end.Address.ToString ();
Debug.Log ("Server: " + server_ip);
}
function StartBroadcast ()
{
// multicast send setup
udp_client = UdpClient ();
udp_client.JoinMulticastGroup (group_address);
remote_end = IPEndPoint (group_address, startup_port);
// sends multicast
while (true)
{
var buffer = Encoding.ASCII.GetBytes ("GameServer");
udp_client.Send (buffer, buffer.Length, remote_end);
yield WaitForSeconds (1);
}
}
Attaching this to your GameObject should do the trick.
Here is a c# version
Thanks
using System.Collections;
using UnityEngine;
using System.Net.Sockets;
using System;
using System.Net;
using System.Text;
public class OwnNetworkManager : MonoBehaviour
{
private int server_port = 5000;
private string server_ip;
// multicast
private int startup_port = 5100;
private IPAddress group_address = IPAddress.Parse("127.0.0.1");
private UdpClient udp_client ;
private IPEndPoint remote_end ;
void Start()
{
// loaded elsewhere
if (Loader.IsPC)
StartGameServer();
else
StartGameClient();
}
void StartGameServer()
{
// the Unity3d way to become a server
NetworkConnectionError init_status = Network.InitializeServer(10,
server_port, false);
Debug.Log("status: " + init_status);
StartCoroutine(StartBroadcast());
}
void StartGameClient()
{
// multicast receive setup
remote_end = new IPEndPoint(IPAddress.Any, startup_port);
udp_client = new UdpClient(remote_end);
udp_client.JoinMulticastGroup(group_address);
// async callback for multicast
udp_client.BeginReceive(new AsyncCallback(ServerLookup), null);
StartCoroutine(MakeConnection());
}
IEnumerator MakeConnection()
{
// continues after we get server's address
while (string.IsNullOrEmpty(server_ip))
yield return null;
while (Network.peerType == NetworkPeerType.Disconnected)
{
Debug.Log("connecting: " + server_ip + ":" + server_port);
// the Unity3d way to connect to a server
NetworkConnectionError error ;
error = Network.Connect(server_ip, server_port);
Debug.Log("status: " + error);
yield return new WaitForSeconds (1);
}
}
/******* broadcast functions *******/
void ServerLookup(IAsyncResult ar)
{
// receivers package and identifies IP
var receiveBytes = udp_client.EndReceive(ar, ref remote_end);
server_ip = remote_end.Address.ToString();
Debug.Log("Server: " + server_ip);
}
IEnumerator StartBroadcast()
{
// multicast send setup
udp_client = new UdpClient();
udp_client.JoinMulticastGroup(group_address);
remote_end = new IPEndPoint(group_address, startup_port);
// sends multicast
while (true)
{
var buffer = Encoding.ASCII.GetBytes("GameServer");
udp_client.Send(buffer, buffer.Length, remote_end);
yield return new WaitForSeconds (1);
}
}
}

BlackBerry - Downloaded images are corrupted on wifi with HttpConnection

In my app I need to download several images from a server. I use this code to get a byte array :
HttpConnection connection = null;
InputStream inputStream = null;
byte[] data = null;
try
{
//connection = (HttpConnection)Connector.open(url);
connection = (HttpConnection)Connector.open(url, Connector.READ_WRITE, true);
int responseCode = connection.getResponseCode();
if(responseCode == HttpConnection.HTTP_OK)
{
inputStream = connection.openInputStream();
data = IOUtilities.streamToBytes(inputStream);
inputStream.close();
}
connection.close();
return data;
}
catch(IOException e)
{
return null;
}
The url are formed with the suffix ";deviceSide=false;ConnectionType=MDS - public" (without spaces) and it is working perfectly well.
The problem is that with phones that do not have a sim card, we can't connect to the internet via the MDS server. So we changed to use the connection factory and let BB choose whatever he wants :
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(url);
if (connDesc != null)
{
final HttpConnection httpConn;
httpConn = (HttpConnection)connDesc.getConnection();
try
{
httpConn.setRequestMethod(HttpConnection.GET);
final int iResponseCode = httpConn.getResponseCode();
if(iResponseCode == HttpConnection.HTTP_OK)
{
InputStream inputStream = null;
try{
inputStream = httpConn.openInputStream();
byte[] data = IOUtilities.streamToBytes(inputStream);
return data;
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
finally{
try
{
inputStream.close();
} catch (IOException e)
{
e.printStackTrace();
return null;
}
}
}
}
catch (IOException e)
{
System.err.println("Caught IOException: " + e.getMessage());
}
}
return null;
The connection works because it select the good prefix (interface=wifi in our case), but this create another problem.
Some images are not well downloaded, some of them (not the sames at each try) are corrupted, but only when the phone use a wifi connection to get these images.
How can I avoid this problem ? What method to get a connection do I have to use ? Is it possible to check if the user have a sim card in orderto use MDS - public ?
Here is an example of a corrupted image :
error image http://nsa30.casimages.com/img/2012/06/28/120628033716123822.png
try this:
public static String buildURL(String url) {
String connParams = "";
if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
connParams = ";interface=wifi"; //Connected to a WiFi access point.
} else {
int coverageStatus = CoverageInfo.getCoverageStatus();
//
if ((coverageStatus & CoverageInfo.COVERAGE_BIS_B) == CoverageInfo.COVERAGE_BIS_B) {
connParams = ";deviceside=false;ConnectionType=mds-public";
} else if ((coverageStatus & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
// Have network coverage and a WAP 2.0 service book record
ServiceRecord record = getWAP2ServiceRecord();
//
if (record != null) {
connParams = ";deviceside=true;ConnectionUID=" + record.getUid();
} else {
connParams = ";deviceside=true";
}
} else if ((coverageStatus & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
// Have an MDS service book and network coverage
connParams = ";deviceside=false";
}
}
Log.d("connection param"+url+connParams);
//
return url+connParams;
}
private static ServiceRecord getWAP2ServiceRecord() {
String cid;
String uid;
ServiceBook sb = ServiceBook.getSB();
ServiceRecord[] records = sb.getRecords();
//
for (int i = records.length -1; i >= 0; i--) {
cid = records[i].getCid().toLowerCase();
uid = records[i].getUid().toLowerCase();
//
if (cid.indexOf("wptcp") != -1
&& records[i].getUid().toLowerCase().indexOf("wap2") !=-1
&& uid.indexOf("wifi") == -1
&& uid.indexOf("mms") == -1) {
return records[i];
}
}
//
return null;
}
What happens when you append interface=wifi? Can you run the network diagnostic tool attached to below kb article and run all tests with SIM removed
http://supportforums.blackberry.com/t5/Java-Development/What-Is-Network-API-alternative-for-legacy-OS/ta-p/614822
Please also note that when download large files over BES/MDS there are limits imposed by MDS. Please ensure you review the below kb article
http://supportforums.blackberry.com/t5/Java-Development/Download-large-files-using-the-BlackBerry-Mobile-Data-System/ta-p/44585
You can check to see if coverage is sufficient for BIS_B (MDS public) but that won't help you if you are trying to support SIM-less users. I wonder if the problem is in an incomparability between the connection on Wi-Fi and IOUtilities.streamToBytes(). Try coding as recommended in the API documents.

Resources