سؤال

QUESTION : I'm trying to use WSAAddressToString function to get the ip address of the computer .I went through the msdn documentation in their website and there are too many structures within structures and i feel that's the place where i'm going wrong . The code is provided in the pastebin link here . Please let me know where exactly I'm going wrong.

ANSWER : The issue is fixed after including WSAStartup function in the code and some modifications in the existing code . The complete code is in the pastebin and the modified section is below .

     retval = WSAStartup(MAKEWORD(2, 2), &wsaData);
      if (retval != 0)
      {
          printf("WSAStartup() failed with error code %d\n", WSAGetLastError());
            return 1;
      }
   else
       printf("WSAStartup() is OK...\n");


        size=256;

        lp=pAddresses->FirstUnicastAddress->Address.lpSockaddr;
        size2=pAddresses->FirstUnicastAddress->Address.iSockaddrLength;
        if(WSAAddressToStringA(lp,size2,NULL,op,&size)!= 0)
        {
                    printf("This thing has failed \n");
                    printf("errordetail: %i\n", WSAGetLastError());

                    return 1;
        }
        else
                    printf("\t The ip address is  = %s\n", op);
هل كانت مفيدة؟

المحلول

Please change this:

if(WSAAddressToString(lp,size2, NULL,op,&size) != 0) {
    printf("This thing has failed \n");   
    return 1;
} else
    printf("Address string = %s\n", op);
    pAddresses = pAddresses->Next;
}

To this:

long errorcode = WSAAddressToString(lp,size2, NULL,op,&size);
if(errorcode != 0) {
    printf("The error is number: %i\n", errorcode);   
    return 1;
} else
    printf("Address string = %s\n", op);
    pAddresses = pAddresses->Next;
}

Then tell us what number it printed.

Or look it up in http://msdn.microsoft.com/en-us/library/windows/desktop/ms681381%28v=vs.85%29.aspx

EDIT:

SOCKADDR_IN6 addrTemp;
addrTemp.sin6_family = AF_INET6;
long errorcode = WSAAddressToString(&addrTemp,size2, NULL,op,&size);
if(errorcode != 0) {
    //printf("The error is number: %i\n", errorcode);   
    printf("errordetail: %i\n", WSAGetLastError());
    return 1;
} else
    printf("Address string = %s\n", op);
    pAddresses = pAddresses->Next;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top