Qt determine if given hostname points to localhost [duplicate] - qt

This question already has an answer here:
How to check if network address is local in Qt
(1 answer)
Closed 6 years ago.
My application connects to a tcp server. I'd like it to be aware of being running on the same host as the server app, so it can eventually directly lauch the server process if it's not up.
As the server listens on an interface and the application resolves a hostname to connect to the server, it's not so obvious for me to determine if the configured hostname used to connect the server points to the same host as the server or not.
I'd like something like this:
bool isThisLocalHost(QString hostName) {
//resolve hostname's address
//list localhost interfaces ip or hw addresses ?
//if the hostname address matches one of the host interfaces address
//pseudo code
bool bRes = interfaces_addresses_list.contains(hostname_address);
return bRes;
}
I'm actually trying to achieve this with
QNetworkInterface, QNetworkAddressEntry, QHostInfo, QHostAddress.
Maybe is there a simple way?

Here is what i got:
bool isThisLocalHost(QString hostName) {
QList <QHostAddress> lAddrHostName = QHostInfo::fromName(hostName).addresses();
QList <QHostAddress> lAddrLocalHostInterfaces = QNetworkInterface::allAddresses();
bool bRes = false;
foreach (QHostAddress addr, lAddrHostName) {
bRes = bRes || lAddrLocalHostInterfaces.contains(addr);
}
return bRes;
}

QHostAddress has isLoopback() which should get you what you need.
If you just want to know if you're connected to yourself this is (partly?) a duplicate of this question.

Related

Elasticsearch not starting, but throwing ReceiveTimeoutTransportException

