Advertisement

getaddrinfo() trouble

Started by April 11, 2018 11:40 PM
4 comments, last by hplus0603 6 years, 7 months ago

I am trying to implement name resolution by using getaddrinfo. Below is my code. When the code is run, sendto() gives an error 10047. I have a feeling that I'm using getaddrinfo incorrectly.


	    cout << "  Sending on port " << port_number << " - CTRL+C to exit." << endl;
	    struct addrinfo hints;
    struct addrinfo *result;
	    memset(&hints, 0, sizeof(struct addrinfo));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_DGRAM;
    hints.ai_flags = 0;
    hints.ai_protocol = IPPROTO_UDP;
	    int s = getaddrinfo("localhost", "1920", &hints, &result);
	    if (s != 0)
    {
      cout << "  getaddrinfo error." << endl;
    }
	    if (INVALID_SOCKET == (udp_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)))
    {
      cout << "  Could not allocate a new socket." << endl;
      cleanup();
      return 3;
    }
	    while (!stop)
    {
      if (SOCKET_ERROR == (sendto(udp_socket, tx_buf, tx_buf_size, 0, (struct  sockaddr*)result, sizeof(struct sockaddr))))
      {
        cout << WSAGetLastError() << endl;
	        if (!stop)
          cout << " (TX ERR)" << endl;
	        break;
      }
    }
	    // call freeaddrinfo...
	

Have you looked up what the error means? https://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx

 

Advertisement

See the struct definition at https://msdn.microsoft.com/en-us/library/windows/desktop/ms737530(v=vs.85).aspx


typedef struct addrinfo {
  int             ai_flags;
  int             ai_family;
  int             ai_socktype;
  int             ai_protocol;
  size_t          ai_addrlen;
  char            *ai_canonname;
  struct sockaddr  *ai_addr;
  struct addrinfo  *ai_next;
} ADDRINFOA, *PADDRINFOA;

You're reinterpreting the start of this struct as an sockaddr, which is completely wrong.

You probably want to use the ai_addr field of your addrinfo, which holds the sockaddr instead of a bunch of assorted fields.

To make it is hell. To fail is divine.

Yes Zao, I needed to use the result->ai_addr member as the sendto() parameter. Thanks!!!

Kylotan, that's a very good resource to have. Thank you.

 


	    if (INVALID_SOCKET == (udp_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)))

 

Additionally: The addrinfo struct contains the values you should pass for address family, socket type, and protocol number. Don't hard-code them, even if you provide them in as hints.

 

enum Bool { True, False, FileNotFound };

This topic is closed to new replies.

Advertisement