mirror of
https://github.com/FairRootGroup/FairMQ.git
synced 2025-10-15 17:41:45 +00:00
add helper function to find IPs of the node
This commit is contained in:
committed by
Mohammad Al-Turany
parent
bfa26e857d
commit
a9b7e8866c
64
fairmq/tools/FairMQTools.h
Normal file
64
fairmq/tools/FairMQTools.h
Normal file
@@ -0,0 +1,64 @@
|
||||
#ifndef FAIRMQTOOLS_H_
|
||||
#define FAIRMQTOOLS_H_
|
||||
|
||||
#ifndef _GNU_SOURCE
|
||||
#define _GNU_SOURCE /* To get defns of NI_MAXSERV and NI_MAXHOST */
|
||||
#endif
|
||||
|
||||
#include <sys/socket.h>
|
||||
#include <sys/types.h>
|
||||
#include <netdb.h>
|
||||
#include <ifaddrs.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
namespace FairMQ
|
||||
{
|
||||
namespace tools
|
||||
{
|
||||
|
||||
int getHostIPs(map<string, string>& addressMap)
|
||||
{
|
||||
struct ifaddrs *ifaddr, *ifa;
|
||||
int s;
|
||||
char host[NI_MAXHOST];
|
||||
|
||||
if (getifaddrs(&ifaddr) == -1)
|
||||
{
|
||||
perror("getifaddrs");
|
||||
return -1;
|
||||
}
|
||||
|
||||
for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
|
||||
{
|
||||
if (ifa->ifa_addr == NULL)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ifa->ifa_addr->sa_family == AF_INET)
|
||||
{
|
||||
s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
|
||||
if (s != 0)
|
||||
{
|
||||
cout << "getnameinfo() failed: " << gai_strerror(s) << endl;
|
||||
return -1;
|
||||
}
|
||||
|
||||
addressMap.insert(pair<string, string>(ifa->ifa_name, host));
|
||||
}
|
||||
}
|
||||
freeifaddrs(ifaddr);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
} // namespace tools
|
||||
} // namespace FairMQ
|
||||
|
||||
#endif
|
35
fairmq/tools/README.md
Normal file
35
fairmq/tools/README.md
Normal file
@@ -0,0 +1,35 @@
|
||||
# FairMQ Tools
|
||||
|
||||
Contains common tools for use by FairMQ and/or users.
|
||||
|
||||
## FairMQ::tools::getHostIPs
|
||||
|
||||
Fills a map with the network interfaces and their IP addresses available on the current host.
|
||||
|
||||
#### Example usage
|
||||
|
||||
```c++
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <iostream>
|
||||
|
||||
#include "FairMQTools.h"
|
||||
|
||||
void main()
|
||||
{
|
||||
std::map<string,string> IPs;
|
||||
|
||||
FairMQ::tools::getHostIPs(IPs);
|
||||
|
||||
for (std::map<string,string>::iterator it = IPs.begin(); it != IPs.end(); ++it)
|
||||
{
|
||||
std::cout << it->first << ": " << it->second << std::endl;
|
||||
}
|
||||
}
|
||||
```
|
||||
##### Example Output
|
||||
```
|
||||
eth0: 123.123.1.123
|
||||
ib0: 123.123.2.123
|
||||
lo: 127.0.0.1
|
||||
```
|
Reference in New Issue
Block a user