String SockAddr::ToString(bool writePort, char portDelineator) const { char dest[INET6_ADDRSTRLEN + 1]; int ret = getnameinfo((struct sockaddr*)&Addr6, sizeof(struct sockaddr_in6), dest, INET6_ADDRSTRLEN, NULL, 0, NI_NUMERICHOST); if (ret != 0) { dest[0] = '\0'; } if (writePort) { unsigned char ch[2]; ch[0]=portDelineator; ch[1]=0; OVR_strcat(dest, 16, (const char*) ch); OVR_itoa(ntohs(Addr6.sin6_port), dest+strlen(dest), 16, 10); } return String(dest); }
static SocketHandle BindShared(int ai_family, int ai_socktype, BerkleyBindParameters *pBindParameters) { SocketHandle sock; struct addrinfo hints; memset(&hints, 0, sizeof (addrinfo)); // make sure the struct is empty hints.ai_family = ai_family; hints.ai_socktype = ai_socktype; hints.ai_flags = AI_PASSIVE; // fill in my IP for me struct addrinfo *servinfo=0, *aip; // will point to the results char portStr[32]; OVR_itoa(pBindParameters->Port, portStr, sizeof(portStr), 10); int errcode = 0; if (!pBindParameters->Address.IsEmpty()) errcode = getaddrinfo(pBindParameters->Address.ToCStr(), portStr, &hints, &servinfo); else errcode = getaddrinfo(0, portStr, &hints, &servinfo); if (0 != errcode) { OVR::LogError("getaddrinfo error: %s", gai_strerror(errcode)); } for (aip = servinfo; aip != NULL; aip = aip->ai_next) { // Open socket. The address type depends on what // getaddrinfo() gave us. sock = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol); if (sock != 0) { SetSocketOptions(sock); int ret = bind( sock, aip->ai_addr, (int) aip->ai_addrlen ); if (ret>=0) { // The actual socket is always non-blocking // I control blocking or not using WSAEventSelect _Ioctlsocket(sock, 1); freeaddrinfo(servinfo); return sock; } else { close(sock); } } } if (servinfo) { freeaddrinfo(servinfo); } return INVALID_SOCKET; }
void SockAddr::Set(const char* hostAddress, UInt16 port, int sockType) { memset(&Addr6, 0, sizeof(Addr6)); struct addrinfo hints; // make sure the struct is empty memset(&hints, 0, sizeof (addrinfo)); hints.ai_socktype = sockType; // SOCK_DGRAM or SOCK_STREAM hints.ai_flags = AI_PASSIVE; // fill in my IP for me hints.ai_family = AF_UNSPEC ; if (SOCK_DGRAM == sockType) { hints.ai_protocol = IPPROTO_UDP; } else if (SOCK_STREAM == sockType) { hints.ai_protocol = IPPROTO_TCP; } struct addrinfo* servinfo = NULL; // will point to the results char portStr[32]; OVR_itoa(port, portStr, sizeof(portStr), 10); int errcode = getaddrinfo(hostAddress, portStr, &hints, &servinfo); if (0 != errcode) { OVR::LogError("getaddrinfo error: %s", gai_strerror(errcode)); } OVR_ASSERT(servinfo); if (servinfo) { memcpy(&Addr6, servinfo->ai_addr, sizeof(Addr6)); freeaddrinfo(servinfo); } }