4

问题:我正在尝试使用WSAAddressToString函数来获取计算机的 IP 地址。我浏览了他们网站上的 msdn 文档,结构中的结构太多,我觉得那是我出错的地方。代码在 此处的 pastebin 链接中提供。请让我知道我到底哪里错了。

解答: 在代码中包含WSAStartup函数并在现有代码中进行一些修改后,该问题已得到解决。完整的代码在 pastebin 中,修改后的部分如下。

     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);
4

1 回答 1

6

请更改此:

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;
}

对此:

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;
}

然后告诉我们它打印的数字。

或者在http://msdn.microsoft.com/en-us/library/windows/desktop/ms681381%28v=vs.85%29.aspx中查找

编辑:

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;
}
于 2013-06-29T12:49:42.587 回答