I am trying to use elastic search with java api, but when i try to run application, i am getting following exception.
18:13:52.378 [elasticsearch[Fallen One][generic][T#1]] INFO org.elasticsearch.client.transport - [Fallen One] failed to get local cluster state for [#transport#-1][integra][inet[/127.0.0.1:9300]], disconnecting...
org.elasticsearch.transport.ReceiveTimeoutTransportException: [][inet[/127.0.0.1:9300]][cluster/state] request_id [52] timed out after [5001ms]
at org.elasticsearch.transport.TransportService$TimeoutHandler.run(TransportService.java:356) [elasticsearch-1.0.1.jar:na]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [na:1.7.0_51]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [na:1.7.0_51]
at java.lang.Thread.run(Thread.java:744) [na:1.7.0_51]
18:13:52.381 [elasticsearch[Fallen One][generic][T#1]] DEBUG org.elasticsearch.transport.netty - [Fallen One] disconnected from [[#transport#-1][integra][inet[/127.0.0.1:9300]]]
18:13:52.391 [elasticsearch[Fallen One][generic][T#3]] DEBUG org.elasticsearch.transport.netty - [Fallen One] connected to node [[#transport#-1][integra][inet[/127.0.0.1:9300]]]
Code for connecting to elastic search is
private String[] esNodes = { "127.0.0.1:9300" };
protected TransportClient buildClient() throws Exception {
Settings settings = ImmutableSettings.settingsBuilder()
.put("client.transport.sniff", true)
.put("client.transport.ignore_cluster_name",true).build();
TransportClient client = new TransportClient(settings);
for (int i = 0; i < esNodes.length; i++) {
client.addTransportAddress(toAddress(esNodes[i]));
}
return client;
}
private InetSocketTransportAddress toAddress(String address) {
if (address == null) return null;
String[] splitted = address.split(":");
int port = 9300;
if (splitted.length > 1) {
port = Integer.parseInt(splitted[1]);
}
return new InetSocketTransportAddress(splitted[0], port);
}
can any one kindly help me, i am new to elastic search and have no idea how to resolve the issue.
I am using this code to connect to my elasticsearch and its pretty well working.
Settings settings = ImmutableSettings.settingsBuilder()
.put("cluster.name", clusterName).build();
this.client = new TransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(ipAddress,9300));
Where ipAddress and Clustername are argument of my function.
You should have a look at the network on your laptop. Check if you can connect to localhost. Another thing you could try is start two elasticsearch instances with the same configuration to see if they connect. Finally have a look at the network part of elasticsearch.yml. When having network problems on a local machine I usually try the following two options:
network.host: localhost
discovery.zen.ping.multicast.enabled: false
discovery.zen.ping.unicast.hosts: ["localhost"]
I think Elastic search server is Not started.. Try to hit in browser or curl comments.. If it works.. Try the above code..
NOTE:IF YOUR JAVA API JAR VERSION DIFFERS ALSO LL RAISE PROB.. ( get java api version same as ES version
Note : elasticsearch java api helps you connect to with elasticsearch.. But its can't start a elasticsearch node using api..
Your code is good.. It's Vry standard too..

how to detect that user internet connection is on?

I have a web page(ASP.NET) that a client (just one) connect to it and after registration I save it's IP address into a text file. What I want to do is if this client has closed the web page, I want to detect it and clear my text file .
Using this You can check Connection
System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()
EXAMPLE:--
public static void **testInternetConnection**()
{
if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
System.Windows.MessageBox.Show("This computer is connected to the internet");
}
else
{
System.Windows.MessageBox.Show("This computer is not connected to the internet");
}
}

How to get the user IP address in Meteor server?

I would like to get the user IP address in my meteor application, on the server side, so that I can log the IP address with a bunch of things (for example: non-registered users subscribing to a mailing list, or just doing anything important).
I know that the IP address 'seen' by the server can be different than the real source address when there are reverse proxies involved. In such situations, X-Forwarded-For header should be parsed to get the real public IP address of the user. Note that parsing X-Forwarded-For should not be automatic (see http://www.openinfo.co.uk/apache/index.html for a discussion of potential security issues).
External reference: This question came up on the meteor-talk mailing list in august 2012 (no solution offered).
1 - Without a http request, in the functions you should be able to get the clientIP with:
clientIP = this.connection.clientAddress;
//EX: you declare a submitForm function with Meteor.methods and
//you call it from the client with Meteor.call().
//In submitForm function you will have access to the client address as above
2 - With a http request and using iron-router and its Router.map function:
In the action function of the targeted route use:
clientIp = this.request.connection.remoteAddress;
3 - using Meteor.onConnection function:
Meteor.onConnection(function(conn) {
console.log(conn.clientAddress);
});
Similar to the TimDog answer but works with newer versions of Meteor:
var Fiber = Npm.require('fibers');
__meteor_bootstrap__.app
.use(function(req, res, next) {
Fiber(function () {
console.info(req.connection.remoteAddress);
next();
}).run();
});
This needs to be in your top-level server code (not in Meteor.startup)
This answer https://stackoverflow.com/a/22657421/2845061 already does a good job on showing how to get the client IP address.
I just want to note that if your app is served behind proxy servers (usually happens), you will need to set the HTTP_FORWARDED_COUNT environment variable to the number of proxies you are using.
Ref: https://docs.meteor.com/api/connections.html#Meteor-onConnection
You could do this in your server code:
Meteor.userIPMap = [];
__meteor_bootstrap__.app.on("request", function(req, res) {
var uid = Meteor.userId();
if (!uid) uid = "anonymous";
if (!_.any(Meteor.userIPMap, function(m) { m.userid === uid; })) {
Meteor.userIPMap.push({userid: uid, ip: req.connection.remoteAddress });
}
});
You'll then have a Meteor.userIPMap with a map of userids to ip addresses (to accommodate the x-forwarded-for header, use this function inside the above).
Three notes: (1) this will fire whenever there is a request in your app, so I'm not sure what kind of performance hit this will cause; (2) the __meteor_bootstrap__ object is going away soon I think with a forthcoming revamped package system; and (3) the anonymous user needs better handling here..you'll need a way to attach an anonymous user to an IP by a unique, persistent constraint in their request object.
You have to hook into the server sessions and grab the ip of the current user:
Meteor.userIP = function(uid) {
var k, ret, s, ss, _ref, _ref1, _ref2, _ref3;
ret = {};
if (uid != null) {
_ref = Meteor.default_server.sessions;
for (k in _ref) {
ss = _ref[k];
if (ss.userId === uid) {
s = ss;
}
}
if (s) {
ret.forwardedFor = ( _ref1 = s.socket) != null ?
( _ref2 = _ref1.headers) != null ?
_ref2['x-forwarded-for'] : void 0 : void 0;
ret.remoteAddress = ( _ref3 = s.socket) != null ?
_ref3.remoteAddress : void 0;
}
}
return ret.forwardedFor ? ret.forwardedFor : ret.remoteAddress;
};
Of course you will need the current user to be logged in. If you need it for anonymous users as well follow this post I wrote.
P.S. I know it's an old thread but it lacked a full answer or had code that no longer works.
Here's a way that has worked for me to get a client's IP address from anywhere on the server, without using additional packages. Working in Meteor 0.7 and should work in earlier versions as well.
On the client, get the socket URL (unique) and send it to the server. You can view the socket URL in the web console (under Network in Chrome and Safari).
socket_url = Meteor.default_connection._stream.socket._transport.url
Meteor.call('clientIP', socket_url)
Then, on the server, use the client's socket URL to find their IP in Meteor.server.sessions.
sr = socket_url.split('/')
socket_path = "/"+sr[sr.length-4]+"/"+sr[sr.length-3]+"/"+sr[sr.length-2]+"/"+sr[sr.length-1]
_.each(_.values(Meteor.server.sessions), (session) ->
if session.socket.url == socket_path
user_ip = session.socket.remoteAddress
)
user_ip now contains the connected client's IP address.

gnu.io.PortInUseException: Unknown Application?

void connect ( String portName ) throws Exception
{
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if ( portIdentifier.isCurrentlyOwned() )
{
System.out.println("Error: Port is currently in use");
}
else
{
System.out.println(portIdentifier.getCurrentOwner());
CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);
if ( commPort instanceof SerialPort )
{
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(115200,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
InputStream in = serialPort.getInputStream();
OutputStream out = serialPort.getOutputStream();
(new Thread(new SerialReader(in))).start();
(new Thread(new SerialWriter(out))).start();
}
else
{
System.out.println("Error: Only serial ports are handled by this example.");
}
}
}
is giving
gnu.io.PortInUseException: Unknown Application
at gnu.io.CommPortIdentifier.open(CommPortIdentifier.java:354)
i am using RXTX with Java in windows 7 home 64-bit.
Check that /var/lock folder exist on your machine.
mkdir /var/lock
chmod go+rwx /var/lock
Reboot the system / disable the port.
Actual problem is when the program runs port is opened and it didn't close after the program terminates.
it works.
I ran into this problem because the port was actually in use. A previous instance of javaw.exe appeared in the Windows task manager, it hogged the port.
The reason why that previous java process hung was a hardware issue: When plugging the USB-2-serial converter that I happened to use into a USB-2 port, all worked fine. When plugged into a USB-3 port, RXTX CommPortIdentifier code would hang, and then subsequent instances of Java received the PortInUseException.
I used Process Explorer to find a process with the handle \Device\PCISerial0 and closed the handle. If your com ports aren't on a PCI card, the name might be different.
For Windows
Open Task Manager
under Eclipse (or your ide) find Java application.
Right click on it -> End Task
May be useful, I solved such problem by remove gateway from service and stop it , gateway is instance of SerialModemGateway.
Service.getInstance().stopService();
Service.getInstance().removeGateway(gateway);
gateway.stopGateway();

TCP sockets over wlan

I have a project that uses TCP sockets to communicate between a server and one client. As of now I have been doing this on one computer so I have just used local address of "127.0.0.1" for the address to bind and connect to on both sides and its worked fine. Now I have a second computer to act as a client, but I don't know how to change the addresses accordingly. They are connected through a network that is not connected to the Internet. Before the code looked like this -
Server -
struct addrinfo hints;
struct addrinfo *servinfo; //will point to the results
//store the connecting address and size
struct sockaddr_storage their_addr;
socklen_t their_addr_size;
memset(&hints, 0, sizeof hints); //make sure the struct is empty
hints.ai_family = AF_INET; //local address
hints.ai_socktype = SOCK_STREAM; //tcp
hints.ai_flags = AI_PASSIVE; //use local-host address
//get server info, put into servinfo
if ((status = getaddrinfo("127.0.0.1", port, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
return false;
}
//make socket
fd = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol);
if (fd < 0) {
printf("\nserver socket failure %m", errno);
return false;
}
//allow reuse of port
int yes=1;
if (setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,(char*) &yes,sizeof(int)) == -1) {
perror("setsockopt");
return false;
}
//unlink and bind
unlink("127.0.0.1");
if(bind (fd, servinfo->ai_addr, servinfo->ai_addrlen) < 0) {
printf("\nBind error %m", errno);
return false;
}
Client -
struct addrinfo hints;
struct addrinfo *servinfo; //will point to the results
memset(&hints, 0, sizeof hints); //make sure the struct is empty
hints.ai_family = AF_INET; //local address
hints.ai_socktype = SOCK_STREAM; //tcp
hints.ai_flags = AI_PASSIVE; //use local-host address
//get server info, put into servinfo
if ((status = getaddrinfo("127.0.0.1", port, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
return false;
}
//make socket
fd = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol);
if (fd < 0) {
printf("\nserver socket failure %m", errno);
return false;
}
//connect
if(connect(fd, servinfo->ai_addr, servinfo->ai_addrlen) < 0) {
printf("\nclient connection failure %m", errno);
return false;
}
I know it should be simple, but I can't figure out how to change the IPs to get them to work. I tried setting the server computer's IP address in the quotes in these lines -
if ((status = getaddrinfo("127.0.0.1", port, &hints, &servinfo)) != 0)
and
unlink("127.0.0.1");
and then change the address in the client code to the client computer's IP address in this line -
if ((status = getaddrinfo("127.0.0.1", port, &hints, &servinfo)) != 0)
Whenever I do that, it tells me connection refused. I have also tried doing the opposite way of putting the server's address in the client's line and client's address in the server's lines along with a few other attempts. At this point I feel like I am just guessing though. So can someone please help me understand how to change this from using the local address with one computer to connecting two computers? Any help is appreciated.
First, unlink("127.0.0.1"); is totally wrong here, don't do that.
Then, you have two computers connected by some network. Both should have IP addresses. Replace 127.0.0.1 with the server's IP address in both client and the server. The server does not to have to know client's address beforehand - it'll get that information from the accept(2) call. The client needs server's address to know where to connect. The server needs its own address for the bind(2) call.
The main problem is that your putting AI_PASSIVE in your client code. AI_PASSIVE is meant for servers only (that's what it signals).
Also on the server side you should first of all not call unlink. That's for AF_UNIX sockets only, not AF_INET. Secondly you don't need to put "127.0.0.1" in the getaddrinfo line on the server side. It's better to use NULL to bind to all available addresses.
If you change those things, I believe your code should work. However you're actually supposed to loop on the getaddrinfo result using the ai_next pointer and try to connect to each result, using the first that succeeds.
Connection Refused usually means your client received a RST to his SYN. This is most often caused by the lack of a listening socket on the server, on the port you're trying to connect to.
Run your server
On the CLI, type netstat -ant. Do you see an entry that's in LISTEN state on your port?
Something like:
tcp4 0 0 *.3689 *.* LISTEN
I bet you do not, and therefore have a problem with your server listening socket. I also bet the changes you made this this line:
if ((status = getaddrinfo("127.0.0.1", port, &hints, &servinfo)) != 0) {
Weren't quite right. Try changing that IP to 0.0.0.0 on the server to tell it to to bind to any IP on the system. On the client, that line should have the IP address of the server. You should also remove the unlink() call in the server; unnecessary.
If you do have a listening socket, then there's probably a firewall or something in between your boxes that's blocking the SYN. Try typing service iptables stop on the CLI of both systems.

Resources