static gboolean extract_address_and_prefix (PIP_ADAPTER_UNICAST_ADDRESS adapter, PIP_ADAPTER_PREFIX prefix, char *iface, char *network) { DWORD ret = 0; DWORD len = INET6_ADDRSTRLEN; ret = WSAAddressToStringA (adapter->Address.lpSockaddr, adapter->Address.iSockaddrLength, NULL, iface, &len); if (ret != 0) return FALSE; if (prefix) { ret = WSAAddressToStringA (prefix->Address.lpSockaddr, prefix->Address.iSockaddrLength, NULL, network, &len); if (ret != 0) return FALSE; } else if (strcmp (iface, "127.0.0.1")) strcpy (network, "127.0.0.0"); else return FALSE; return TRUE; }
void TcpConnection::init_addr(){ if( !this->connected_) return; if( local_addr == NULL ){ struct sockaddr_in local_sockaddr; int addrlen = sizeof(struct sockaddr_storage); getsockname(socket_, (struct sockaddr*)&local_sockaddr, &addrlen); DWORD len = addrlen; //local_addr = inet_ntoa(local_sockaddr.sin_addr); local_addr = new char[22]; if( WSAAddressToStringA((LPSOCKADDR)&local_sockaddr, addrlen, NULL, local_addr, &len) != 0){ printf("WSAAddressToString() failed with error code %ld\n", WSAGetLastError()); } } if( remote_addr == NULL ){ struct sockaddr_in remote_sockaddr; int addrlen = sizeof(struct sockaddr_storage); getpeername(socket_, (struct sockaddr*)&remote_sockaddr, &addrlen); DWORD len = addrlen; //remote_addr = inet_ntoa(remote_sockaddr.sin_addr); remote_addr = new char[22]; if( WSAAddressToStringA((LPSOCKADDR)&remote_sockaddr, addrlen, NULL, remote_addr, &len) != 0){ printf("WSAAddressToString() failed with error code %ld\n", WSAGetLastError()); } } }
static void print_hostent (struct hostent *he) { int i; char **pAlias; printf("\tOfficial name: %s\n", he->h_name); for (i=0, pAlias = he->h_aliases; *pAlias != 0; pAlias++) { printf("\tAlternate name #%d: %s\n", ++i, *pAlias); } printf("\tAddress type: "); switch (he->h_addrtype) { case AF_INET: printf("AF_INET\n"); break; case AF_INET6: printf("AF_INET6\n"); break; case AF_NETBIOS: printf("AF_NETBIOS\n"); break; default: printf(" %d\n", he->h_addrtype); break; } printf("\tAddress length: %d\n", he->h_length); if (he->h_addrtype == AF_INET) { struct sockaddr_in addr; memset (&addr, 0, sizeof (addr)); addr.sin_family = AF_INET; addr.sin_port = 0; i = 0; while (he->h_addr_list[i] != 0) { char buf[1024]; DWORD buflen = 1024; addr.sin_addr = *(struct in_addr *) he->h_addr_list[i++]; if (NO_ERROR == WSAAddressToStringA ((LPSOCKADDR) &addr, sizeof (addr), NULL, buf, &buflen)) printf("\tIPv4 Address #%d: %s\n", i, buf); else printf("\tIPv4 Address #%d: Can't convert: %lu\n", i, GetLastError ()); } } else if (he->h_addrtype == AF_INET6) { struct sockaddr_in6 addr; memset (&addr, 0, sizeof (addr)); addr.sin6_family = AF_INET6; addr.sin6_port = 0; i = 0; while (he->h_addr_list[i] != 0) { char buf[1024]; DWORD buflen = 1024; addr.sin6_addr = *(struct in6_addr *) he->h_addr_list[i++]; if (NO_ERROR == WSAAddressToStringA ((LPSOCKADDR) &addr, sizeof (addr), NULL, buf, &buflen)) printf("\tIPv6 Address #%d: %s\n", i, buf); else printf("\tIPv6 Address #%d: Can't convert: %lu\n", i, GetLastError ()); } } }
/** @details The conversion is based on the current IP address type (as returned by GetType). This * method uses internal network functions to do the conversion, and upon failure will return a * string of "Invalid" followed by the IP address type. If the IP address type is * IPAddressType::INVALID then this method simply returns "Invalid." * @returns A string of the human readable IP address. */ _CGUL_EXPORT CGUL::String CGUL::Network::IPAddress::ToString() const { char str[INET6_ADDRSTRLEN]; str[0] = 0; if (type == IPAddressType::INVALID) { return "Invalid"; } if (type == IPAddressType::IPV4) { # ifdef CGUL_WINDOWS sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = (ULONG)address[0]; // this will truncate the address, which is PROPER functionality DWORD length = INET6_ADDRSTRLEN; if (WSAAddressToStringA((sockaddr*)&addr, sizeof(addr), NULL, str, &length) != 0) { // we should never hit this case return "Invalid IPv4"; } # else if (inet_ntop(AF_INET, &address, str, sizeof(str)) == NULL) { // we should never hit this case return "Invalid IPv4"; } # endif } if (type == IPAddressType::IPV6) { # ifdef CGUL_WINDOWS sockaddr_in6 addr; memset(&addr, 0, sizeof(addr)); addr.sin6_family = AF_INET6; memcpy(&addr.sin6_addr, &address, sizeof(address)); DWORD length = INET6_ADDRSTRLEN; if (WSAAddressToStringA((sockaddr*)&addr, sizeof(addr), NULL, str, &length) != 0) { // we should never hit this case return "Invalid IPv6"; } # else if (inet_ntop(AF_INET6, &address, str, sizeof(str)) == NULL) { // we should never hit this case return "Invalid IPv6"; } # endif } return CGUL::String(str); }
const char * inet_ntop(int af, const void *src, char *dst, size_t size) { if (af != AF_INET && af != AF_INET6) return NULL; SOCKADDR_STORAGE address; DWORD address_length; if (af == AF_INET) { address_length = sizeof(struct sockaddr_in); struct sockaddr_in* ipv4_address = (struct sockaddr_in*)(&address); ipv4_address->sin_family = AF_INET; ipv4_address->sin_port = 0; memcpy(&ipv4_address->sin_addr, src, sizeof(struct in_addr)); } else // AF_INET6 { address_length = sizeof(struct sockaddr_in6); struct sockaddr_in6* ipv6_address = (struct sockaddr_in6*)(&address); ipv6_address->sin6_family = AF_INET6; ipv6_address->sin6_port = 0; ipv6_address->sin6_flowinfo = 0; // hmmm ipv6_address->sin6_scope_id = 0; memcpy(&ipv6_address->sin6_addr, src, sizeof(struct in6_addr)); } DWORD string_length = (DWORD)(size); int result; result = WSAAddressToStringA((struct sockaddr*)(&address), address_length, 0, dst, &string_length); // one common reason for this to fail is that ipv6 is not installed return result == SOCKET_ERROR ? NULL : dst; }
std::string GetLocalIP(int sock) { union { struct sockaddr sa; struct sockaddr_in ipv4; struct sockaddr_in6 ipv6; } server_addr; memset(&server_addr, 0, sizeof(server_addr)); socklen_t len = sizeof(server_addr); if (getsockname(sock, (struct sockaddr *)&server_addr, &len) == 0) { char temp[64]{}; // We clear the port below for WSAAddressToStringA. void *addr; if (server_addr.sa.sa_family == AF_INET6) { server_addr.ipv6.sin6_port = 0; addr = &server_addr.ipv6.sin6_addr; } else { server_addr.ipv4.sin_port = 0; addr = &server_addr.ipv4.sin_addr; } #ifdef _WIN32 DWORD len = (DWORD)sizeof(temp); // Windows XP doesn't support inet_ntop. if (WSAAddressToStringA((struct sockaddr *)&server_addr, sizeof(server_addr), nullptr, temp, &len) == 0) { return temp; } #else const char *result = inet_ntop(server_addr.sa.sa_family, addr, temp, sizeof(temp)); if (result) { return result; } #endif } return ""; }
std::string GetSocketIpAddressString(const sockaddr_in& socketAddress) { #if defined(_WIN32) DWORD addressStringLength = 256; std::string result; while(1) { result.resize(addressStringLength); int error = WSAAddressToStringA(reinterpret_cast<sockaddr*>(const_cast<sockaddr_in*>(&socketAddress)), sizeof(sockaddr_in), NULL, const_cast<char*>(result.data()), &addressStringLength); if(error == 0) { break; } else { error = WSAGetLastError(); if(error == WSAEFAULT && (result.size() != addressStringLength)) { //Size already has been updated continue; } else { result.clear(); break; } } } return result; #elif defined(__unix__) std::string result; socklen_t addressStringLength = INET_ADDRSTRLEN; while(1) { result.resize(addressStringLength); const char* error = inet_ntop(socketAddress.sin_family, &socketAddress.sin_addr, const_cast<char*>(result.data()), addressStringLength); if(error != NULL) { break; } else { if(errno == ENOSPC) { addressStringLength *= 2; continue; } else { result.clear(); break; } } } return result; #else return "(Not implemented)"; #endif }
static const char* _inet_ntop(int af, const void* src, char* dst, int cnt){ struct sockaddr_storage srcaddr; memset(dst, 0, cnt); memset(&srcaddr, 0, sizeof(struct sockaddr_storage)); srcaddr.ss_family = af; switch (af) { case AF_INET: { struct sockaddr_in * ipv4 = reinterpret_cast< struct sockaddr_in *>(&srcaddr); memcpy(&(ipv4->sin_addr), src, sizeof(ipv4->sin_addr)); } break; case AF_INET6: { struct sockaddr_in6 * ipv6 = reinterpret_cast< struct sockaddr_in6 *>(&srcaddr); memcpy(&(ipv6->sin6_addr), src, sizeof(ipv6->sin6_addr)); } break; } if (WSAAddressToStringA((struct sockaddr*) &srcaddr, sizeof(struct sockaddr_storage), 0, dst, (LPDWORD) &cnt) != 0) { DWORD rv = WSAGetLastError(); return NULL; } return dst; }
const char * lw_addr_tostring (lw_addr ctx) { if (!lw_addr_ready (ctx)) return ""; if (*ctx->buffer) return ctx->buffer; if ((!ctx->info) || (!ctx->info->ai_addr)) return ""; switch (ctx->info->ai_family) { case AF_INET: lwp_snprintf (ctx->buffer, sizeof (ctx->buffer), "%s:%d", inet_ntoa (((struct sockaddr_in *) ctx->info->ai_addr)->sin_addr), ntohs (((struct sockaddr_in *) ctx->info->ai_addr)->sin_port)); break; case AF_INET6: { int length = sizeof (ctx->buffer) - 1; #ifdef _WIN32 WSAAddressToStringA ((LPSOCKADDR) ctx->info->ai_addr, (DWORD) ctx->info->ai_addrlen, 0, ctx->buffer, (LPDWORD) &length); #else inet_ntop (AF_INET6, &((struct sockaddr_in6 *) ctx->info->ai_addr)->sin6_addr, ctx->buffer, length); #endif lwp_snprintf (ctx->buffer + strlen (ctx->buffer), sizeof (ctx->buffer) - strlen (ctx->buffer) - 1, ":%d", ntohs (((struct sockaddr_in6 *) ctx->info->ai_addr)->sin6_port)); break; } }; return ctx->buffer ? ctx->buffer: ""; }
const char* net_address_to_string(int af, const void* src, char* dst, socklen_t cnt) { #ifdef WINSOCK struct sockaddr_in sin4; struct sockaddr_in6 sin6; struct in_addr* addr4 = (struct in_addr*) src; struct in6_addr* addr6 = (struct in6_addr*) src; size_t size; LPSOCKADDR addr; DWORD len = cnt; switch (af) { case AF_INET: sin4.sin_family = AF_INET; sin4.sin_port = 0; sin4.sin_addr = *addr4; size = sizeof(sin4); addr = (LPSOCKADDR) &sin4; break; case AF_INET6: sin6.sin6_family = AF_INET6; sin6.sin6_port = 0; sin6.sin6_addr = *addr6; sin6.sin6_scope_id = 0; size = sizeof(sin6); addr = (LPSOCKADDR) &sin6; break; default: return NULL; } if (WSAAddressToStringA(addr, size, NULL, dst, &len) == 0) { return dst; } return NULL; #else if (inet_ntop(af, src, dst, cnt)) { if (af == AF_INET6 && strncmp(dst, "::ffff:", 7) == 0) /* IPv6 mapped IPv4 address. */ { memmove(dst, dst + 7, cnt - 7); } return dst; } return NULL; #endif }
/** * liefert einen string der übergebenen Ip. * * @author OLiver * @author FloSoft */ std::string Socket::IpToString(const sockaddr* addr) { static char temp[256]; #ifdef _WIN32 size_t size = 0; if (addr->sa_family == AF_INET) size = sizeof(sockaddr_in); else size = sizeof(sockaddr_in6); assert(size != 0); sockaddr* copy = (sockaddr*)calloc(1, size); memcpy(copy, addr, size); if (addr->sa_family == AF_INET) ((sockaddr_in*)copy)->sin_port = 0; else ((sockaddr_in6*)copy)->sin6_port = 0; DWORD le = GetLastError(); DWORD templen = sizeof(temp); WSAAddressToStringA(copy, size, NULL, temp, &templen); SetLastError(le); free(copy); #else void* ip; if (addr->sa_family == AF_INET) { ip = &(((sockaddr_in*)addr)->sin_addr); } else { ip = &(((sockaddr_in6*)addr)->sin6_addr); } inet_ntop(addr->sa_family, ip, temp, sizeof(temp)); #endif std::string buffer = temp; int pos = buffer.find("::ffff:"); if(pos != -1) buffer.replace(pos, 7, ""); return buffer; }
const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) { union { struct sockaddr sa; struct sockaddr_in sai; struct sockaddr_in6 sai6; } addr; int res; memset(&addr, 0, sizeof(addr)); addr.sa.sa_family = af; if (af == AF_INET6) { memcpy(&addr.sai6.sin6_addr, src, sizeof(addr.sai6.sin6_addr)); } else { memcpy(&addr.sai.sin_addr, src, sizeof(addr.sai.sin_addr)); } res = WSAAddressToStringA(&addr.sa, sizeof(addr), 0, dst, (LPDWORD) &size); if (res != 0) return NULL; return dst; }
const char *custom_inet_ntop(int af, const void *src, char *dst, int cnt) { struct sockaddr_in srcaddr; memset(&srcaddr, 0, sizeof(struct sockaddr_in)); memcpy(&(srcaddr.sin_addr), src, sizeof(srcaddr.sin_addr)); srcaddr.sin_family = af; if (WSAAddressToStringA((struct sockaddr *) &srcaddr, sizeof(struct sockaddr_in), 0, dst, (LPDWORD) &cnt) != 0) { wxLogInfo(wxT("SSH error: WSAAddressToStringA failed with error code %d"), WSAGetLastError()); return NULL; } return dst; }
char* NetlibAddressToString(SOCKADDR_INET_M* addr) { char saddr[128]; DWORD len = sizeof(saddr); if (!WSAAddressToStringA((PSOCKADDR)addr, sizeof(*addr), NULL, saddr, &len)) return mir_strdup(saddr); if (addr->si_family == AF_INET) { char *szIp = inet_ntoa(addr->Ipv4.sin_addr); if (addr->Ipv4.sin_port != 0) { mir_snprintf(saddr, "%s:%d", szIp, htons(addr->Ipv4.sin_port)); return mir_strdup(saddr); } return mir_strdup(szIp); } return NULL; }
char *inet_ntop( int af, const void *src, char *dst, size_t size ) { void *pSrc_sockaddr; struct sockaddr_in src_sockaddr; struct sockaddr_in6 src6_sockaddr; DWORD src_size; DWORD temp; int result; DWORD error; switch( af ) { case AF_INET: src_sockaddr.sin_family = AF_INET; src_sockaddr.sin_port = 0; memcpy( &src_sockaddr.sin_addr, src, sizeof( struct in_addr ) ); pSrc_sockaddr = &src_sockaddr; src_size = sizeof( struct sockaddr_in ); break; case AF_INET6: src6_sockaddr.sin6_family = AF_INET6; src6_sockaddr.sin6_port = 0; src6_sockaddr.sin6_flowinfo = 0; src6_sockaddr.sin6_scope_id = 0; memcpy( &src6_sockaddr.sin6_addr, src, sizeof( struct in6_addr ) ); pSrc_sockaddr = &src6_sockaddr; src_size = sizeof( struct sockaddr_in6 ); break; default: return NULL; } temp = size; result = WSAAddressToStringA( (LPSOCKADDR)pSrc_sockaddr, src_size, NULL, dst, &temp ); error = GetLastError(); if (result == 0) // Success return dst; else // Failure return NULL; }
static BOOL start_listening_on_all_addresses(messageStorage *msgStorage, ULONG family) { IP_ADAPTER_ADDRESSES *adapterAddresses = NULL, *adapterAddress; ULONG bufferSize = 0; LPSOCKADDR sockaddr; DWORD addressLength; char address[64]; BOOL ret = FALSE; ULONG retVal; retVal = GetAdaptersAddresses(family, 0, NULL, NULL, &bufferSize); /* family should be AF_INET or AF_INET6 */ if (retVal != ERROR_BUFFER_OVERFLOW) goto cleanup; /* Get size of buffer for adapters */ adapterAddresses = (IP_ADAPTER_ADDRESSES *)heap_alloc(bufferSize); if (adapterAddresses == NULL) goto cleanup; /* Get list of adapters */ retVal = GetAdaptersAddresses(family, 0, NULL, adapterAddresses, &bufferSize); if (retVal != ERROR_SUCCESS) goto cleanup; for (adapterAddress = adapterAddresses; adapterAddress != NULL; adapterAddress = adapterAddress->Next) { if (msgStorage->numThreadHandles >= MAX_LISTENING_THREADS) { ret = TRUE; goto cleanup; } if (adapterAddress->FirstUnicastAddress == NULL) continue; sockaddr = adapterAddress->FirstUnicastAddress->Address.lpSockaddr; addressLength = sizeof(address); WSAAddressToStringA(sockaddr, adapterAddress->FirstUnicastAddress->Address.iSockaddrLength, NULL, address, &addressLength); start_listening(msgStorage, adapterAddress->FirstUnicastAddress->Address.lpSockaddr->sa_family == AF_INET ? SEND_ADDRESS_IPV4 : SEND_ADDRESS_IPV6, address); } ret = TRUE; cleanup: heap_free(adapterAddresses); return ret; }
static const char* inet_ntopA(int af, const void *cp, char *buf, socklen_t len) { DWORD Dlen = len, AFlen = 0; SOCKADDR_STORAGE any; LPSOCKADDR anyp = (LPSOCKADDR)&any; LPSOCKADDR_IN any4 = (LPSOCKADDR_IN)&any; LPSOCKADDR_IN6 any6 = (LPSOCKADDR_IN6)&any; if (!buf) { WSASetLastError(STATUS_INVALID_PARAMETER); return NULL; } if (af != AF_INET && af != AF_INET6) { WSASetLastError(WSAEAFNOSUPPORT); return NULL; } ZeroMemory(&any, sizeof(SOCKADDR_STORAGE)); any.ss_family = af; switch (af) { case AF_INET: { CopyMemory(&any4->sin_addr, cp, sizeof(IN_ADDR)); AFlen = sizeof(SOCKADDR_IN); break; } case AF_INET6: { CopyMemory(&any6->sin6_addr, cp, sizeof(IN6_ADDR)); AFlen = sizeof(SOCKADDR_IN6); break; } } if (WSAAddressToStringA(anyp, AFlen, NULL, buf, &Dlen) == SOCKET_ERROR) return NULL; return buf; }
const char *zbx_inet_ntop(int af, const void *src, char *dst, size_t size) { struct sockaddr_storage ss; unsigned long s = size; memset(&ss, '\0', sizeof(ss)); ss.ss_family = af; switch(af) { case AF_INET: ((struct sockaddr_in *)&ss)->sin_addr = *(struct in_addr *)src; break; case AF_INET6: ((struct sockaddr_in6 *)&ss)->sin6_addr = *(struct in6_addr *)src; break; default: return NULL; } return (0 == WSAAddressToStringA((struct sockaddr *)&ss, sizeof(ss), NULL, dst, &s))? dst : NULL; }
const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt) { /* WSAAddressToString takes a full sockaddr, while inet_ntop only takes the address */ struct sockaddr_in sock4; struct sockaddr_in6 sock6; DWORD addrLen = cnt; int err = 0; /* src is either an in_addr or an in6_addr. */ const struct in_addr *src4 = (const struct in_addr*) src; const struct in6_addr *src6 = (const struct in6_addr*) src; int ipv6 = af == AF_INET6; /* DebugBreak(); */ if ( ipv6 ) { sock6.sin6_family = AF_INET6; sock6.sin6_port = 0; sock6.sin6_addr = *src6; } else { sock4.sin_family = AF_INET; sock4.sin_port = 0; sock4.sin_addr = *src4; } err = WSAAddressToStringA( ipv6 ? (LPSOCKADDR) &sock6 : (LPSOCKADDR) &sock4, ipv6 ? sizeof(sock6) : sizeof(sock4), NULL, dst, &addrLen ); return err == 0 ? dst : NULL; }
std::string get_domain_ip(const std::string& domain) { AUTO_LOG_FUNCTION; struct addrinfo *result = nullptr; struct addrinfo *ptr = nullptr; struct addrinfo hints; struct sockaddr_in *sockaddr_ipv4; // struct sockaddr_in6 *sockaddr_ipv6; LPSOCKADDR sockaddr_ip; char ipstringbuffer[46]; DWORD ipbufferlength = 46; //-------------------------------- // Setup the hints address info structure // which is passed to the getaddrinfo() function ZeroMemory(&hints, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; std::string ip; do { //-------------------------------- // Call getaddrinfo(). If the call succeeds, // the result variable will hold a linked list // of addrinfo structures containing response // information DWORD dwRetval = getaddrinfo(domain.c_str(), "0", &hints, &result); if (dwRetval != 0) { JLOGA("getaddrinfo failed with error: %d\n", dwRetval); break; } JLOGA("getaddrinfo returned success\n"); // Retrieve each address and print out the hex bytes int i = 0; int iRetval = 0; bool ok = false; for (ptr = result; ptr != nullptr; ptr = ptr->ai_next) { JLOGA("getaddrinfo response %d\n", i++); JLOGA("\tFlags: 0x%x\n", ptr->ai_flags); JLOGA("\tFamily: "); switch (ptr->ai_family) { case AF_UNSPEC: JLOGA("Unspecified\n"); break; case AF_INET: JLOGA("AF_INET (IPv4)\n"); sockaddr_ipv4 = (struct sockaddr_in *) ptr->ai_addr; ip = inet_ntoa(sockaddr_ipv4->sin_addr); JLOGA("\tIPv4 address %s\n", ip.c_str()); ok = true; break; case AF_INET6: JLOGA("AF_INET6 (IPv6)\n"); // the InetNtop function is available on Windows Vista and later // sockaddr_ipv6 = (struct sockaddr_in6 *) ptr->ai_addr; // printf("\tIPv6 address %s\n", // InetNtop(AF_INET6, &sockaddr_ipv6->sin6_addr, ipstringbuffer, 46) ); // We use WSAAddressToString since it is supported on Windows XP and later sockaddr_ip = (LPSOCKADDR)ptr->ai_addr; // The buffer length is changed by each call to WSAAddresstoString // So we need to set it for each iteration through the loop for safety ipbufferlength = 46; iRetval = WSAAddressToStringA(sockaddr_ip, (DWORD)ptr->ai_addrlen, nullptr, ipstringbuffer, &ipbufferlength); if (iRetval) JLOGA("WSAAddressToString failed with %u\n", WSAGetLastError()); else JLOGA("\tIPv6 address %s\n", ipstringbuffer); break; case AF_NETBIOS: JLOGA("AF_NETBIOS (NetBIOS)\n"); break; default: JLOGA("Other %ld\n", ptr->ai_family); break; } JLOGA("\tSocket type: "); switch (ptr->ai_socktype) { case 0: JLOGA("Unspecified\n"); break; case SOCK_STREAM: JLOGA("SOCK_STREAM (stream)\n"); break; case SOCK_DGRAM: JLOGA("SOCK_DGRAM (datagram) \n"); break; case SOCK_RAW: JLOGA("SOCK_RAW (raw) \n"); break; case SOCK_RDM: JLOGA("SOCK_RDM (reliable message datagram)\n"); break; case SOCK_SEQPACKET: JLOGA("SOCK_SEQPACKET (pseudo-stream packet)\n"); break; default: JLOGA("Other %ld\n", ptr->ai_socktype); break; } JLOGA("\tProtocol: "); switch (ptr->ai_protocol) { case 0: JLOGA("Unspecified\n"); break; case IPPROTO_TCP: JLOGA("IPPROTO_TCP (TCP)\n"); break; case IPPROTO_UDP: JLOGA("IPPROTO_UDP (UDP) \n"); break; default: JLOGA("Other %ld\n", ptr->ai_protocol); break; } JLOGA("\tLength of this sockaddr: %d\n", ptr->ai_addrlen); JLOGA("\tCanonical name: %s\n", ptr->ai_canonname); if (ok) { break; } } freeaddrinfo(result); if (ok) { return ip; } } while (false); return ""; }
/* * Returns: [interfaces (table)] */ static int sock_getifaddrs (lua_State *L) { struct sock_addr *sap; int i, res; #ifndef _WIN32 struct ifaddrs *result, *rp; sys_vm_leave(L); res = getifaddrs(&result); sys_vm_enter(L); #else INTERFACE_INFO result[8192], *rp; SOCKET sd = WSASocketW(AF_INET, SOCK_STREAM, 0, NULL, 0, WSA_FLAGS); DWORD n; sys_vm_leave(L); res = WSAIoctl(sd, SIO_GET_INTERFACE_LIST, NULL, 0, result, sizeof(result), &n, NULL, NULL); closesocket(sd); sys_vm_enter(L); #endif if (res == -1) return sys_seterror(L, 0); lua_createtable(L, 8, 0); rp = result; #ifndef _WIN32 for (i = 0; rp; rp = rp->ifa_next) { #else for (i = 0; n--; ++rp) { #endif #ifndef _WIN32 sap = (struct sock_addr *) rp->ifa_addr; #else sap = (struct sock_addr *) &rp->iiAddress; #endif if (!sap || sap->u.addr.sa_family == AF_UNSPEC) continue; lua_newtable(L); { const int af = sap->u.addr.sa_family; if (af == AF_INET #ifdef AF_INET6 || af == AF_INET6 #endif ) { sock_pushaddr(L, sap); lua_setfield(L, -2, "addr"); } { const char *s = NULL; switch (af) { case AF_INET: s = "INET"; break; #ifdef AF_INET6 case AF_INET6: s = "INET6"; break; #endif #ifdef AF_LOCAL case AF_LOCAL: s = "LOCAL"; break; #endif #ifdef AF_AX25 case AF_AX25: s = "AX25"; break; #endif #ifdef AF_IPX case AF_IPX: s = "IPX"; break; #endif #ifdef AF_APPLETALK case AF_APPLETALK: s = "APPLETALK"; break; #endif #ifdef AF_NETROM case AF_NETROM: s = "NETROM"; break; #endif #ifdef AF_BRIDGE case AF_BRIDGE: s = "BRIDGE"; break; #endif #ifdef AF_ATMPVC case AF_ATMPVC: s = "ATMPVC"; break; #endif #ifdef AF_X25 case AF_X25: s = "X25"; break; #endif #ifdef AF_ROSE case AF_ROSE: s = "ROSE"; break; #endif #ifdef AF_DECnet case AF_DECnet: s = "DECnet"; break; #endif #ifdef AF_NETBEUI case AF_NETBEUI: s = "NETBEUI"; break; #endif #ifdef AF_SECURITY case AF_SECURITY: s = "SECURITY"; break; #endif #ifdef AF_KEY case AF_KEY: s = "KEY"; break; #endif #ifdef AF_NETLINK case AF_NETLINK: s = "NETLINK"; break; #endif #ifdef AF_PACKET case AF_PACKET: s = "PACKET"; break; #endif #ifdef AF_ASH case AF_ASH: s = "ASH"; break; #endif #ifdef AF_ECONET case AF_ECONET: s = "ECONET"; break; #endif #ifdef AF_ATMSVC case AF_ATMSVC: s = "ATMSVC"; break; #endif #ifdef AF_RDS case AF_RDS: s = "RDS"; break; #endif #ifdef AF_SNA case AF_SNA: s = "SNA"; break; #endif #ifdef AF_IRDA case AF_IRDA: s = "IRDA"; break; #endif #ifdef AF_PPPOX case AF_PPPOX: s = "PPPOX"; break; #endif #ifdef AF_WANPIPE case AF_WANPIPE: s = "WANPIPE"; break; #endif #ifdef AF_LLC case AF_LLC: s = "LLC"; break; #endif #ifdef AF_CAN case AF_CAN: s = "CAN"; break; #endif #ifdef AF_TIPC case AF_TIPC: s = "TIPC"; break; #endif #ifdef AF_BLUETOOTH case AF_BLUETOOTH: s = "BLUETOOTH"; break; #endif #ifdef AF_IUCV case AF_IUCV: s = "IUCV"; break; #endif #ifdef AF_RXRPC case AF_RXRPC: s = "RXRPC"; break; #endif #ifdef AF_ISDN case AF_ISDN: s = "ISDN"; break; #endif #ifdef AF_PHONET case AF_PHONET: s = "PHONET"; break; #endif #ifdef AF_IEEE802154 case AF_IEEE802154: s = "IEEE802154"; break; #endif default: s = "UNKNOWN"; } if (s) { lua_pushstring(L, s); lua_setfield(L, -2, "family"); } } #ifndef _WIN32 sap = (struct sock_addr *) rp->ifa_netmask; #else sap = (struct sock_addr *) &rp->iiNetmask; #endif if (sap) { sock_pushaddr(L, sap); lua_setfield(L, -2, "netmask"); } #ifndef _WIN32 sap = (struct sock_addr *) rp->ifa_broadaddr; #else sap = (struct sock_addr *) &rp->iiBroadcastAddress; #endif if (sap) { sock_pushaddr(L, sap); lua_setfield(L, -2, "broadaddr"); } lua_createtable(L, 0, 5); { #ifndef _WIN32 const int flags = rp->ifa_flags; #else const int flags = rp->iiFlags; #endif lua_pushboolean(L, flags & IFF_UP); lua_setfield(L, -2, "up"); lua_pushboolean(L, flags & IFF_BROADCAST); lua_setfield(L, -2, "broadcast"); lua_pushboolean(L, flags & IFF_LOOPBACK); lua_setfield(L, -2, "loopback"); lua_pushboolean(L, flags & IFF_POINTOPOINT); lua_setfield(L, -2, "pointtopoint"); lua_pushboolean(L, flags & IFF_MULTICAST); lua_setfield(L, -2, "multicast"); } lua_setfield(L, -2, "flags"); } lua_rawseti(L, -2, ++i); } #ifndef _WIN32 freeifaddrs(result); #endif return 1; } /* * Arguments: text_address (string), [ip4_tonumber (true)] * Returns: [binary_address (string | number)] */ static int sock_inet_pton (lua_State *L) { const char *src = luaL_checkstring(L, 1); const int to_ip4 = lua_toboolean(L, 2); const int af = (!to_ip4 && strchr(src, ':')) ? AF_INET6 : AF_INET; struct sock_addr sa; void *inp = sock_addr_get_inp(&sa, af); const int in_len = sock_addr_get_inlen(af); #ifdef _WIN32 union sys_rwptr src_ptr; /* to avoid "const cast" warning */ #endif memset(&sa, 0, sizeof(struct sock_addr)); if (*src == '*') goto end; #ifndef _WIN32 if (inet_pton(af, src, inp) == 1) { #else sa.addrlen = sizeof(sa); src_ptr.r = src; if (!WSAStringToAddressA(src_ptr.w, af, NULL, &sa.u.addr, &sa.addrlen)) { #endif end: if (to_ip4) lua_pushnumber(L, ntohl(*((unsigned long *) inp))); else lua_pushlstring(L, inp, in_len); return 1; } return sys_seterror(L, 0); } /* * Arguments: binary_address (string | number) * Returns: [text_address (string)] */ static int sock_inet_ntop (lua_State *L) { const int is_ip4 = (lua_type(L, 1) == LUA_TNUMBER); unsigned long ip4; int in_len, af; const char *src; char buf[48]; if (is_ip4) { const lua_Number num = lua_tonumber(L, 1); in_len = 4; af = AF_INET; ip4 = htonl((unsigned long) num); src = (const char *) &ip4; } else { src = sock_checkladdr(L, 1, &in_len, &af); } #ifndef _WIN32 if (inet_ntop(af, src, buf, sizeof(buf)) == NULL) goto err; #else { struct sock_addr sa; void *inp = sock_addr_get_inp(&sa, af); const int sl = (af == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6); DWORD buflen = sizeof(buf); memset(&sa, 0, sizeof(struct sock_addr)); memcpy(inp, src, in_len); sa.u.addr.sa_family = (short) af; if (WSAAddressToStringA(&sa.u.addr, sl, NULL, buf, &buflen) || buflen >= sizeof(buf)) goto err; } #endif lua_pushstring(L, buf); return 1; err: return sys_seterror(L, 0); } /* * Returns: sock_addr_udata */ static int sock_addr_new (lua_State *L) { lua_newuserdata(L, sizeof(struct sock_addr)); luaL_getmetatable(L, SA_TYPENAME); lua_setmetatable(L, -2); return 1; } /* * Arguments: sock_addr_udata, [port (number), binary_address (string)] * Returns: sock_addr_udata | port (number), binary_address (string) */ static int sock_addr_inet (lua_State *L) { struct sock_addr *sap = checkudata(L, 1, SA_TYPENAME); if (lua_gettop(L) == 1) { const int af = sap->u.addr.sa_family; if (af == AF_INET) { lua_pushinteger(L, ntohs(sap->u.in.sin_port)); lua_pushlstring(L, (char *) &sap->u.in.sin_addr, sizeof(struct in_addr)); } else if (af == AF_INET6) { lua_pushinteger(L, ntohs(sap->u.in6.sin6_port)); lua_pushlstring(L, (char *) &sap->u.in6.sin6_addr, sizeof(struct in6_addr)); } else return 0; return 2; } else { const int port = (int) lua_tointeger(L, 2); int in_len = SOCK_ADDR_LEN, af = AF_INET; const char *addr = lua_isnoneornil(L, 3) ? NULL : sock_checkladdr(L, 3, &in_len, &af); memset(sap, 0, sizeof(struct sock_addr)); sap->u.addr.sa_family = (short) af; if (af == AF_INET) { sap->u.in.sin_port = htons((unsigned short) port); if (addr) memcpy(&sap->u.in.sin_addr, addr, in_len); sap->addrlen = sizeof(struct sockaddr_in); } else { sap->u.in6.sin6_port = htons((unsigned short) port); if (addr) memcpy(&sap->u.in6.sin6_addr, addr, in_len); sap->addrlen = sizeof(struct sockaddr_in6); } lua_settop(L, 1); return 1; }; } /* * Arguments: sock_addr_udata, [path (string)] * Returns: sock_addr_udata | path (string) */ static int sock_addr_file (lua_State *L) { struct sock_addr *sap = checkudata(L, 1, SA_TYPENAME); #ifndef _WIN32 if (lua_gettop(L) == 1) { if (sap->u.addr.sa_family == AF_LOCAL) { lua_pushstring(L, sap->u.un.sun_path); return 1; } } else { size_t len; const char *path = luaL_checklstring(L, 2, &len); if (len < sizeof(sap->u.un.sun_path)) { sap->u.un.sun_family = AF_LOCAL; sap->addrlen = ++len; memcpy(sap->u.un.sun_path, path, len); lua_settop(L, 1); return 1; } }; #else (void) sap; #endif return 0; } /* * Arguments: sock_addr_udata, sd_udata * Returns: [sock_addr_udata] */ static int sock_addr_getsockname (lua_State *L) { struct sock_addr *sap = checkudata(L, 1, SA_TYPENAME); sd_t sd = (sd_t) lua_unboxinteger(L, 2, SD_TYPENAME); sap->addrlen = SOCK_ADDR_LEN; if (!getsockname(sd, &sap->u.addr, &sap->addrlen)) { lua_settop(L, 1); return 1; } return sys_seterror(L, 0); } /* * Arguments: sock_addr_udata, sd_udata * Returns: [sock_addr_udata] */ static int sock_addr_getpeername (lua_State *L) { struct sock_addr *sap = checkudata(L, 1, SA_TYPENAME); sd_t sd = (sd_t) lua_unboxinteger(L, 2, SD_TYPENAME); sap->addrlen = SOCK_ADDR_LEN; if (!getpeername(sd, &sap->u.addr, &sap->addrlen)) { lua_settop(L, 1); return 1; } return sys_seterror(L, 0); } /* * Arguments: sock_addr_udata * Returns: string */ static int sock_addr_tostring (lua_State *L) { struct sock_addr *sap = checkudata(L, 1, SA_TYPENAME); lua_pushfstring(L, SA_TYPENAME " (%p)", sap); return 1; } #define ADDR_METHODS \ {"getaddrinfo", sock_getaddrinfo}, \ {"getnameinfo", sock_getnameinfo}, \ {"getifaddrs", sock_getifaddrs}, \ {"inet_pton", sock_inet_pton}, \ {"inet_ntop", sock_inet_ntop}, \ {"addr", sock_addr_new} static luaL_Reg addr_meth[] = { {"inet", sock_addr_inet}, {"file", sock_addr_file}, {"getsockname", sock_addr_getsockname}, {"getpeername", sock_addr_getpeername}, {"__tostring", sock_addr_tostring}, {NULL, NULL} };
void DNSSD_API CDNSSD::GetAddrInfoReply ( DNSServiceRef sdRef, DNSServiceFlags flags, uint32_t ifIndex, DNSServiceErrorType errorCode, const char *hostNameUTF8, const struct sockaddr *rawAddress, uint32_t ttl, void *context ) { CComObject<CDNSSDService> * service; int err; service = ( CComObject< CDNSSDService>* ) context; require_action( service, exit, err = kDNSServiceErr_Unknown ); if ( !service->Stopped() ) { IGetAddrInfoListener * listener; listener = ( IGetAddrInfoListener* ) service->GetListener(); require_action( listener, exit, err = kDNSServiceErr_Unknown ); if ( !errorCode ) { CComBSTR hostName; DWORD sockaddrLen; DNSSDAddressFamily addressFamily; char addressUTF8[INET6_ADDRSTRLEN]; DWORD addressLen = sizeof( addressUTF8 ); CComBSTR address; BOOL ok; ok = UTF8ToBSTR( hostNameUTF8, hostName ); require_action( ok, exit, err = kDNSServiceErr_Unknown ); switch ( rawAddress->sa_family ) { case AF_INET: { addressFamily = kDNSSDAddressFamily_IPv4; sockaddrLen = sizeof( sockaddr_in ); } break; case AF_INET6: { addressFamily = kDNSSDAddressFamily_IPv6; sockaddrLen = sizeof( sockaddr_in6 ); } break; } err = WSAAddressToStringA( ( LPSOCKADDR ) rawAddress, sockaddrLen, NULL, addressUTF8, &addressLen ); require_noerr( err, exit ); ok = UTF8ToBSTR( addressUTF8, address ); require_action( ok, exit, err = kDNSServiceErr_Unknown ); listener->GetAddrInfoReply( service, ( DNSSDFlags ) flags, ifIndex, hostName, addressFamily, address, ttl ); } else { listener->GetAddrInfoFailed( service, ( DNSSDError ) errorCode ); } } exit: return; }
void __fastcall CaptureFilterRulesInit(std::string &FilterRules) { //Initialization(Part 1) std::vector<PDNS_SERVER_DATA> AddrList; auto RepeatingItem = false; //IPv6 if (Parameter.RequestMode_Network == REQUEST_MODE_NETWORK_BOTH || Parameter.RequestMode_Network == REQUEST_MODE_IPV6 || //IPv6 Parameter.RequestMode_Network == REQUEST_MODE_IPV4 && Parameter.DNSTarget.IPv4.AddressData.Storage.ss_family == 0) //Non-IPv4 { //Main if (Parameter.DNSTarget.IPv6.AddressData.Storage.ss_family > 0) AddrList.push_back(&Parameter.DNSTarget.IPv6); //Alternate if (Parameter.DNSTarget.Alternate_IPv6.AddressData.Storage.ss_family > 0) { //Check repeating items. for (auto DNSServerDataIter:AddrList) { if (DNSServerDataIter->AddressData.Storage.ss_family == Parameter.DNSTarget.Alternate_IPv6.AddressData.Storage.ss_family && memcmp(&DNSServerDataIter->AddressData.IPv6.sin6_addr, &Parameter.DNSTarget.Alternate_IPv6.AddressData.IPv6.sin6_addr, sizeof(in6_addr)) == EXIT_SUCCESS) { RepeatingItem = true; break; } } //Add to address list. if (!RepeatingItem) AddrList.push_back(&Parameter.DNSTarget.Alternate_IPv6); RepeatingItem = false; } //Other(Multi) if (Parameter.DNSTarget.IPv6_Multi != nullptr) { for (auto &DNSServerDataIter:*Parameter.DNSTarget.IPv6_Multi) { //Check repeating items. for (auto DNSServerDataInnerIter:AddrList) { if (DNSServerDataInnerIter->AddressData.Storage.ss_family == DNSServerDataIter.AddressData.Storage.ss_family && memcmp(&DNSServerDataInnerIter->AddressData.IPv6.sin6_addr, &DNSServerDataIter.AddressData.IPv6.sin6_addr, sizeof(in6_addr)) == EXIT_SUCCESS) { RepeatingItem = true; break; } } //Add to address list. if (!RepeatingItem) AddrList.push_back(&DNSServerDataIter); RepeatingItem = false; } } } //IPv4 if (Parameter.RequestMode_Network == REQUEST_MODE_NETWORK_BOTH || Parameter.RequestMode_Network == REQUEST_MODE_IPV4 || //IPv4 Parameter.RequestMode_Network == REQUEST_MODE_IPV6 && Parameter.DNSTarget.IPv6.AddressData.Storage.ss_family == 0) //Non-IPv6 { //Main if (Parameter.DNSTarget.IPv4.AddressData.Storage.ss_family > 0) AddrList.push_back(&Parameter.DNSTarget.IPv4); //Alternate if (Parameter.DNSTarget.Alternate_IPv4.AddressData.Storage.ss_family > 0) { //Check repeating items. for (auto DNSServerDataIter:AddrList) { if (DNSServerDataIter->AddressData.Storage.ss_family == Parameter.DNSTarget.Alternate_IPv4.AddressData.Storage.ss_family && DNSServerDataIter->AddressData.IPv4.sin_addr.s_addr == Parameter.DNSTarget.Alternate_IPv4.AddressData.IPv4.sin_addr.s_addr) { RepeatingItem = true; break; } } //Add to address list. if (!RepeatingItem) AddrList.push_back(&Parameter.DNSTarget.Alternate_IPv4); RepeatingItem = false; } //Other(Multi) if (Parameter.DNSTarget.IPv4_Multi != nullptr) { for (auto &DNSServerDataIter:*Parameter.DNSTarget.IPv4_Multi) { //Check repeating items. for (auto DNSServerDataInnerIter:AddrList) { if (DNSServerDataInnerIter->AddressData.Storage.ss_family == DNSServerDataIter.AddressData.Storage.ss_family && DNSServerDataInnerIter->AddressData.IPv4.sin_addr.s_addr == DNSServerDataIter.AddressData.IPv4.sin_addr.s_addr) { RepeatingItem = true; break; } } //Add to address list. if (!RepeatingItem) AddrList.push_back(&DNSServerDataIter); RepeatingItem = false; } } } //Initialization(Part 2) std::string AddrString; std::shared_ptr<char> Addr(new char[ADDR_STRING_MAXSIZE]()); memset(Addr.get(), 0, ADDR_STRING_MAXSIZE); FilterRules.clear(); FilterRules.append("(src host "); //Minimum supported system of inet_ntop() and inet_pton() is Windows Vista(Windows XP with SP3 support). [Roy Tam] #if (defined(PLATFORM_WIN32) && !defined(PLATFORM_WIN64)) std::shared_ptr<sockaddr_storage> SockAddr(new sockaddr_storage()); memset(SockAddr.get(), 0, sizeof(sockaddr_storage)); DWORD BufferLength = ADDR_STRING_MAXSIZE; #endif //List all target addresses. RepeatingItem = false; for (auto DNSServerDataIter:AddrList) { //IPv6 if (DNSServerDataIter->AddressData.Storage.ss_family == AF_INET6) { if (RepeatingItem) AddrString.append(" or "); RepeatingItem = true; #if (defined(PLATFORM_WIN32) && !defined(PLATFORM_WIN64)) if (Parameter.FunctionPTR_InetNtop != nullptr) { (*Parameter.FunctionPTR_InetNtop)(AF_INET6, &DNSServerDataIter->AddressData.IPv6.sin6_addr, Addr.get(), ADDR_STRING_MAXSIZE); } else { BufferLength = ADDR_STRING_MAXSIZE; SockAddr->ss_family = AF_INET6; ((PSOCKADDR_IN6)SockAddr.get())->sin6_addr = DNSServerDataIter->AddressData.IPv6.sin6_addr; WSAAddressToStringA((PSOCKADDR)SockAddr.get(), sizeof(sockaddr_in6), nullptr, Addr.get(), &BufferLength); } #else inet_ntop(AF_INET6, &DNSServerDataIter->AddressData.IPv6.sin6_addr, Addr.get(), ADDR_STRING_MAXSIZE); #endif AddrString.append(Addr.get()); memset(Addr.get(), 0, ADDR_STRING_MAXSIZE); } //IPv4 else if (DNSServerDataIter->AddressData.Storage.ss_family == AF_INET) { if (RepeatingItem) AddrString.append(" or "); RepeatingItem = true; #if (defined(PLATFORM_WIN32) && !defined(PLATFORM_WIN64)) if (Parameter.FunctionPTR_InetNtop != nullptr) { (*Parameter.FunctionPTR_InetNtop)(AF_INET, &DNSServerDataIter->AddressData.IPv4.sin_addr, Addr.get(), ADDR_STRING_MAXSIZE); } else { BufferLength = ADDR_STRING_MAXSIZE; SockAddr->ss_family = AF_INET; ((PSOCKADDR_IN)SockAddr.get())->sin_addr = DNSServerDataIter->AddressData.IPv4.sin_addr; WSAAddressToStringA((PSOCKADDR)SockAddr.get(), sizeof(sockaddr_in), nullptr, Addr.get(), &BufferLength); } #else inet_ntop(AF_INET, &DNSServerDataIter->AddressData.IPv4.sin_addr, Addr.get(), ADDR_STRING_MAXSIZE); #endif AddrString.append(Addr.get()); memset(Addr.get(), 0, ADDR_STRING_MAXSIZE); } } //End of address list FilterRules.append(AddrString); FilterRules.append(") or (pppoes and src host "); FilterRules.append(AddrString); FilterRules.append(")"); return; }
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; }
BOOL RouteLookup(SOCKADDR *destAddr, int destLen, SOCKADDR *localAddr, int localLen ) { DWORD dwBytes = 0; BOOL bRet = FALSE; CHAR szAddr[MAX_PATH] = {0}; SOCKET s = INVALID_SOCKET; __try { if (INVALID_SOCKET == (s = socket(destAddr->sa_family,SOCK_DGRAM,0))) { ERR("socket"); __leave; } if (SOCKET_ERROR == WSAIoctl(s, SIO_ROUTING_INTERFACE_QUERY, destAddr, destLen, localAddr, localLen, &dwBytes, NULL, NULL )) { ERR("WSAIoctl"); __leave; } dwBytes = sizeof(szAddr); ZeroMemory(szAddr,dwBytes); WSAAddressToStringA(destAddr, (DWORD)destLen, NULL, szAddr, &dwBytes ); dwBytes = sizeof(szAddr); ZeroMemory(szAddr,dwBytes); WSAAddressToStringA(localAddr, (DWORD)localLen, NULL, szAddr, &dwBytes ); bRet = TRUE; } __finally { CLOSESOCK(s); } return bRet; }
bool DNSResolver::Resolve_(const String &sSearchFor, std::vector<String> &vecFoundNames, WORD wType, int iRecursion) { if (iRecursion > 10) { String sMessage = Formatter::Format("Too many recursions during query. Query: {0}, Type: {1}", sSearchFor, wType); ErrorManager::Instance()->ReportError(ErrorManager::Low, 4401, "DNSResolver::Resolve_", sMessage); return false; } PDNS_RECORD pDnsRecord = NULL; PIP4_ARRAY pSrvList = NULL; DWORD fOptions = DNS_QUERY_STANDARD; DNS_STATUS nDnsStatus = DnsQuery(sSearchFor, wType, fOptions, NULL, &pDnsRecord, NULL); PDNS_RECORD pDnsRecordsToDelete = pDnsRecord; if (nDnsStatus != 0) { if (pDnsRecordsToDelete) _FreeDNSRecord(pDnsRecordsToDelete); bool bDNSError = IsDNSError_(nDnsStatus); if (bDNSError) { String sMessage; sMessage.Format(_T("DNS - Query failure. Query: %s, Type: %d, DnsQuery return value: %d."), sSearchFor.c_str(), wType, nDnsStatus); LOG_TCPIP(sMessage); return false; } return true; } std::vector<DnsRecordWithPreference> foundDnsRecordsWithPreference; do { switch (pDnsRecord->wType) { case DNS_TYPE_A: { SOCKADDR_IN addr; memset(&addr, 0, sizeof addr); addr.sin_family = AF_INET; addr.sin_addr = *((in_addr*)&(pDnsRecord->Data.AAAA.Ip6Address)); char buf[128]; DWORD bufSize = sizeof(buf); if (WSAAddressToStringA((sockaddr*)&addr, sizeof addr, NULL, buf, &bufSize) == 0) { DnsRecordWithPreference rec(0, buf); foundDnsRecordsWithPreference.push_back(rec); } break; } case DNS_TYPE_AAAA: { SOCKADDR_IN6 addr; memset(&addr, 0, sizeof addr); addr.sin6_family = AF_INET6; addr.sin6_addr = *((in_addr6*)&(pDnsRecord->Data.AAAA.Ip6Address)); char buf[128]; DWORD bufSize = sizeof(buf); if (WSAAddressToStringA((sockaddr*)&addr, sizeof addr, NULL, buf, &bufSize) == 0) { DnsRecordWithPreference rec(0, buf); foundDnsRecordsWithPreference.push_back(rec); } break; } case DNS_TYPE_CNAME: { String sDomainName = pDnsRecord->Data.CNAME.pNameHost; if (!Resolve_(sDomainName, vecFoundNames, wType, iRecursion+1)) return false; break; } case DNS_TYPE_MX: { String sName = pDnsRecord->pName; bool bNameMatches = (sName.CompareNoCase(sSearchFor) == 0); if (pDnsRecord->Flags.S.Section == DNSREC_ANSWER && bNameMatches) { DnsRecordWithPreference rec(pDnsRecord->Data.MX.wPreference, pDnsRecord->Data.MX.pNameExchange); foundDnsRecordsWithPreference.push_back(rec); } break; } case DNS_TYPE_TEXT: { AnsiString retVal; for (u_int i = 0; i < pDnsRecord->Data.TXT.dwStringCount; i++) retVal += pDnsRecord->Data.TXT.pStringArray[i]; DnsRecordWithPreference rec (0, retVal); foundDnsRecordsWithPreference.push_back(rec); break; } case DNS_TYPE_PTR: { AnsiString retVal; retVal = pDnsRecord->Data.PTR.pNameHost; DnsRecordWithPreference rec(0, retVal); foundDnsRecordsWithPreference.push_back(rec); break; } default: { ErrorManager::Instance()->ReportError(ErrorManager::Medium, 5036, "DNSResolver::Resolve_", Formatter::Format("Queried for {0} but received type {1}", wType, pDnsRecord->wType)); break; } } pDnsRecord = pDnsRecord->pNext; } while (pDnsRecord != nullptr); std::sort(foundDnsRecordsWithPreference.begin(), foundDnsRecordsWithPreference.end(), SortDnsRecordWithPreference); for (DnsRecordWithPreference item : foundDnsRecordsWithPreference) { vecFoundNames.push_back(item.Value); } _FreeDNSRecord(pDnsRecordsToDelete); pDnsRecordsToDelete = 0; return true; }
int main (int argc, char **argv) { int ret; int r = 1; WSADATA wsd; GUID *prov = NULL; GUID *sc = NULL; 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; } 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) { NSP_ROUTINE api; ret = startup (prov, &api); if (NO_ERROR != ret) fprintf (stderr, "startup failed\n"); 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 = sc; 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\n"); } 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) { 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); } } WSACleanup(); return r; }