Jump to content
  • Advertisement

getaddrinfo() trouble

Recommended Posts

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;
      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;
	    // call freeaddrinfo...

Share this post

Link to post
Share on other sites

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;

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.

Edited by Zao

Share this post

Link to post
Share on other sites

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.

Share this post

Link to post
Share on other sites


	    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.


Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!