// Networking.cpp //#include #if defined(_WIN32) || defined(_WIN64) #define WIN32_LEAN_AND_MEAN #include #include #elif defined(linux) || defined(__linux) || (defined(__APPLE__) && defined(__MACH__)) #include #include #endif #include #include #include #include "ErrorHandling.hpp" #include "cipres-jni.h" #define MAX_HOSTNAME_LENGTH 255 using namespace CipresJNI; // Java_org_cipres_jni_Networking_getShortHostname jstring JNICALL Java_org_cipres_jni_Networking_getShortHostname(JNIEnv *env, jclass obj) { try { #if defined(_WIN32) || defined(_WIN64) WSADATA lib_data; if(::WSAStartup(MAKEWORD(1, 1), &lib_data) != 0) { ThrowSystemError(env, ::WSAGetLastError()); return NULL; } #endif boost::shared_array hostname(new char[MAX_HOSTNAME_LENGTH + 1]); ::gethostname(hostname.get(), MAX_HOSTNAME_LENGTH); // gethostname only consults local files, but gethostbyname will use // the network for name resolution hostent *host_info = ::gethostbyname(hostname.get()); if(host_info == NULL) { #if defined(_WIN32) || defined(_WIN64) ThrowSystemError(env, ::WSAGetLastError()); #elif defined(linux) || defined(__linux) || (defined(__APPLE__) && defined(__MACH__)) ThrowError(env, JAVA_CLASS_RUNTIME_EXCEPT, ::hstrerror(h_errno)); #endif return NULL; } // the first segment of the host name is used as the short name char *dot_char = std::strchr(host_info->h_name, '.'); if(dot_char != NULL) *dot_char = '\0'; jstring short_name = env->NewStringUTF(host_info->h_name); #if defined(_WIN32) || defined(_WIN64) ::WSACleanup(); #endif return short_name; } catch(const std::bad_alloc &) { ThrowOutOfMemError(env); return NULL; } }