Main Page | Namespace List | Class Hierarchy | Alphabetical List | Class List | File List | Namespace Members | Class Members | File Members | Related Pages

gdcmUtil.cxx

Go to the documentation of this file.
00001 /*=========================================================================
00002                                                                                 
00003   Program:   gdcm
00004   Module:    $RCSfile: gdcmUtil.cxx,v $
00005   Language:  C++
00006   Date:      $Date: 2005/02/05 01:37:09 $
00007   Version:   $Revision: 1.132 $
00008                                                                                 
00009   Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
00010   l'Image). All rights reserved. See Doc/License.txt or
00011   http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
00012                                                                                 
00013      This software is distributed WITHOUT ANY WARRANTY; without even
00014      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
00015      PURPOSE.  See the above copyright notices for more information.
00016                                                                                 
00017 =========================================================================*/
00018 
00019 #include "gdcmUtil.h"
00020 #include "gdcmDebug.h"
00021 #include <iostream>
00022 
00023 // For GetCurrentDate, GetCurrentTime
00024 #include <time.h>
00025 #include <sys/types.h>
00026 #include <sys/stat.h>
00027 
00028 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
00029 #include <sys/timeb.h>
00030 #else
00031 #include <sys/time.h>
00032 #endif
00033 
00034 #include <stdarg.h>  //only included in implementation file
00035 #include <stdio.h>   //only included in implementation file
00036 
00037 #if defined(_MSC_VER) || defined(__MINGW32__)
00038    #include <winsock.h>  // for gethostname and gethostbyname
00039    #undef GetCurrentTime
00040 #else
00041 #ifndef __BORLANDC__
00042    #include <unistd.h>  // for gethostname
00043    #include <netdb.h>   // for gethostbyname
00044 #endif
00045 #endif
00046 
00047 // For GetMACAddress
00048 #ifdef _WIN32
00049    #include <snmp.h>
00050    #include <conio.h>
00051 #else
00052    #include <unistd.h>
00053    #include <stdlib.h>
00054    #include <string.h>
00055    #include <sys/types.h>
00056 #endif
00057 
00058 #ifdef CMAKE_HAVE_SYS_IOCTL_H
00059    #include <sys/ioctl.h>  // For SIOCGIFCONF on Linux
00060 #endif
00061 #ifdef CMAKE_HAVE_SYS_SOCKET_H
00062    #include <sys/socket.h>
00063 #endif
00064 #ifdef CMAKE_HAVE_SYS_SOCKIO_H
00065    #include <sys/sockio.h>  // For SIOCGIFCONF on SunOS
00066 #endif
00067 #ifdef CMAKE_HAVE_NET_IF_H
00068    #include <net/if.h>
00069 #endif
00070 #ifdef CMAKE_HAVE_NETINET_IN_H
00071    #include <netinet/in.h>   //For IPPROTO_IP
00072 #endif
00073 #ifdef CMAKE_HAVE_NET_IF_DL_H
00074    #include <net/if_dl.h>
00075 #endif
00076 #if defined(CMAKE_HAVE_NET_IF_ARP_H) && defined(__sun)
00077    // This is absolutely necessary on SunOS
00078    #include <net/if_arp.h>
00079 #endif
00080 
00081 // For GetCurrentThreadID()
00082 #ifdef __linux__
00083    #include <sys/types.h>
00084    #include <linux/unistd.h>
00085 #endif
00086 #ifdef __sun
00087    #include <thread.h>
00088 #endif
00089 
00090 namespace gdcm 
00091 {
00092 //-------------------------------------------------------------------------
00093 const std::string Util::GDCM_UID = "1.2.826.0.1.3680043.2.1143";
00094 std::string Util::RootUID        = GDCM_UID;
00095 
00096 //-------------------------------------------------------------------------
00097 // Public
00113 std::string Util::Format(const char *format, ...)
00114 {
00115    char buffer[2048];
00116    va_list args;
00117    va_start(args, format);
00118    vsprintf(buffer, format, args);  //might be a security flaw
00119    va_end(args); // Each invocation of va_start should be matched 
00120                  // by a corresponding invocation of va_end
00121                  // args is then 'undefined'
00122    return buffer;
00123 }
00124 
00125 
00129 void Util::Tokenize (const std::string &str,
00130                      std::vector<std::string> &tokens,
00131                      const std::string &delimiters)
00132 {
00133    std::string::size_type lastPos = str.find_first_not_of(delimiters,0);
00134    std::string::size_type pos     = str.find_first_of    (delimiters,lastPos);
00135    while (std::string::npos != pos || std::string::npos != lastPos)
00136    {
00137       tokens.push_back(str.substr(lastPos, pos - lastPos));
00138       lastPos = str.find_first_not_of(delimiters, pos);
00139       pos     = str.find_first_of    (delimiters, lastPos);
00140    }
00141 }
00142 
00148 int Util::CountSubstring (const std::string &str,
00149                           const std::string &subStr)
00150 {
00151    int count = 0;   // counts how many times it appears
00152    std::string::size_type x = 0;       // The index position in the string
00153 
00154    do
00155    {
00156       x = str.find(subStr,x);       // Find the substring
00157       if (x != std::string::npos)   // If present
00158       {
00159          count++;                  // increase the count
00160          x += subStr.length();     // Skip this word
00161       }
00162    }
00163    while (x != std::string::npos);  // Carry on until not present
00164 
00165    return count;
00166 }
00167 
00173 std::string Util::CreateCleanString(std::string const &s)
00174 {
00175    std::string str = s;
00176 
00177    for(unsigned int i=0; i<str.size(); i++)
00178    {
00179       if(!isprint((unsigned char)str[i]))
00180       {
00181          str[i] = '.';
00182       }
00183    }
00184 
00185    if(str.size() > 0)
00186    {
00187       if(!isprint((unsigned char)s[str.size()-1]))
00188       {
00189          if(s[str.size()-1] == 0)
00190          {
00191             str[str.size()-1] = ' ';
00192          }
00193       }
00194    }
00195 
00196    return str;
00197 }
00198 
00203 std::string Util::NormalizePath(std::string const &pathname)
00204 {
00205    const char SEPARATOR_X      = '/';
00206    const char SEPARATOR_WIN    = '\\';
00207    const std::string SEPARATOR = "/";
00208    std::string name = pathname;
00209    int size = name.size();
00210 
00211    if( name[size-1] != SEPARATOR_X && name[size-1] != SEPARATOR_WIN )
00212    {
00213       name += SEPARATOR;
00214    }
00215    return name;
00216 }
00217 
00222 std::string Util::GetPath(std::string const &fullName)
00223 {
00224    std::string res = fullName;
00225    int pos1 = res.rfind("/");
00226    int pos2 = res.rfind("\\");
00227    if( pos1 > pos2)
00228    {
00229       res.resize(pos1);
00230    }
00231    else
00232    {
00233       res.resize(pos2);
00234    }
00235 
00236    return res;
00237 }
00238 
00243 std::string Util::GetName(std::string const &fullName)
00244 {   
00245   std::string filename = fullName;
00246 
00247   std::string::size_type slash_pos = filename.rfind("/");
00248   std::string::size_type backslash_pos = filename.rfind("\\");
00249   slash_pos = slash_pos > backslash_pos ? slash_pos : backslash_pos;
00250   if(slash_pos != std::string::npos)
00251     {
00252     return filename.substr(slash_pos + 1);
00253     }
00254   else
00255     {
00256     return filename;
00257     }
00258 } 
00259 
00263 std::string Util::GetCurrentDate()
00264 {
00265     char tmp[512];
00266     time_t tloc;
00267     time (&tloc);    
00268     strftime(tmp,512,"%Y%m%d", localtime(&tloc) );
00269     return tmp;
00270 }
00271 
00275 std::string Util::GetCurrentTime()
00276 {
00277     char tmp[512];
00278     time_t tloc;
00279     time (&tloc);
00280     strftime(tmp,512,"%H%M%S", localtime(&tloc) );
00281     return tmp;  
00282 }
00283 
00288 std::string Util::GetCurrentDateTime()
00289 {
00290    char tmp[40];
00291    long milliseconds;
00292    time_t timep;
00293   
00294    // We need implementation specific functions to obtain millisecond precision
00295 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
00296    struct timeb tb;
00297    ::ftime(&tb);
00298    timep = tb.time;
00299    milliseconds = tb.millitm;
00300 #else
00301    struct timeval tv;
00302    gettimeofday (&tv, NULL);
00303    timep = tv.tv_sec;
00304    // Compute milliseconds from microseconds.
00305    milliseconds = tv.tv_usec / 1000;
00306 #endif
00307    // Obtain the time of day, and convert it to a tm struct.
00308    struct tm *ptm = localtime (&timep);
00309    // Format the date and time, down to a single second.
00310    strftime (tmp, sizeof (tmp), "%Y%m%d%H%M%S", ptm);
00311 
00312    // Add milliseconds
00313    std::string r = tmp;
00314    r += Format("%03ld", milliseconds);
00315 
00316    return r;
00317 }
00318 
00319 unsigned int Util::GetCurrentThreadID()
00320 {
00321 // FIXME the implementation is far from complete
00322 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
00323   return (unsigned int)GetCurrentThreadId();
00324 #endif
00325 #ifdef __linux__
00326    return 0;
00327    // Doesn't work on fedora, but is in the man page...
00328    //return (unsigned int)gettid();
00329 #endif
00330 #ifdef __sun
00331    return (unsigned int)thr_self();
00332 #else
00333    //default implementation
00334    return 0;
00335 #endif
00336 }
00337 
00338 unsigned int Util::GetCurrentProcessID()
00339 {
00340 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
00341   // NOTE: There is also a _getpid()...
00342   return (unsigned int)GetCurrentProcessId();
00343 #else
00344   // get process identification, POSIX
00345   return (unsigned int)getpid();
00346 #endif
00347 }
00348 
00352 bool Util::IsCurrentProcessorBigEndian()
00353 {
00354 #ifdef GDCM_WORDS_BIGENDIAN
00355    return true;
00356 #else
00357    return false;
00358 #endif
00359 }
00360 
00369 std::string Util::DicomString(const char *s, size_t l)
00370 {
00371    std::string r(s, s+l);
00372    gdcmAssertMacro( !(r.size() % 2) ); // == basically 'l' is even
00373    return r;
00374 }
00375 
00387 std::string Util::DicomString(const char *s)
00388 {
00389    size_t l = strlen(s);
00390    if( l%2 )
00391    {
00392       l++;
00393    }
00394    std::string r(s, s+l);
00395    gdcmAssertMacro( !(r.size() % 2) );
00396    return r;
00397 }
00398 
00405 bool Util::DicomStringEqual(const std::string &s1, const char *s2)
00406 {
00407   // s2 is the string from the DICOM reference: 'MONOCHROME1'
00408   std::string s1_even = s1; //Never change input parameter
00409   std::string s2_even = DicomString( s2 );
00410   if( s1_even[s1_even.size()-1] == ' ')
00411   {
00412     s1_even[s1_even.size()-1] = '\0'; //replace space character by null
00413   }
00414   return s1_even == s2_even;
00415 }
00416 
00417 #ifdef _WIN32
00418    typedef BOOL(WINAPI * pSnmpExtensionInit) (
00419            IN DWORD dwTimeZeroReference,
00420            OUT HANDLE * hPollForTrapEvent,
00421            OUT AsnObjectIdentifier * supportedView);
00422 
00423    typedef BOOL(WINAPI * pSnmpExtensionTrap) (
00424            OUT AsnObjectIdentifier * enterprise,
00425            OUT AsnInteger * genericTrap,
00426            OUT AsnInteger * specificTrap,
00427            OUT AsnTimeticks * timeStamp,
00428            OUT RFC1157VarBindList * variableBindings);
00429 
00430    typedef BOOL(WINAPI * pSnmpExtensionQuery) (
00431            IN BYTE requestType,
00432            IN OUT RFC1157VarBindList * variableBindings,
00433            OUT AsnInteger * errorStatus,
00434            OUT AsnInteger * errorIndex);
00435 
00436    typedef BOOL(WINAPI * pSnmpExtensionInitEx) (
00437            OUT AsnObjectIdentifier * supportedView);
00438 #endif //_WIN32
00439 
00440 
00441 int GetMacAddrSys ( unsigned char *addr )
00442 {
00443 #ifdef _WIN32
00444    WSADATA WinsockData;
00445    if (WSAStartup(MAKEWORD(2, 0), &WinsockData) != 0) 
00446    {
00447       std::cerr << "This program requires Winsock 2.x!" << std::endl;
00448       return -1;
00449    }
00450 
00451    HANDLE PollForTrapEvent;
00452    AsnObjectIdentifier SupportedView;
00453    UINT OID_ifEntryType[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 3 };
00454    UINT OID_ifEntryNum[] = { 1, 3, 6, 1, 2, 1, 2, 1 };
00455    UINT OID_ipMACEntAddr[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 6 };
00456    AsnObjectIdentifier MIB_ifMACEntAddr = {
00457        sizeof(OID_ipMACEntAddr) / sizeof(UINT), OID_ipMACEntAddr };
00458    AsnObjectIdentifier MIB_ifEntryType = {
00459        sizeof(OID_ifEntryType) / sizeof(UINT), OID_ifEntryType };
00460    AsnObjectIdentifier MIB_ifEntryNum = {
00461        sizeof(OID_ifEntryNum) / sizeof(UINT), OID_ifEntryNum };
00462    RFC1157VarBindList varBindList;
00463    RFC1157VarBind varBind[2];
00464    AsnInteger errorStatus;
00465    AsnInteger errorIndex;
00466    AsnObjectIdentifier MIB_NULL = { 0, 0 };
00467    int ret;
00468    int dtmp;
00469    int j = 0;
00470 
00471    // Load the SNMP dll and get the addresses of the functions necessary
00472    HINSTANCE m_hInst = LoadLibrary("inetmib1.dll");
00473    if (m_hInst < (HINSTANCE) HINSTANCE_ERROR)
00474    {
00475       return -1;
00476    }
00477    pSnmpExtensionInit m_Init =
00478        (pSnmpExtensionInit) GetProcAddress(m_hInst, "SnmpExtensionInit");
00479    pSnmpExtensionQuery m_Query =
00480        (pSnmpExtensionQuery) GetProcAddress(m_hInst, "SnmpExtensionQuery");
00481    m_Init(GetTickCount(), &PollForTrapEvent, &SupportedView);
00482 
00483    /* Initialize the variable list to be retrieved by m_Query */
00484    varBindList.list = varBind;
00485    varBind[0].name = MIB_NULL;
00486    varBind[1].name = MIB_NULL;
00487 
00488    // Copy in the OID to find the number of entries in the
00489    // Inteface table
00490    varBindList.len = 1;        // Only retrieving one item
00491    SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryNum);
00492    m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
00493                  &errorIndex);
00494 //   printf("# of adapters in this system : %i\n",
00495 //          varBind[0].value.asnValue.number);
00496    varBindList.len = 2;
00497 
00498    // Copy in the OID of ifType, the type of interface
00499    SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryType);
00500 
00501    // Copy in the OID of ifPhysAddress, the address
00502    SNMP_oidcpy(&varBind[1].name, &MIB_ifMACEntAddr);
00503 
00504    do
00505    {
00506       // Submit the query.  Responses will be loaded into varBindList.
00507       // We can expect this call to succeed a # of times corresponding
00508       // to the # of adapters reported to be in the system
00509       ret = m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
00510                     &errorIndex); 
00511       if (!ret)
00512       {
00513          ret = 1;
00514       }
00515       else
00516       {
00517          // Confirm that the proper type has been returned
00518          ret = SNMP_oidncmp(&varBind[0].name, &MIB_ifEntryType,
00519                             MIB_ifEntryType.idLength);
00520       }
00521       if (!ret)
00522       {
00523          j++;
00524          dtmp = varBind[0].value.asnValue.number;
00525 
00526          // Type 6 describes ethernet interfaces
00527          if (dtmp == 6)
00528          {
00529             // Confirm that we have an address here
00530             ret = SNMP_oidncmp(&varBind[1].name, &MIB_ifMACEntAddr,
00531                                MIB_ifMACEntAddr.idLength);
00532             if ( !ret && varBind[1].value.asnValue.address.stream != NULL )
00533             {
00534                if ( (varBind[1].value.asnValue.address.stream[0] == 0x44)
00535                  && (varBind[1].value.asnValue.address.stream[1] == 0x45)
00536                  && (varBind[1].value.asnValue.address.stream[2] == 0x53)
00537                  && (varBind[1].value.asnValue.address.stream[3] == 0x54)
00538                  && (varBind[1].value.asnValue.address.stream[4] == 0x00) )
00539                {
00540                    // Ignore all dial-up networking adapters
00541                    std::cerr << "Interface #" << j << " is a DUN adapter\n";
00542                    continue;
00543                }
00544                if ( (varBind[1].value.asnValue.address.stream[0] == 0x00)
00545                  && (varBind[1].value.asnValue.address.stream[1] == 0x00)
00546                  && (varBind[1].value.asnValue.address.stream[2] == 0x00)
00547                  && (varBind[1].value.asnValue.address.stream[3] == 0x00)
00548                  && (varBind[1].value.asnValue.address.stream[4] == 0x00)
00549                  && (varBind[1].value.asnValue.address.stream[5] == 0x00) )
00550                {
00551                   // Ignore NULL addresses returned by other network
00552                   // interfaces
00553                   std::cerr << "Interface #" << j << " is a NULL address\n";
00554                   continue;
00555                }
00556                memcpy( addr, varBind[1].value.asnValue.address.stream, 6);
00557             }
00558          }
00559       }
00560    } while (!ret);
00561 
00562    // Free the bindings
00563    SNMP_FreeVarBind(&varBind[0]);
00564    SNMP_FreeVarBind(&varBind[1]);
00565    return 0;
00566 #endif //Win32 version
00567 
00568 
00569 // implementation for POSIX system
00570 #ifdef __sun
00571    //The POSIX version is broken anyway on Solaris, plus would require full
00572    //root power
00573    struct  arpreq          parpreq;
00574    struct  sockaddr_in     *psa;
00575    struct  hostent         *phost;
00576    char                    hostname[MAXHOSTNAMELEN];
00577    char                    **paddrs;
00578    int                     sock, status=0;
00579 
00580    if(gethostname(hostname,  MAXHOSTNAMELEN) != 0)
00581    {
00582       perror("gethostname");
00583       return -1;
00584    }
00585    phost = gethostbyname(hostname);
00586    paddrs = phost->h_addr_list;
00587 
00588    sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
00589    if(sock == -1)
00590    {
00591       perror("sock");
00592       return -1;
00593    }
00594    memset(&parpreq, 0, sizeof(struct arpreq));
00595    psa = (struct sockaddr_in *) &parpreq.arp_pa;
00596 
00597    memset(psa, 0, sizeof(struct sockaddr_in));
00598    psa->sin_family = AF_INET;
00599    memcpy(&psa->sin_addr, *paddrs, sizeof(struct in_addr));
00600 
00601    status = ioctl(sock, SIOCGARP, &parpreq);
00602    if(status == -1)
00603    {
00604       perror("SIOCGARP");
00605       return -1;
00606    }
00607    memcpy(addr, parpreq.arp_ha.sa_data, 6);
00608 
00609    return 0;
00610 #else
00611 #ifdef CMAKE_HAVE_NET_IF_H
00612    int       sd;
00613    struct ifreq    ifr, *ifrp;
00614    struct ifconf    ifc;
00615    char buf[1024];
00616    int      n, i;
00617    unsigned char    *a;
00618 #if defined(AF_LINK) && (!defined(SIOCGIFHWADDR) && !defined(SIOCGENADDR))
00619    struct sockaddr_dl *sdlp;
00620 #endif
00621 
00622 //
00623 // BSD 4.4 defines the size of an ifreq to be
00624 // max(sizeof(ifreq), sizeof(ifreq.ifr_name)+ifreq.ifr_addr.sa_len
00625 // However, under earlier systems, sa_len isn't present, so the size is 
00626 // just sizeof(struct ifreq)
00627 // We should investiage the use of SIZEOF_ADDR_IFREQ
00628 //
00629 #ifdef HAVE_SA_LEN
00630    #ifndef max
00631       #define max(a,b) ((a) > (b) ? (a) : (b))
00632    #endif
00633    #define ifreq_size(i) max(sizeof(struct ifreq),\
00634         sizeof((i).ifr_name)+(i).ifr_addr.sa_len)
00635 #else
00636    #define ifreq_size(i) sizeof(struct ifreq)
00637 #endif // HAVE_SA_LEN
00638 
00639    if( (sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) < 0 )
00640    {
00641       return -1;
00642    }
00643    memset(buf, 0, sizeof(buf));
00644    ifc.ifc_len = sizeof(buf);
00645    ifc.ifc_buf = buf;
00646    if (ioctl (sd, SIOCGIFCONF, (char *)&ifc) < 0)
00647    {
00648       close(sd);
00649       return -1;
00650    }
00651    n = ifc.ifc_len;
00652    for (i = 0; i < n; i+= ifreq_size(*ifrp) )
00653    {
00654       ifrp = (struct ifreq *)((char *) ifc.ifc_buf+i);
00655       strncpy(ifr.ifr_name, ifrp->ifr_name, IFNAMSIZ);
00656 #ifdef SIOCGIFHWADDR
00657       if (ioctl(sd, SIOCGIFHWADDR, &ifr) < 0)
00658          continue;
00659       a = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
00660 #else
00661 #ifdef SIOCGENADDR
00662       // In theory this call should also work on Sun Solaris, but apparently
00663       // SIOCGENADDR is not implemented properly thus the call 
00664       // ioctl(sd, SIOCGENADDR, &ifr) always returns errno=2 
00665       // (No such file or directory)
00666       // Furthermore the DLAPI seems to require full root access
00667       if (ioctl(sd, SIOCGENADDR, &ifr) < 0)
00668          continue;
00669       a = (unsigned char *) ifr.ifr_enaddr;
00670 #else
00671 #ifdef AF_LINK
00672       sdlp = (struct sockaddr_dl *) &ifrp->ifr_addr;
00673       if ((sdlp->sdl_family != AF_LINK) || (sdlp->sdl_alen != 6))
00674          continue;
00675       a = (unsigned char *) &sdlp->sdl_data[sdlp->sdl_nlen];
00676 #else
00677       perror("No way to access hardware");
00678       close(sd);
00679       return -1;
00680 #endif // AF_LINK
00681 #endif // SIOCGENADDR
00682 #endif // SIOCGIFHWADDR
00683       if (!a[0] && !a[1] && !a[2] && !a[3] && !a[4] && !a[5]) continue;
00684 
00685       if (addr) 
00686       {
00687          memcpy(addr, a, 6);
00688          close(sd);
00689          return 0;
00690       }
00691    }
00692    close(sd);
00693 #endif
00694    // Not implemented platforms
00695    perror("There was a configuration problem on your plateform");
00696    memset(addr,0,6);
00697    return -1;
00698 #endif //__sun
00699 }
00700 
00706 inline int getlastdigit(unsigned char *data)
00707 {
00708   int extended, carry = 0;
00709   for(int i=0;i<6;i++)
00710     {
00711     extended = (carry << 8) + data[i];
00712     data[i] = extended / 10;
00713     carry = extended % 10;
00714     }
00715   return carry;
00716 }
00717 
00722 std::string Util::GetMACAddress()
00723 {
00724    // This code is the result of a long internet search to find something
00725    // as compact as possible (not OS independant). We only have to separate
00726    // 3 OS: Win32, SunOS and 'real' POSIX
00727    // http://groups-beta.google.com/group/comp.unix.solaris/msg/ad36929d783d63be
00728    // http://bdn.borland.com/article/0,1410,26040,00.html
00729    unsigned char addr[6];
00730 
00731    int stat = GetMacAddrSys(addr);
00732    if (stat == 0)
00733    {
00734       // We need to convert a 6 digit number from base 256 to base 10, using integer
00735       // would requires a 48bits one. To avoid this we have to reimplement the div + modulo 
00736       // with string only
00737       bool zero = false;
00738       int res;
00739       std::string sres;
00740       while(!zero)
00741       {
00742          res = getlastdigit(addr);
00743          sres.insert(sres.begin(), '0' + res);
00744          zero = (addr[0] == 0) && (addr[1] == 0) && (addr[2] == 0) && (addr[3] == 0) && (addr[4] == 0) && (addr[5] == 0);
00745       }
00746 
00747       return sres;
00748    }
00749    else
00750    {
00751       gdcmWarningMacro("Problem in finding the MAC Address");
00752       return "";
00753    }
00754 }
00755 
00762 std::string Util::CreateUniqueUID(const std::string &root)
00763 {
00764    std::string prefix;
00765    std::string append;
00766    if( root.empty() )
00767    {
00768       // gdcm UID prefix, as supplied by http://www.medicalconnections.co.uk
00769       prefix = RootUID; 
00770    }
00771    else
00772    {
00773       prefix = root;
00774    }
00775 
00776    // A root was specified use it to forge our new UID:
00777    append += ".";
00778    append += Util::GetMACAddress();
00779    append += ".";
00780    append += Util::GetCurrentDateTime();
00781 
00782    //Also add a mini random number just in case:
00783    int r = (int) (100.0*rand()/RAND_MAX);
00784    append += Format("%02d", r);
00785 
00786    // If append is too long we need to rehash it
00787    if( (prefix + append).size() > 64 )
00788    {
00789       gdcmErrorMacro( "Size of UID is too long." );
00790       // we need a hash function to truncate this number
00791       // if only md5 was cross plateform
00792       // MD5(append);
00793    }
00794 
00795    return prefix + append;
00796 }
00797 
00798 void Util::SetRootUID(const std::string &root)
00799 {
00800    if( root.empty() )
00801       RootUID = GDCM_UID;
00802    else
00803       RootUID = root;
00804 }
00805 
00806 const std::string &Util::GetRootUID()
00807 {
00808    return RootUID;
00809 }
00810 
00811 //-------------------------------------------------------------------------
00817 template <class T>
00818 std::ostream &binary_write(std::ostream &os, const T &val)
00819 {
00820    return os.write(reinterpret_cast<const char*>(&val), sizeof val);
00821 }
00822 
00828 std::ostream &binary_write(std::ostream &os, const uint16_t &val)
00829 {
00830 #ifdef GDCM_WORDS_BIGENDIAN
00831    uint16_t swap;
00832    swap = ((( val << 8 ) & 0xff00 ) | (( val >> 8 ) & 0x00ff ) );
00833    return os.write(reinterpret_cast<const char*>(&swap), 2);
00834 #else
00835    return os.write(reinterpret_cast<const char*>(&val), 2);
00836 #endif //GDCM_WORDS_BIGENDIAN
00837 }
00838 
00844 std::ostream &binary_write(std::ostream &os, const uint32_t &val)
00845 {
00846 #ifdef GDCM_WORDS_BIGENDIAN
00847    uint32_t swap;
00848    swap = ( ((val<<24) & 0xff000000) | ((val<<8)  & 0x00ff0000) | 
00849             ((val>>8)  & 0x0000ff00) | ((val>>24) & 0x000000ff) );
00850    return os.write(reinterpret_cast<const char*>(&swap), 4);
00851 #else
00852    return os.write(reinterpret_cast<const char*>(&val), 4);
00853 #endif //GDCM_WORDS_BIGENDIAN
00854 }
00855 
00861 std::ostream &binary_write(std::ostream &os, const char *val)
00862 {
00863    return os.write(val, strlen(val));
00864 }
00865 
00871 std::ostream &binary_write(std::ostream &os, std::string const &val)
00872 {
00873    return os.write(val.c_str(), val.size());
00874 }
00875 
00876 //-------------------------------------------------------------------------
00877 // Protected
00878 
00879 //-------------------------------------------------------------------------
00880 // Private
00884 std::string Util::GetIPAddress()
00885 {
00886    // This is a rip from 
00887    // http://www.codeguru.com/Cpp/I-N/internet/network/article.php/c3445/
00888 #ifndef HOST_NAME_MAX
00889    // SUSv2 guarantees that `Host names are limited to 255 bytes'.
00890    // POSIX 1003.1-2001 guarantees that `Host names (not including the
00891    // terminating NUL) are limited to HOST_NAME_MAX bytes'.
00892 #define HOST_NAME_MAX 255
00893    // In this case we should maybe check the string was not truncated.
00894    // But I don't known how to check that...
00895 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
00896    // with WinSock DLL we need to initialize the WinSock before using gethostname
00897    WORD wVersionRequested = MAKEWORD(1,0);
00898    WSADATA WSAData;
00899    int err = WSAStartup(wVersionRequested,&WSAData);
00900    if (err != 0)
00901    {
00902       // Tell the user that we could not find a usable
00903       // WinSock DLL.
00904       WSACleanup();
00905       return "127.0.0.1";
00906    }
00907 #endif
00908   
00909 #endif //HOST_NAME_MAX
00910 
00911    std::string str;
00912    char szHostName[HOST_NAME_MAX+1];
00913    int r = gethostname(szHostName, HOST_NAME_MAX);
00914  
00915    if( r == 0 )
00916    {
00917       // Get host adresses
00918       struct hostent *pHost = gethostbyname(szHostName);
00919  
00920       for( int i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
00921       {
00922          for( int j = 0; j<pHost->h_length; j++ )
00923          {
00924             if( j > 0 ) str += ".";
00925  
00926             str += Util::Format("%u", 
00927                 (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);
00928          }
00929          // str now contains one local IP address 
00930  
00931 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
00932    WSACleanup();
00933 #endif
00934 
00935       }
00936    }
00937    // If an error occur r == -1
00938    // Most of the time it will return 127.0.0.1...
00939    return str;
00940 }
00941 
00942 //-------------------------------------------------------------------------
00943 } // end namespace gdcm
00944 

Generated on Thu Feb 10 22:18:00 2005 for gdcm by doxygen 1.3.6