I am building a windows phone 7.1 app. I need to find out if the phone is connected to any Wifi and if so, what is its current IP in the local network (ie. 192.168.0.100 like this).
I've been trying to find out these information for some time now. Please help.
I've managed to get the local IP on my console app by using the following code
public void ScanIP()
{
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
String localIP = ip.ToString();
Console.WriteLine(localIP);
}
}
Console.ReadKey();
}
However, I need similar thing done for windows mobile 7 app. Any idea ? Please share.
Do a multicast and listen for replies. Once you identify your multicast message, you can get the IP of the sender (which is yourself). You can use UdpAnySourceMulticastClient to do the multicasting. In case you're not in a wifi network, you will get a socket failure in the EndJoinGroup call. You should handle the exception and pass a specific value indicating you're not in a wifi network.
More info in this blog post by Andy Pennell.
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;
}
Related
I have an interesting problem that appears to be related to multicast being switched off (at the kernal) on newer andriod devices, please note This is NOT an issue with setting up UDP on multi adapters or LTE/WIFI, I understand that.
A lot of googling and trying loads things out have offered up a multitude of answers, e.g. acquire multi cast locks and some git hub issues where people say its impossible as devices have multicast disabled in the kernel. I have also just found this on SO
My code works fine on:-
Nexus 5 Andriod 8.1 - API 27
Lenovo Tablet Andriod 8.1 - API 27
That is it can send and receive UDP packets that is not directly targeted to the IP address of the phone.
It does NOT receive UDP packets on:-
Pixel 3a Andriod 10/11 APIS 29/30
The Xamarin forms code to replicate this is:
public TestCameraPage()
{
InitializeComponent();
sendClient = new UdpClient
{
EnableBroadcast = true,
ExclusiveAddressUse = false,
MulticastLoopback = true
};
sendClient.Client.Bind(new IPEndPoint(IPAddress.Any, CameraPort));
Lab1.Text = "Started to listen for UDP packets";
sendClient.BeginReceive(DiscoverCallback, sendClient);
}
private void DiscoverCallback(IAsyncResult result)
{
try
{
var ep = new IPEndPoint(IPAddress.Any, CameraPort);
var data = sendClient.EndReceive(result, ref ep);
var msg = $"Received: {Encoding.UTF8.GetString(data)}";
//Sniff out camera IP
var ip = $"{data[15]}.{data[14]}.{data[13]}.{data[12]}";
Device.BeginInvokeOnMainThread(() =>
{
Lab1.Text = $"CAMERA IP: {ip} FULL MESSAGE: {msg}";
});
}
finally
{
sendClient.BeginReceive(DiscoverCallback, sendClient);
}
}
private void Button_OnClicked(object sender, EventArgs e)
{
var data = PollMessageToCamera();
sendClient.Send(data, data.Length, "255.255.255.255", ListeningPort);
}
So my questions are two fold
Is it possible to receive UDP packets that are NOT broadcasted directly to the device on a newer Andriod phone?
If it is possible what do I need to do to fix it?
Example output on nexus and tablets
I should also point out I have a console app that can send UDP messages and if I use this (ip address of pixel 3a), it works
sendClient.Send(data, data.Length, "192.168.1.248", CameraPort);
If I use 255.255.255.255 (multi cast) in console app only the nexus and tablet works the pixel 3a doesn't
sendClient.Send(data, data.Length, "255.255.255.255", CameraPort);
I've been trying to connect to a specific wifi through code, but with no succcess.
This is what i've come up with:
public void ConnectToWifi(string ssid, string password)
{
WifiManager wifiManager = (WifiManager)Android.App.Application.Context.GetSystemService(Context.WifiService);
if (!wifiManager.IsWifiEnabled)
{
wifiManager.SetWifiEnabled(true);
}
string formattedSsid = $"\"{ssid}\"";
string formattedPassword = $"\"{password}\"";
WifiConfiguration wifiConfig = new WifiConfiguration
{
Ssid = formattedSsid,
PreSharedKey = formattedPassword
};
var addNetwork = wifiManager.AddNetwork(wifiConfig);
WifiConfiguration network = wifiManager.ConfiguredNetworks.FirstOrDefault(n => n.Ssid == ssid);
if (network == null)
{
Console.WriteLine($"Cannot connect to network: {ssid}");
return;
}
wifiManager.Disconnect();
bool enableNetwork = wifiManager.EnableNetwork(network.NetworkId, true);
}
I've added permissions.
When testing it does turn the wifi on atleast, so i know it works until that point. What seems not to be working is the AddNetwork part.
I appreciate any help i can get!
You are missing one key method - reconnect(). You can read more about it in the WifiManager's docs here
The important part of the documentation is:
Reconnect to the currently active access point, if we are currently disconnected.
So, what you need to do it after you have disconnected and enabled your new network, call in the end this and you will be good to go:
wifiManager.Disconnect();
wifiManager.EnableNetwork(network.NetworkId, true);
wifiManager.Reconnect(); // This is the missing method
NB: Keep in mind that most of the WifiManager's code that you are using is being obsolete starting Android 10. So, if you want to target Android 10, then you will need to write an additional code for the connectivity for devices with Android 10+.
I am beginning to use the sample IBM-IOT C# sample code as per
https://github.com/ibm-watson-iot/iot-csharp/blob/master/docs/Gateway.rst
however I get "An invalid IP address was specified." thrown when the gateway constructor is called using the org id.
I'm using an orgid of 'p3wg4w' (set in config and accessed as a string property Globals.WatsonOrgID" )
my code is
private static void InitGatewayClient()
{
if (gw == null)
{
gw = new GatewayClient(Globals.WatsonOrgID,
Globals.WatsonGatewayDeviceType,
Globals.WatsonGatewayDeviceID,
Globals.WatsonAuthMethod,
Globals.WatsonToken);
gw.commandCallback += processCommand;
gw.errorCallback += processError;
gw.connect();
Console.WriteLine("Gateway connected");
Console.WriteLine("publishing gateway events..");
}
}
Has anyone seen this before ?
check if you can access or if you can:
telnet p3wg4w.messaging.internetofthings.ibmcloud.com 8883
The libraries aren't using any IP to create the connection, it is using the below vars
public static string DOMAIN = ".messaging.internetofthings.ibmcloud.com";
public static int MQTTS_PORT = 8883;
I can only think that your firewall is blocking the connection
I've used the below sample and worked just fine for me:
https://github.com/ibm-watson-iot/iot-csharp/blob/master/sample/Gateway/SampleGateway.cs
hi can you please tell me how to access iOS device ip address using xamarin. we are building iOS app in which we want to show device local ip address. I used many other solutions but they didnt work for me.
I found a post about it here: https://forums.xamarin.com/discussion/348/acquire-device-ip-addresses-monotouch-since-ios6-0
it goes as follow:
Try using System.Net.NetworkInformation.NetworkInterface:
foreach (var netInterface in NetworkInterface.GetAllNetworkInterfaces()) {
if (netInterface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 ||
netInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet) {
foreach (var addrInfo in netInterface.GetIPProperties().UnicastAddresses) {
if (addrInfo.Address.AddressFamily == AddressFamily.InterNetwork) {
var ipAddress = addrInfo.Address;
// use ipAddress as needed ...
}
}
}
}
Is there any code or method to get the IP addresses of the local system?
To enumerate local IP addresses, use the Win32 API GetAdaptersInfo() (supports IPv4 only) or GetAdaptersAddresses() (supports IPv4 and IPv6) function. C/C++ examples are included in their documentation.
If you are in C#, you could use .NET:
using System;
using System.Net;
public static string GetLocalIP() {
var hosts = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ipEntry in host.AddressList)
{
if (ipEntry.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
}
You can later add a throw new Exception at the end, it will show up if you have no IPv4 adapters installed.