Windows phone 8 - IP address is of wifi or carrier - windows-phone-8

I am developing an application on windows phone 8, and would like to know - Is it possible to check whether retrieved device IP address is over Wifi or carrier?
Code used to find device IP address is -
public IPAddress IdentifyDeviceIp()
{
List<string> DeviceIPAddresses = new List<string>();
var DeviceHostnames = Windows.Networking.Connectivity.NetworkInformation.GetHostNames();
foreach (var DeviceHostName in DeviceHostnames)
{
if (DeviceHostName.IPInformation != null)
{
string DeviceIpAddress = DeviceHostName.DisplayName;
// Emulator: ignore IPV6 addresses
if (DeviceIpAddress.Contains(":"))
continue;
DeviceIPAddresses.Add(DeviceIpAddress);
}
}
if (DeviceIPAddresses.Count == 0)
{
MessageBox.Show("No IP address found!!");
return new IPAddress(0);
}
return IPAddress.Parse(DeviceIPAddresses[0]);
}

To determine what a network is currently used by a phone you can check NetworkInterfaceType. Mode details here http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh487166(v=vs.105).aspx.

you can use this code for determinate where is the type of Network Interface :
NetworkInterfaceType MyNetworkInterfaceType = Microsoft.Phone.Net.NetworkInformation.NetworkInterface.NetworkInterfaceType;
If you've on Wifi, this code return "Wireless80211", you can read all documentation here
Also, with Windows Phone, you can Set your prefer NetworkInterface ( If you hove connected on Wifi and, on 3G, you can create a request with the Cellular connection (2G/3G/4G) or with NonCellular connection ( Ethernet, Wifi...) you can read this for information
You can Set your prefer Network for SocketRequest and for WebRequest you can read documentation about that in the msdn :
Microsoft.Phone.Net.NetworkInformation.WebRequestExtensions
Microsoft.Phone.Net.NetworkInformation.SocketExtensions
Use just the function
SetNetworkPreference(Socket/WebRequest, NetworkSelectionCharacteristics)
for define a request with your prefer network.
For better Experience for your application user, prefer the NonCellular DataConnection, generaly, it's faster [except for 4G] and cheaper... :D
For Your Problem, If you Set your prefer Connection, and you send a request, the ip adress use for this request must match the network defined preference.

Related

Create a Network Load Balancer on Oracle Cloud Infrastructure with a Reserved IP using Terraform

Using Terraform to set up a Network Load Balancer on Oracle Cloud Infrastructure, it works as expected if created with an ephemeral public IP, however one created using a reserved public IP does not respond. Here are the exact Terraform resourses used to create the load balancer:
resource "oci_core_public_ip" "ip" {
for_each = { for lb in var.load_balancers: lb.subnet => lb if ! lb.private
compartment_id = local.compartment_ocid
display_name = "${var.name}-public-ip"
lifetime = "RESERVED"
lifecycle {
prevent_destroy = true
}
}
resource "oci_network_load_balancer_network_load_balancer" "nlb" {
for_each = { for lb in var.load_balancers: lb.subnet => lb if lb.type == "network" }
compartment_id = local.compartment_ocid
display_name = "${var.name}-network-load-balancer"
subnet_id = oci_core_subnet.s[each.value.subnet].id
is_private = each.value.private
#reserved_ips {
# id = oci_core_public_ip.ip[each.value.subnet].id
#}
}
All of the other resources: security list rules, listeners, backend set and backends, etc, etc, are created such that the above works. If, however I uncomment the assignment of reserved_ips to the network load balancer then it does not work: no response from the load balancer's public IP. Everything is the same except those three lines being uncommented.
Between each test I tear down everything and recreate with Terraform. It always works with an ephemeral IP and never works with the reserved IP. Why? What am I missing? Or does this just not work as advertised?
The Terraform version is v1.3.4 and the resource version is oracle/oci version 4.98.0.
The reserved IP is set up correctly however the terraform provider removes its association with the load balancer's private IP. Closer inspection of the Terraform output shows this
~ resource "oci_core_public_ip" "ip" {
id = "ocid1.publicip.oc1.uk-london-1.ama...sta"
- private_ip_id = "ocid1.privateip.oc1.uk-london-1.abw...kya" -> null
# (11 unchanged attributes hidden)
}
Manually replacing it fixes it (until the next tf run)
$ oci network public-ip update --public-ip-id ocid1.publicip.oc1.uk-london-1.ama...rrq --private-ip-id ocid1.privateip.oc1.uk-london-1.abw...kya
There is a bug ticket on Terraform's github.

java.net.ConnectException: Connection refused: connect. Data Grip [duplicate]

I'm trying to implement a TCP connection, everything works fine from the server's side but when I run the client program (from client computer) I get the following error:
java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at java.net.Socket.<init>(Socket.java:375)
at java.net.Socket.<init>(Socket.java:189)
at TCPClient.main(TCPClient.java:13)
I tried changing the socket number in case it was in use but to no avail, does anyone know what is causing this error & how to fix it.
The Server Code:
//TCPServer.java
import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String argv[]) throws Exception {
String fromclient;
String toclient;
ServerSocket Server = new ServerSocket(5000);
System.out.println("TCPServer Waiting for client on port 5000");
while (true) {
Socket connected = Server.accept();
System.out.println(" THE CLIENT" + " " + connected.getInetAddress()
+ ":" + connected.getPort() + " IS CONNECTED ");
BufferedReader inFromUser = new BufferedReader(
new InputStreamReader(System.in));
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connected.getInputStream()));
PrintWriter outToClient = new PrintWriter(
connected.getOutputStream(), true);
while (true) {
System.out.println("SEND(Type Q or q to Quit):");
toclient = inFromUser.readLine();
if (toclient.equals("q") || toclient.equals("Q")) {
outToClient.println(toclient);
connected.close();
break;
} else {
outToClient.println(toclient);
}
fromclient = inFromClient.readLine();
if (fromclient.equals("q") || fromclient.equals("Q")) {
connected.close();
break;
} else {
System.out.println("RECIEVED:" + fromclient);
}
}
}
}
}
The Client Code:
//TCPClient.java
import java.io.*;
import java.net.*;
class TCPClient {
public static void main(String argv[]) throws Exception {
String FromServer;
String ToServer;
Socket clientSocket = new Socket("localhost", 5000);
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(
System.in));
PrintWriter outToServer = new PrintWriter(
clientSocket.getOutputStream(), true);
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
while (true) {
FromServer = inFromServer.readLine();
if (FromServer.equals("q") || FromServer.equals("Q")) {
clientSocket.close();
break;
} else {
System.out.println("RECIEVED:" + FromServer);
System.out.println("SEND(Type Q or q to Quit):");
ToServer = inFromUser.readLine();
if (ToServer.equals("Q") || ToServer.equals("q")) {
outToServer.println(ToServer);
clientSocket.close();
break;
} else {
outToServer.println(ToServer);
}
}
}
}
}
This exception means that there is no service listening on the IP/port you are trying to connect to:
You are trying to connect to the wrong IP/Host or port.
You have not started your server.
Your server is not listening for connections.
On Windows servers, the listen backlog queue is full.
I would check:
Host name and port you're trying to connect to
The server side has managed to start listening correctly
There's no firewall blocking the connection
The simplest starting point is probably to try to connect manually from the client machine using telnet or Putty. If that succeeds, then the problem is in your client code. If it doesn't, you need to work out why it hasn't. Wireshark may help you on this front.
You have to connect your client socket to the remote ServerSocket. Instead of
Socket clientSocket = new Socket("localhost", 5000);
do
Socket clientSocket = new Socket(serverName, 5000);
The client must connect to serverName which should match the name or IP of the box on which your ServerSocket was instantiated (the name must be reachable from the client machine). BTW: It's not the name that is important, it's all about IP addresses...
I had the same problem, but running the Server before running the Client fixed it.
One point that I would like to add to the answers above is my experience-
"I hosted on my server on localhost and was trying to connect to it through an android emulator by specifying proper URL like http://localhost/my_api/login.php . And I was getting connection refused error"
Point to note - When I just went to browser on the PC and use the same URL (http://localhost/my_api/login.php) I was getting correct response
so the Problem in my case was the term localhost which I replaced with the IP for my server (as your server is hosted on your machine) which made it reachable from my emulator on the same PC.
To get IP for your local machine, you can use ipconfig command on cmd
you will get IPv4 something like 192.68.xx.yy
Voila ..that's your machine's IP where you have your server hosted.
use it then instead of localhost
http://192.168.72.66/my_api/login.php
Note - you won't be able to reach this private IP from any node outside this computer. (In case you need ,you can use Ngnix for that)
I had the same problem with Mqtt broker called vernemq.but solved it by adding the following.
$ sudo vmq-admin listener show
to show the list o allowed ips and ports for vernemq
$ sudo vmq-admin listener start port=1885 -a 0.0.0.0 --mountpoint /appname --nr_of_acceptors=10 --max_connections=20000
to add any ip and your new port. now u should be able to connect without any problem.
Hope it solves your problem.
Hope my experience may be useful to someone. I faced the problem with the same exception stack trace and I couldn't understand what the issue was. The Database server which I was trying to connect was running and the port was open and was accepting connections.
The issue was with internet connection. The internet connection that I was using was not allowed to connect to the corresponding server. When I changed the connection details, the issue got resolved.
In my case, I gave the socket the name of the server (in my case "raspberrypi"), and instead an IPv4 address made it, or to specify, IPv6 was broken (the name resolved to an IPv6)
In my case, I had to put a check mark near Expose daemon on tcp://localhost:2375 without TLS in docker setting (on the right side of the task bar, right click on docker, select setting)
i got this error because I closed ServerSocket inside a for loop that try to accept number of clients inside it (I did not finished accepting all clints)
so be careful where to close your Socket
I had same problem and the problem was that I was not closing socket object.After using socket.close(); problem solved.
This code works for me.
ClientDemo.java
public class ClientDemo {
public static void main(String[] args) throws UnknownHostException,
IOException {
Socket socket = new Socket("127.0.0.1", 55286);
OutputStreamWriter os = new OutputStreamWriter(socket.getOutputStream());
os.write("Santosh Karna");
os.flush();
socket.close();
}
}
and
ServerDemo.java
public class ServerDemo {
public static void main(String[] args) throws IOException {
System.out.println("server is started");
ServerSocket serverSocket= new ServerSocket(55286);
System.out.println("server is waiting");
Socket socket=serverSocket.accept();
System.out.println("Client connected");
BufferedReader reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str=reader.readLine();
System.out.println("Client data: "+str);
socket.close();
serverSocket.close();
}
}
I changed my DNS network and it fixed the problem
You probably didn't initialize the server or client is trying to connect to wrong ip/port.
Change local host to your ip address
localhost
//to you local ip
192.168.xxxx
I saw the same error message ""java.net.ConnectException: Connection refused" in SQuirreLSQL when it was trying to connect to a postgresql database through an ssh tunnel.
Example of opening tunel:
Example of error in Squirrel with Postgresql:
It was trying to connect to the wrong port. After entering the correct port, the process execution was successful.
See more options to fix this error at: https://stackoverflow.com/a/6876306/5857023
In my case, with server written in c# and client written in Java, I resolved it by specifying hostname as 'localhost' in the server, and '[::1]' in the client. I don't know why that is, but specifying 'localhost' in the client did not work.
Supposedly these are synonyms in many ways, but apparently, not not a 100% match. Hope it helps someone avoid a headache.
For those who are experiencing the same problem and use Spring framework, I would suggest to check an http connection provider configuration. I mean RestTemplate, WebClient, etc.
In my case there was a problem with configured RestTemplate (it's just an example):
public RestTemplate localRestTemplate() {
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", <some port>));
SimpleClientHttpRequestFactory clientHttpReq = new SimpleClientHttpRequestFactory();
clientHttpReq.setProxy(proxy);
return new RestTemplate(clientHttpReq);
}
I just simplified configuration to:
public RestTemplate restTemplate() {
return new RestTemplate(new SimpleClientHttpRequestFactory());
}
And it started to work properly.
There is a service called MySQL80 that should be running to connect to the database
for windows you can access it by searching for services than look for MySQL80 service and make sure it is running
It could be that there is a previous instance of the client still running and listening on port 5000.

Connecting Arduino to a remote MySQL database using DNS and WiFi

I am currently trying to connect my ESP8266 to an Azure MySQL database using WiFi and DNS. It seems like the WiFi library does not natively support DNS, only IP however Azure does not support static IP, therefore I need to use DNS.
This is the code I have so far:
#include <WiFi.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>
#include <Dns.h>
byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
char hostname[] = "something.mysql.database.azure.com"; //replace something with database name
IPAddress server_ip;
char user[] = "root"; // MySQL user login username
char password[] = "secret"; // MySQL user login password
// WiFi card example
char ssid[] = "WiFiSSID"; // your SSID
char pass[] = "secret"; // your SSID Password
WiFiClient client; // Use this for WiFi instead of EthernetClient
MySQL_Connection conn((Client *)&client);
void setup() {
Serial.begin(115200);
while (!Serial); // wait for serial port to connect. Needed for Leonardo only
// Begin WiFi section
int status = WiFi.begin(ssid, pass);
if ( status != WL_CONNECTED) {
Serial.println("Couldn't get a wifi connection");
while(true);
}
// print out info about the connection:
else {
Serial.println("Connected to network");
IPAddress ip = WiFi.localIP();
// Particle.process(); Seemingly need to call this for WiFi.dnsServerIP() to be available but gives "out of scope error".
DNSClient dns;
dns.begin(WiFi.dnsServerIP());
dns.getHostByName(hostname, server_ip);
}
// End WiFi section
Serial.println("Connecting...");
if (conn.connect(server_ip, 3306, user, password)) {
delay(1000);
}
else
Serial.println("Connection failed.");
conn.close();
}
void loop() {
}
This is the error I'm getting:
Arduino: 1.8.5 (Windows 10), Board: "SparkFun ESP8266 Thing Dev, 80 MHz, 512K (no SPIFFS), v2 Lower Memory, Disabled, None, Only Sketch, 115200"
C:\Users\Mathi\OneDrive\Documents\Arduino\wifi_hostname_sketchB\wifi_hostname_sketchB.ino: In function 'void setup()':
wifi_hostname_sketchB:65: error: 'class WiFiClass' has no member named 'dnsServerIP'
dns.begin(WiFi.dnsServerIP());
^
Multiple libraries were found for "Ethernet.h"
Used: C:\Users\Mathi\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.1\libraries\Ethernet
Not used: D:\Programs\Arduino IDE\Arduino\libraries\Ethernet
exit status 1
'class WiFiClass' has no member named 'dnsServerIP'
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
I have tried using the Particle.process function but it kept giving me an 'Out of scope' error. Most people fixed this by changing the firmware but did not help me.
I got most of the code from https://github.com/ChuckBell/MySQL_Connector_Arduino
I followed the guide for accessing the MySQL database with WiFi, however this did not include DNS.
don't use DNSclient it won't work with WiFi use WiFi.hostByName instead. Took me 2 days to find this gem..
IPAddress server_ip;
WiFi.hostByName("www.google.com",server_ip);
Serial.println(server_ip); // server_ip will contain the ip address of google.com
the WiFi library WiFiWebClient example uses host name to connect to the web server.
char server[] = "www.google.com"; // name address for Google (using DNS)
if (client.connect(server, 80)) {
Since microsoft Azure does only support DNS and the ESP8266 WiFi library only supports static IP, they will not work together. You could use google cloud instead, since this supports static IP.

IOT: Only one usage of each socket address (protocol/network address/port) is normally permitted

I'm trying to run my first IoT on my Raspberry Pi 3.
But using this code ....
public void StartServer()
{
Task.Run(async () =>
{
listener = new StreamSocketListener();
listener.Control.KeepAlive = true;
listener.Control.NoDelay = true;
await listener.BindServiceNameAsync(port.ToString());
});
}
I get this error at BindServiceNameAsync...
Exception thrown: 'System.Runtime.InteropServices.COMException' in mscorlib.ni.dll
WinRT information: Only one usage of each socket address (protocol/network address/port)
is normally permitted.
In appmanifest I have checked "Internet (Client & Server)".
Any idea why I get this error?
Thanks
Most likely the port that you are trying to use is already being used by another process. Try a different port.

How to "start" or "activate" a network with libvirt?

How do you "start" an inactive network using libvirt? With virsh this would be net-start <network>.
I can create a network with virNetworkDefineXML, which will:
Define an inactive persistent virtual network or modify an existing persistent one from the XML description.
(which is the equivalent of virsh net-define), but I don't know how to "start" this newly-created, but inactive network.
I'm using the libvirt-python bindings, but knowing the correct C API would be sufficient.
The API is virNetworkCreate():
Create and start a defined network. If the call succeed the network moves from the defined to the running networks pools.
To find this, we can look at the source for virsh. The "net-start" command is defined in tools/virsh-network.c:
static bool
cmdNetworkStart(vshControl *ctl, const vshCmd *cmd)
{
virNetworkPtr network;
bool ret = true;
const char *name = NULL;
if (!(network = virshCommandOptNetwork(ctl, cmd, &name)))
return false;
if (virNetworkCreate(network) == 0) {
vshPrint(ctl, _("Network %s started\n"), name);
} else {
vshError(ctl, _("Failed to start network %s"), name);
ret = false;
}
virNetworkFree(network);
return ret;
}
In libvirt-python, this means simply calling .create() on the network object returned from .networkDefineXML():
conn = libvirt.open('qemu:///system')
# Define a new persistent, inactive network
xml = open('net.xml', 'r').read()
net = conn.networkDefineXML(xml)
# Set it to auto-start
net.setAutostart(True)
# Start it!
net.create()