How to get this getnameinfo code

I get ai_family error not supported in getnameinfo call.

  1 #include <iostream>
  2 #include <sys/types.h>
  3 #include <unistd.h>
  4 #include <sys/socket.h>
  5 #include <netdb.h>
  6 #include <arpa/inet.h>
  7 #include <iomanip>
  8 extern "C" {
  9 #include "../../pg/include/errhnd.h"
 10 }
 11 
 12 using namespace std;
 13 
 14 
 15 int main(int argc, char** argv)
 16 {
 17         if (argc != 2)
 18                 err_quit("Usage: %s <ip address>", argv[0]);
 19 
 20         struct sockaddr_in sa;
 21         if (inet_pton(AF_INET, argv[1], &sa) <= 0)
 22                 err_sys("inet_pton error");
 23 
 24         char hostname[1000], servname[1000];
 25 
 26         cout << hex << (unsigned int)sa.sin_addr.s_addr << endl;
 27 
 28         sa.sin_port = htons(80);
 29 
 30         int x;
 31         if ((x=getnameinfo((struct sockaddr*)&(sa.sin_addr),
 32                          16, hostname, 1000, servname, 1000, NI_NAMEREQD)) != 0) {
 33                 err_ret("getnameinfo error");
 34                 cout << gai_strerror(x) << endl;
 35         }
 36 
 37         cout << hostname << " " << servname << endl;
 38 
 39         return 0;
 40 }
+3
source share
2 answers

Your problem is the challenge inet_pton. When AF_INETa family of addresses is passed, the pointer dstmust be a pointer to struct in_addr, not struct sockaddr_in.

Change line 21 to:

if (inet_pton(AF_INET, argv[1], &sa.sin_addr) <= 0)

Insert a line in line 23:

sa.sin_family = AF_INET;

Change the lines from 31-32 to:

if ((x=getnameinfo((struct sockaddr*)&sa, sizeof sa,
    hostname, sizeof hostname, servname, sizeof servname, NI_NAMEREQD)) != 0) {

then it should work.

+3
source

The first parameter of the function must be a member struct sockaddr_innot sin_addr.

If you are using IPv6, you need to use struct sockaddr_in6instead struct sockaddr_in. This may be the cause of EAI_FAMILY.

, : http://linux.die.net/man/3/getnameinfo.

0

Source: https://habr.com/ru/post/1719279/


All Articles