I want to get the IP Address and the country in which it belongs using Qt please help me with examples. thank you for your time.
I tried this code
foreach (const QHostAddress &address, QNetworkInterface::allAddresses()) {
if (address.protocol() == QAbstractSocket::IPv6Protocol && address != QHostAddress(QHostAddress::LocalHost)) {
qDebug() << address.toString();
}
}
but it did not work, i want to get the IP like the one witch gives the website http://whatismyipaddress.com/fr/mon-ip it gives the IP Address and the country in witch it belogns.
Thank you so much for your time.
Related
I'm developing an app which have to implement a WiFi connection mechanism (it'll be a fullscreen touchscreen app). To do that I'm using the DBus to communicate with Network Manager. I managed to successfully make it scan access points and list them in the QTableView. Next thing will be to connect to the chosen wifi network. First thing I do when trying to connect is checking if there is an existing connection to that access point already in the system so I do this:
settings = new QDBusInterface("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings", "org.freedesktop.NetworkManager.Settings", dbusConnection, this);
QDBusMessage msg = settings->call("ListConnections");
QDBusArgument arg = msg.arguments().at(0).value<QDBusArgument>();
QList<QDBusObjectPath> pathsList = qdbus_cast<QList<QDBusObjectPath>>(arg);
foreach (QDBusObjectPath p, pathsList) {
QDBusInterface *conn = new QDBusInterface("org.freedesktop.NetworkManager", p.path(), "org.freedesktop.NetworkManager.Settings.Connection", dbusConnection);
QDBusMessage msg = conn->call("GetSettings");
qDebug() << "Reply: " << msg;
}
I receive the message and can read it with qDebug(). The message is in d-bus format: a{sa{sv}} as the documentation for Network Manager says. And I have problem to parse it to any usable form. From what I understand, the equivalent Qt classes I should put the data to are:
QList<QMap<QString, QMap<QString, QVariant>>>
And I think I should do it with the QDBusArgument class but can't figure out how exactly it should be done. Can someone tell me what is the best way to do this?
Thanks.
I managed to solve my problem, it turned out to be quite easy. I created the map object and used >> operator:
QDBusArgument arg = args.at(0).value<QDBusArgument>();
QMap<QString, QMap<QString, QVariant>> map;
arg >> map;
I am trying to scan my serial ports periodically to see if my device is connected or not. Here is what I have done and it works well. I would like to see if there is a better and optimized way to do so.
I created the following timer in my constructor to check the serial port frequently. I made a method (scanSerialPorts()) and call it every 1 second.
QTimer *timer = new QTimer(this);
connect(timer,SIGNAL(timeout()),this,SLOT(scanSerialPorts()));
timer->start(1000);
This is my scanSerialPorts() implementation:
foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
currentPortName = info.systemLocation();
}
if (currentPortName == "My Desired PortName" ) {
updateSettings();
if ( !serial->isOpen()){
qDebug() << "Serial Not Open";
openSerialPort();
}
} else
{
serial->close();
}
updateSettings(); // Fills up the serial port parameters.
openSerialPort(); //Opens up the serial port.
I used QT examples to write this. Please let me know what you think and how I can make it better.
As it is, you only scan the last port, since the rest of the code is outside the foreachloop;
You close the other (probably not opened) ports instead of the one you're opening
Most probably, availablePorts won't change during execution, so you could move it outside of the scan function to save some processing time in the timer. The same for updateSettings().
I recently bought and RDp and everything went well, and i made a little script in .as (can't show it on here) which bounds to my local ip, e.g. 192.168.42.1, but when I tried the same on another rdp I got this: http://prntscr.com/6hywkm , a very odd IP, can anyone explain me how this comes and how to fix it(getting back a normal local ip 192.168.x.x)
Thanks.
seems like a IPv6 Address, so converting them to back to IPv4 ( like 127.0.0.1 ) is not possible all the time, so here is snippet in javascript which might help you out:
but keep in mind that its not always possible!
<script>
function parseIp6(str)
{
//init
var ar=new Array;
for(var i=0;i<8;i++)ar[i]=0;
//check for trivial IPs
if(str=="::")return ar;
//parse
var sar=str.split(':');
var slen=sar.length;
if(slen>8)slen=8;
var j=0;
for(var i=0;i<slen;i++){
//this is a "::", switch to end-run mode
if(i && sar[i]==""){j=9-slen+i;continue;}
ar[j]=parseInt("0x0"+sar[i]);
j++;
}
return ar;
}
function ipcnvfrom6(ip6)
{
var ip6=parseIp6(ip6);
var ip4=(ip6[6]>>8)+"."+(ip6[6]&0xff)+"."+(ip6[7]>>8)+"."+(ip6[7]&0xff);
return ip4;
}
alert(ipcnvfrom6("::C0A8:4A07"));
</script>
It's an IPv6 structure. Online convertor exists : http://www.subnetonline.com/pages/subnet-calculators/ipv4-to-ipv6-converter.php
but the conversion is not always possible.
I am trying to write a program that uses an arduino mega and a FTDI-based USB to RS485 adapter.
I want to make the program user-friendly, thus I don't wont the user to manually check the com port number, but I want to auto-detect it. Here's a snippet of the code
ManagementScope scope = new ManagementScope();
SelectQuery query = new SelectQuery("SELECT * FROM Win32_SerialPort");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
try
{
foreach (ManagementObject item in searcher.Get())
{
String description = item["Description"].ToString();
String deviceID = item["DeviceID"].ToString();
Console.WriteLine("Porta " + description + " deviceID " + deviceID);
if (description.Contains("USB Serial Port"))
return deviceID;
}
}
catch (ManagementException)
{
}
The point that I am not able to understand is why I can find the USB Serial port of the Arduino (matching description.Contains("Arduino") ) but not the com port of the USB RS485 port.
Do you have an idea why this could happen? is the query SELECT * FROM Win32_SerialPort wrong?
Well, after studying several forums, I discovered that the com port associated to the USB/RS485 adapter is listed if I run the query SELECT * FROM Win32_PnPEntity .
But I really don't understand why the serial port of the arduino is shown by a query and the other port with the other query.... I mean, those are both uSB<->serial adapters!
I don't have a USB<->RS485 adapter, but I suspect they don't fall into the "serial port" category (which seems reserved for RS232 interfaces), which could be the reason why they don't appear among the Win32_SerialPort query results.
To detect the connection of and Arduino board I look into this registry key:
HKLM\HARDWARE\DEVICEMAP\SERIALCOMM
for entries like
\Device\VCP0
(VCP is the prefix to look for).
Maybe you can look into this registry key too, or watch its parent key, DEVICEMAP, and see what happens when you connect the FTDI RS485 adapter.
Detecting a change in one of these registry keys contents should be straightforward at that point.
HTH
This might work for you. I used this to dynamically read port number of Arduino on a system. Here
description.Contains("uino")
is to look for both Arduino and Genuino keyword for both varients of board.
public string detectArduinoPort()
{
ManagementScope mScope = new ManagementScope();
SelectQuery query = new SelectQuery("SELECT * FROM Win32_SerialPort");
ManagementObjectSearcher objectList = new ManagementObjectSearcher(mScope, query);
try
{
foreach (ManagementObject obj in objectList.Get())
{
string description = obj["Description"].ToString();
string deviceId = obj["DeviceID"].ToString();
if (description.Contains("uino"))
{
return deviceId;
}
}
}
catch (Exception)
{
}
return "";
}
as #Marcello Romani pointed out FTDI don't fall into the "serial port" category. Even though I am late I came across this problem recently and I fixed it using another query. Instead of searching in WIN32_SerialPort, you can query the Win32_PnPEntity class.One downside of using this class is that is slow to query.
using (var searcher = new ManagementObjectSearcher
("SELECT * FROM Win32_PnPEntity"))
{
string[] portnames = SerialPort.GetPortNames();
var ports = searcher.Get().Cast<ManagementBaseObject>().ToList();
foreach (ManagementBaseObject queryObj in ports)
{
}
}
Basically, this is due to the HID (Human Interface Device)
I think that this is due to the HID provided by the arduino board.
Arduino hardware (and thus, the microcontroller) communicates directely with the PC using HID (and so, no need for additional device). And HID can behave as a mouse, keyboard, or simply a serial device (it "simply" declare itself to the PC as a Serial Comport). So somehow, there is some "intelligent" way when communicating with the PC.
On the other hand, USBtoSerial converters and in some Arduino boards, like the Arduino Nano which embed an FTDI (or CH340), these are "obliged" to behave as a normal comport cause there is no intelligence behind (the the one behind the HID).
This is the label
<asp:Label ID="lblIp" runat="server"></asp:Label>
Here Code I used to get user IP address
string VisitorsIPAddr = string.Empty;
if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
lblIp.Text = VisitorsIPAddr;
}
else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
{
VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
lblIp.Text = VisitorsIPAddr;
}
but Always I got the same result. That was 127.0.0.1 and always it goes to else if state.
further
HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] did not give any result. It always give nothing
You are running the application at your own machine therefor you are the one sliding there, so you will always get 127.0.0.1 in the else if.
If you want to see another IP open the app and relevant port and get there with another machine.
Also the HTTP_X_FORWARDED_FOR is not always there (usually from normal web requests it will be but there are exceptions).
I think thats what Kundan Singh Chouhan tried to suggest, hope I am not wrong.