LWS_VISIBLE const char * lws_plat_inet_ntop(int af, const void *src, char *dst, int cnt) { WCHAR *buffer; DWORD bufferlen = cnt; BOOL ok = FALSE; buffer = lws_malloc(bufferlen); if (!buffer) { lwsl_err("Out of memory\n"); return NULL; } if (af == AF_INET) { struct sockaddr_in srcaddr; bzero(&srcaddr, sizeof(srcaddr)); srcaddr.sin_family = AF_INET; memcpy(&(srcaddr.sin_addr), src, sizeof(srcaddr.sin_addr)); if (!WSAAddressToStringW((struct sockaddr*)&srcaddr, sizeof(srcaddr), 0, buffer, &bufferlen)) ok = TRUE; #ifdef LWS_USE_IPV6 } else if (af == AF_INET6) { struct sockaddr_in6 srcaddr; bzero(&srcaddr, sizeof(srcaddr)); srcaddr.sin6_family = AF_INET6; memcpy(&(srcaddr.sin6_addr), src, sizeof(srcaddr.sin6_addr)); if (!WSAAddressToStringW((struct sockaddr*)&srcaddr, sizeof(srcaddr), 0, buffer, &bufferlen)) ok = TRUE; #endif } else lwsl_err("Unsupported type\n"); if (!ok) { int rv = WSAGetLastError(); lwsl_err("WSAAddressToString() : %d\n", rv); } else { if (WideCharToMultiByte(CP_ACP, 0, buffer, bufferlen, dst, cnt, 0, NULL) <= 0) ok = FALSE; } lws_free(buffer); return ok ? dst : NULL; }
static void SockAddrToString(sockaddr * addr, int addrlen, std::string & out) { wchar_t buffer[INET6_ADDRSTRLEN]; DWORD buflen = INET6_ADDRSTRLEN; int res = WSAAddressToStringW(addr, addrlen, nullptr, buffer, &buflen); if (res != 0) throw_winsock2_error(::WSAGetLastError(), "WSAAddressToStringW failed"); buflen -= 1; out.clear(); std::codecvt_utf8<wchar_t> cvt; ext::codecvt_convert::to_bytes(cvt, boost::make_iterator_range_n(buffer, buflen), out); }
//****************************************************************************** // Routine: // PrintAddress // // Description: // The function prints out the address contained in the SOCKADDR_STORAGE // //****************************************************************************** VOID PrintAddress(PSOCKADDR_STORAGE pSocketAddress) { DWORD cbBuffer = 2000; WCHAR buffer[2000]; SOCKADDR_STORAGE socketAddress; ULONG Length; if (!pSocketAddress) { return; } ZeroMemory(buffer, sizeof(buffer)); ZeroMemory(&socketAddress, sizeof(socketAddress)); // // If the address is empty, print * // if (!memcmp(((PBYTE)&socketAddress) + sizeof(USHORT), ((PBYTE)pSocketAddress) + sizeof(USHORT), sizeof(socketAddress) - sizeof(USHORT))) { printf("\tAddress: *\n"); return; } Length = (pSocketAddress->ss_family == AF_INET ? sizeof(SOCKADDR_IN) : sizeof(SOCKADDR_IN6)); if (SOCKET_ERROR == WSAAddressToStringW((LPSOCKADDR)(pSocketAddress), Length, NULL, buffer, &cbBuffer)) { printf("WSAAddressToStringW() failed with 0x%x\n", WSAGetLastError()); buffer[0] = L'\0'; } printf("\tAddress: %S\n", buffer); }
static ce::wstring IPAddressString( ) { ce::auto_ptr<IP_ADAPTER_ADDRESSES> AdapterAddresses; // buffer used by GetAdaptersAddresses() ULONG BufferSize = 0; // size of buffer returned by GetAdaptersAddresses() DWORD Result = 0; // result codes from iphelper apis WCHAR NetworkAddress[ s_MAXNETADDRLEN ]; DWORD AddressLen = s_MAXNETADDRLEN; // Find out size of returned buffer Result = GetAdaptersAddresses( AF_INET, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_DNS_SERVER, NULL, AdapterAddresses, &BufferSize ); if(BufferSize) { // Allocate sufficient Space AdapterAddresses = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(operator new (BufferSize)); if (AdapterAddresses != NULL) { // Get Adapter List Result = GetAdaptersAddresses( AF_INET, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_DNS_SERVER, NULL, AdapterAddresses, &BufferSize ); if (Result == ERROR_SUCCESS) { // Loop through all the adapters (interfaces) returned for(PIP_ADAPTER_ADDRESSES pAdapterIter = AdapterAddresses; pAdapterIter != NULL; pAdapterIter = pAdapterIter->Next) { // don't use tunneling adapters if(pAdapterIter->IfType == IF_TYPE_SOFTWARE_LOOPBACK) { continue; } // Loop through all the addresses returned for(PIP_ADAPTER_UNICAST_ADDRESS pUnicastAddress = pAdapterIter->FirstUnicastAddress; pUnicastAddress != NULL; pUnicastAddress = pUnicastAddress->Next) { if(((PSOCKADDR_IN)pUnicastAddress->Address.lpSockaddr)->sin_addr.S_un.S_addr) { //Convert from Address to string SOCKADDR sa; sa = *(pUnicastAddress->Address.lpSockaddr); if (WSAAddressToStringW( &sa, pUnicastAddress->Address.iSockaddrLength, NULL, NetworkAddress, &AddressLen) == 0) //success { return ce::wstring( NetworkAddress ); } } } } } } } return ce::wstring(); }
int main (int argc, char **argv) { int ret; int r = 1; WSADATA wsd; GUID prov; GUID sc; wchar_t *cmdl; int wargc; wchar_t **wargv; if (WSAStartup(MAKEWORD(2,2), &wsd) != 0) { fprintf (stderr, "WSAStartup() failed: %lu\n", GetLastError()); return 5; } cmdl = GetCommandLineW (); if (cmdl == NULL) { WSACleanup(); return 2; } wargv = CommandLineToArgvW (cmdl, &wargc); if (wargv == NULL) { WSACleanup(); return 3; } r = 4; if (wargc == 5) { if (wcscmp (wargv[1], L"A") == 0) sc = SVCID_DNS_TYPE_A; else if (wcscmp (wargv[1], L"AAAA") == 0) sc = SVCID_DNS_TYPE_AAAA; else if (wcscmp (wargv[1], L"name") == 0) sc = SVCID_HOSTNAME; else if (wcscmp (wargv[1], L"addr") == 0) sc = SVCID_INET_HOSTADDRBYNAME; else wargc -= 1; if (wcscmp (wargv[4], L"mswdns") == 0) prov = W32_DNS; else if (wcscmp (wargv[4], L"gnunetdns") == 0) prov = GNUNET_NAMESPACE_PROVIDER_DNS; else wargc -= 1; } else if (wargc == 3) { } else { fprintf (stderr, "Usage: %S <record type> <service name> <NSP library path> <NSP id>\n" "record type - one of the following: A | AAAA | name | addr\n" "service name - a string to resolve; \" \" (a space) means 'blank'\n" "NSP library path - path to libw32nsp\n" "NSP id - one of the following: mswdns | gnunetdns\n", wargv[0]); } if (wargc == 5) { HMODULE nsp; nsp = LoadLibraryW (wargv[3]); if (nsp == NULL) { fprintf (stderr, "Failed to load library `%S'\n", wargv[3]); } else { LPNSPSTARTUP startup = (LPNSPSTARTUP) GetProcAddress (nsp, "NSPStartup"); if (startup == NULL) startup = (LPNSPSTARTUP) GetProcAddress (nsp, "NSPStartup@8"); if (startup != NULL) { NSP_ROUTINE api; api.cbSize = sizeof (api); ret = startup (&prov, &api); if (NO_ERROR != ret) fprintf (stderr, "startup failed: %lu\n", GetLastError ()); else { HANDLE lookup; WSAQUERYSETW search; char buf[4096]; WSAQUERYSETW *result = (WSAQUERYSETW *) buf; DWORD resultsize; DWORD err; memset (&search, 0, sizeof (search)); search.dwSize = sizeof (search); search.lpszServiceInstanceName = (wcscmp (wargv[2], L" ") == 0) ? NULL : wargv[2]; search.lpServiceClassId = ≻ search.lpNSProviderId = &prov; search.dwNameSpace = NS_ALL; ret = api.NSPLookupServiceBegin (&prov, &search, NULL, LUP_RETURN_ALL, &lookup); if (ret != NO_ERROR) { fprintf (stderr, "lookup start failed\n"); } else { resultsize = 4096; ret = api.NSPLookupServiceNext (lookup, LUP_RETURN_ALL, &resultsize, result); err = GetLastError (); if (ret != NO_ERROR) { fprintf (stderr, "lookup next failed: %lu\n", err); } else { int i; printf ("Got result:\n"); printf (" lpszServiceInstanceName: %S\n", result->lpszServiceInstanceName ? result->lpszServiceInstanceName : L"NULL"); if (result->lpServiceClassId) printf (" lpServiceClassId: { 0x%08lX,0x%04X,0x%04X, { 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X } }\n", result->lpServiceClassId->Data1, result->lpServiceClassId->Data2, result->lpServiceClassId->Data3, result->lpServiceClassId->Data4[0], result->lpServiceClassId->Data4[1], result->lpServiceClassId->Data4[2], result->lpServiceClassId->Data4[3], result->lpServiceClassId->Data4[4], result->lpServiceClassId->Data4[5], result->lpServiceClassId->Data4[6], result->lpServiceClassId->Data4[7]); else printf (" lpServiceClassId: NULL\n"); if (result->lpVersion) printf (" lpVersion: 0x%08lX, %d\n", result->lpVersion->dwVersion, result->lpVersion->ecHow); else printf (" lpVersion: NULL\n"); printf (" lpszComment: %S\n", result->lpszComment ? result->lpszComment : L"NULL"); printf (" dwNameSpace: %lu\n", result->dwNameSpace); if (result->lpNSProviderId) printf (" lpNSProviderId: { 0x%08lX,0x%04X,0x%04X, { 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X } }\n", result->lpNSProviderId->Data1, result->lpNSProviderId->Data2, result->lpNSProviderId->Data3, result->lpNSProviderId->Data4[0], result->lpNSProviderId->Data4[1], result->lpNSProviderId->Data4[2], result->lpNSProviderId->Data4[3], result->lpNSProviderId->Data4[4], result->lpNSProviderId->Data4[5], result->lpNSProviderId->Data4[6], result->lpNSProviderId->Data4[7]); else printf (" lpNSProviderId: NULL\n"); printf (" lpszContext: %S\n", result->lpszContext ? result->lpszContext : L"NULL"); printf (" dwNumberOfProtocols: %lu\n", result->dwNumberOfProtocols); printf (" lpszQueryString: %S\n", result->lpszQueryString ? result->lpszQueryString : L"NULL"); printf (" dwNumberOfCsAddrs: %lu\n", result->dwNumberOfCsAddrs); for (i = 0; i < result->dwNumberOfCsAddrs; i++) { switch (result->lpcsaBuffer[i].iSocketType) { case SOCK_STREAM: printf (" %d: iSocketType = SOCK_STREAM\n", i); break; case SOCK_DGRAM: printf (" %d: iSocketType = SOCK_DGRAM\n", i); break; default: printf (" %d: iSocketType = %d\n", i, result->lpcsaBuffer[i].iSocketType); } switch (result->lpcsaBuffer[i].iProtocol) { case IPPROTO_TCP: printf (" %d: iProtocol = IPPROTO_TCP\n", i); break; case IPPROTO_UDP: printf (" %d: iProtocol = IPPROTO_UDP\n", i); break; default: printf (" %d: iProtocol = %d\n", i, result->lpcsaBuffer[i].iProtocol); } switch (result->lpcsaBuffer[i].LocalAddr.lpSockaddr->sa_family) { case AF_INET: printf (" %d: loc family = AF_INET\n", i); break; case AF_INET6: printf (" %d: loc family = AF_INET6\n", i); break; default: printf (" %d: loc family = %hu\n", i, result->lpcsaBuffer[i].LocalAddr.lpSockaddr->sa_family); } switch (result->lpcsaBuffer[i].RemoteAddr.lpSockaddr->sa_family) { case AF_INET: printf (" %d: rem family = AF_INET\n", i); break; case AF_INET6: printf (" %d: rem family = AF_INET6\n", i); break; default: printf (" %d: rem family = %hu\n", i, result->lpcsaBuffer[i].RemoteAddr.lpSockaddr->sa_family); } char buf[1024]; DWORD buflen = 1024; if (NO_ERROR == WSAAddressToStringA (result->lpcsaBuffer[i].LocalAddr.lpSockaddr, result->lpcsaBuffer[i].LocalAddr.iSockaddrLength, NULL, buf, &buflen)) printf("\tLocal Address #%d: %s\n", i, buf); else printf("\tLocal Address #%d: Can't convert: %lu\n", i, GetLastError ()); buflen = 1024; if (NO_ERROR == WSAAddressToStringA (result->lpcsaBuffer[i].RemoteAddr.lpSockaddr, result->lpcsaBuffer[i].RemoteAddr.iSockaddrLength, NULL, buf, &buflen)) printf("\tRemote Address #%d: %s\n", i, buf); else printf("\tRemote Address #%d: Can't convert: %lu\n", i, GetLastError ()); } printf (" dwOutputFlags: 0x%08lX\n", result->dwOutputFlags); printf (" lpBlob: 0x%p\n", result->lpBlob); if (result->lpBlob) { struct hostent *he = malloc (result->lpBlob->cbSize); if (he != NULL) { GNUNET_memcpy (he, result->lpBlob->pBlobData, result->lpBlob->cbSize); UnpackHostEnt (he); print_hostent (he); free (he); } } } ret = api.NSPLookupServiceEnd (lookup); if (ret != NO_ERROR) printf ("NSPLookupServiceEnd() failed: %lu\n", GetLastError ()); } api.NSPCleanup (&prov); } } FreeLibrary (nsp); } } else if (wargc == 3) { int s; ADDRINFOW hints; ADDRINFOW *result; ADDRINFOW *pos; memset (&hints, 0, sizeof (struct addrinfo)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if (0 != (s = GetAddrInfoW (wargv[2], NULL, &hints, &result))) { fprintf (stderr, "Cound not resolve `%S' using GetAddrInfoW: %lu\n", wargv[2], GetLastError ()); } else { for (pos = result; pos != NULL; pos = pos->ai_next) { wchar_t tmpbuf[1024]; DWORD buflen = 1024; if (0 == WSAAddressToStringW (pos->ai_addr, pos->ai_addrlen, NULL, tmpbuf, &buflen)) fprintf (stderr, "Result:\n" " flags: 0x%X\n" " family: 0x%X\n" " socktype: 0x%X\n" " protocol: 0x%X\n" " addrlen: %u\n" " addr: %S\n" " canonname: %S\n", pos->ai_flags, pos->ai_family, pos->ai_socktype, pos->ai_protocol, pos->ai_addrlen, tmpbuf, pos->ai_canonname); else fprintf (stderr, "Result:\n" " flags: 0x%X\n" " family: 0x%X\n" " socktype: 0x%X\n" " protocol: 0x%X\n" " addrlen: %u\n" " addr: %S\n" " canonname: %S\n", pos->ai_flags, pos->ai_family, pos->ai_socktype, pos->ai_protocol, pos->ai_addrlen, L"<can't stringify>", pos->ai_canonname); } if (NULL != result) FreeAddrInfoW (result); } } WSACleanup(); return r; }
/*! * \brief * This function pings an IPv6-Address with a specified Time-To-Live-value. * * \param ai * The AddrInfo-representation of the TargetIP * * \param ttl * The Time-To-Live-value to perform the ping with * * \param out * The Buffer into which the result of the ping-command will be written * * \param outSize * The maximum number of characters that can be written into "out" * * \returns * True if the execution succeded and false otherwise. The following will be written in "out": "TARGET "+TargetIP if the target was reached, "HOP "+HopIP if an intermediate Host was reached or "NO_REPLY" if an execution error occurred. If an internal error occured, a message describing that error will be written. * * \remarks * ai will be Freed */ bool ping6(struct addrinfoW *ai, int ttl, WCHAR * out, int outSize){ // Create a handle to a hIcmpFile (required by Icmp6SendEcho2) HANDLE hIcmpFile = Icmp6CreateFile(); if (hIcmpFile == INVALID_HANDLE_VALUE) { outPutWstring(std::wstring(L"Icmp6Createfile returned error: ")+getFormatedLastError(),out,outSize); // Free all allocated resources FreeAddrInfoW(ai); return false; } // A ICMP-request using IPv6 requires a source address: Get the system's IPv6 addresses ADDRINFOW hints; memset(&hints,0,sizeof(ADDRINFOW)); hints.ai_family = AF_INET6; struct addrinfoW *lai; if(! (0==GetAddrInfoW(L"",NULL,&hints,&lai))){ outPutWstring(std::wstring(L"Invalid Socket (Localhost) : ")+getFormatedLastError(),out,outSize); // Free all allocated resources FreeAddrInfoW(ai); IcmpCloseHandle(hIcmpFile); return false; } // Out of all of the system's IPv6-addresses: get a global IPv6 IP-Address for localhost struct addrinfoW *sourceGlobal = lai; while(sourceGlobal != NULL){ sockaddr_in6 * a = (sockaddr_in6 *)sourceGlobal->ai_addr; if(IN6_IS_ADDR_GLOBAL(&a->sin6_addr)) break; sourceGlobal = sourceGlobal->ai_next; } // If there is none then there is no way to perform an ICMP-request on a IPv6-address -> abbort! if(sourceGlobal == NULL){ outPutWstring(std::wstring(L"No global IPv6 interface found on localhost: ")+getFormatedLastError(),out,outSize); // Free all allocated resources FreeAddrInfoW(ai); FreeAddrInfoW(lai); IcmpCloseHandle(hIcmpFile); return false; } // Build the payload of the ICMP-request (mustn't be empty) char SendData[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345"; // Allocate space for a single reply DWORD ReplySize = sizeof (ICMPV6_ECHO_REPLY) + sizeof (SendData) + 8 + sizeof(IO_STATUS_BLOCK); LPVOID ReplyBuffer = (VOID *) malloc(ReplySize); // Create a IP_OPTION_INFORMATION and set its TTL-field so Icmp6SendEcho2 will perform a ping with the correct TTL IP_OPTION_INFORMATION ipopts; memset(&ipopts,0,sizeof(ipopts)); ipopts.Ttl = (unsigned char)ttl; //Try to perform the actual ping DWORD dwRetVal = Icmp6SendEcho2(hIcmpFile, NULL, NULL, NULL,(sockaddr_in6 *)sourceGlobal->ai_addr, (sockaddr_in6 *)ai->ai_addr, SendData, sizeof (SendData), &ipopts, ReplyBuffer, ReplySize, 1000); if (dwRetVal == 0) { // In case it failed: Did it fail because of a timeout or because of a serious problem? bool success = false; DWORD lastError = GetLastError(); if(IP_REQ_TIMED_OUT == lastError || IP_DEST_NET_UNREACHABLE == lastError ){ // If it failed because of a Timeout return "NO_REPLY" outPutWstring(std::wstring(L"NO_REPLY"),out,outSize); success = true; } else{ // If it failed because of a serious problem return a detailed description about the failure outPutWstring(std::wstring(L"Call to Icmp6SendEcho2 failed: ")+getFormatedLastError(),out,outSize); } // Free all allocated resources FreeAddrInfoW(ai); FreeAddrInfoW(lai); free(ReplyBuffer); IcmpCloseHandle(hIcmpFile); return success; } // Parse the reply on the ICMP-request PICMPV6_ECHO_REPLY pEchoReply = (PICMPV6_ECHO_REPLY) ReplyBuffer; /* * Extract the address of the replying host */ // First: copy the reply data into a sockaddr_in6-struckture PIPV6_ADDRESS_EX pIP6Addr = &pEchoReply->Address;; sockaddr_in6 sock6; sock6.sin6_family = AF_INET6; sock6.sin6_flowinfo = pIP6Addr->sin6_flowinfo; sock6.sin6_port = pIP6Addr->sin6_port; sock6.sin6_scope_id = pIP6Addr->sin6_scope_id; memcpy(&sock6.sin6_addr, pIP6Addr->sin6_addr,sizeof(IN6_ADDR)); // Second: convert it into human readable version WCHAR ip6AddressString[256]; DWORD bufferLenght = 256; if(0 != WSAAddressToStringW((LPSOCKADDR)&sock6,sizeof(sockaddr_in6),NULL,ip6AddressString,&bufferLenght)){ outPutWstring(std::wstring(L"Call to WSAAddressToStringW failed: ")+getFormatedLastError(),out,outSize); // Free all allocated resources FreeAddrInfoW(ai); FreeAddrInfoW(lai); free(ReplyBuffer); IcmpCloseHandle(hIcmpFile); return false; } // Third: convert it into a wstring std::wstring hopName = std::wstring(ip6AddressString); /* * Switch according to status of reply */ ULONG status = pEchoReply->Status; if(status == IP_SUCCESS){ // Ping reached the target outPutWstring(std::wstring(L"TARGET ")+ hopName,out,outSize); } else if(status == IP_TTL_EXPIRED_TRANSIT || status == IP_TTL_EXPIRED_REASSEM){ // Ping got a reply from a hop on the way to target outPutWstring(std::wstring(L"HOP ")+ hopName,out,outSize); } else{ // Something didn't work outPutWstring(std::wstring(L"NO_REPLY"),out,outSize); } // Free all allocated resources free(ReplyBuffer); FreeAddrInfoW(ai); FreeAddrInfoW(lai); IcmpCloseHandle(hIcmpFile); return true; }
static BOOL socket_address_to_string(WCHAR *buf, DWORD len, SOCKET_ADDRESS *addr) { return WSAAddressToStringW(addr->lpSockaddr, addr->iSockaddrLength, NULL, buf, &len) == 0; }
int wmain(int argc, WCHAR *argv[]) { WSADATA wsaData; ULONG i; DWORD StrLen = 46; int Status; /* Initialize the Console Standard Streams */ ConInitStdStreams(); IpOptions.Ttl = 128; if (!ParseCmdLine(argc, argv)) return 1; if (!SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE)) { DPRINT("Failed to set control handler: %lu\n", GetLastError()); return 1; } Status = WSAStartup(MAKEWORD(2, 2), &wsaData); if (Status != 0) { ConResPrintf(StdErr, IDS_WINSOCK_FAIL, Status); return 1; } if (!ResolveTarget(TargetName)) { WSACleanup(); return 1; } if (WSAAddressToStringW(Target->ai_addr, (DWORD)Target->ai_addrlen, NULL, Address, &StrLen) != 0) { DPRINT("WSAAddressToStringW failed: %d\n", WSAGetLastError()); FreeAddrInfoW(Target); WSACleanup(); return 1; } if (Family == AF_INET6) hIcmpFile = Icmp6CreateFile(); else hIcmpFile = IcmpCreateFile(); if (hIcmpFile == INVALID_HANDLE_VALUE) { DPRINT("IcmpCreateFile failed: %lu\n", GetLastError()); FreeAddrInfoW(Target); WSACleanup(); return 1; } if (*CanonName) ConResPrintf(StdOut, IDS_PINGING_HOSTNAME, CanonName, Address); else ConResPrintf(StdOut, IDS_PINGING_ADDRESS, Address); ConResPrintf(StdOut, IDS_PING_SIZE, RequestSize); Ping(); i = 1; while (i < PingCount) { Sleep(1000); Ping(); if (!PingForever) i++; } PrintStats(); IcmpCloseHandle(hIcmpFile); FreeAddrInfoW(Target); WSACleanup(); return 0; }