]> Creatis software - gdcm.git/blob - src/gdcmUtil.cxx
* src/gdcmUtil.cxx : compilation fix on Win32
[gdcm.git] / src / gdcmUtil.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmUtil.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/01/28 09:37:29 $
7   Version:   $Revision: 1.126 $
8                                                                                 
9   Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10   l'Image). All rights reserved. See Doc/License.txt or
11   http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
12                                                                                 
13      This software is distributed WITHOUT ANY WARRANTY; without even
14      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15      PURPOSE.  See the above copyright notices for more information.
16                                                                                 
17 =========================================================================*/
18
19 #include "gdcmUtil.h"
20 #include "gdcmDebug.h"
21 #include <iostream>
22 #include <algorithm>
23
24 // For GetCurrentDate, GetCurrentTime
25 #include <time.h>
26 #include <sys/types.h>
27 #include <sys/stat.h>
28
29 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
30 #include <sys/timeb.h>
31 #else
32 #include <sys/time.h>
33 #endif
34
35 #include <stdarg.h>  //only included in implementation file
36 #include <stdio.h>   //only included in implementation file
37
38 #if defined(_MSC_VER) || defined(__MINGW32__)
39    #include <winsock.h>  // for gethostname & gethostbyname
40    #undef GetCurrentTime
41 #else
42 #ifndef __BORLANDC__
43    #include <unistd.h>  // for gethostname
44    #include <netdb.h>   // for gethostbyname
45 #endif
46 #endif
47
48 // For GetMACAddress
49 #ifdef _WIN32
50    #include <snmp.h>
51    #include <conio.h>
52 #else
53    #include <unistd.h>
54    #include <stdlib.h>
55    #include <string.h>
56    #include <sys/types.h>
57 #endif
58
59 #ifdef CMAKE_HAVE_SYS_IOCTL_H
60    #include <sys/ioctl.h>  // For SIOCGIFCONF on Linux
61 #endif
62 #ifdef CMAKE_HAVE_SYS_SOCKET_H
63    #include <sys/socket.h>
64 #endif
65 #ifdef CMAKE_HAVE_SYS_SOCKIO_H
66    #include <sys/sockio.h>  // For SIOCGIFCONF on SunOS
67 #endif
68 #ifdef CMAKE_HAVE_NET_IF_H
69    #include <net/if.h>
70 #endif
71 #ifdef CMAKE_HAVE_NETINET_IN_H
72    #include <netinet/in.h>   //For IPPROTO_IP
73 #endif
74 #ifdef CMAKE_HAVE_NET_IF_DL_H
75    #include <net/if_dl.h>
76 #endif
77 #if defined(CMAKE_HAVE_NET_IF_ARP_H) && defined(__sun)
78    // This is absolutely necessary on SunOS
79    #include <net/if_arp.h>
80 #endif
81
82 // For GetCurrentThreadID()
83 #ifdef __linux__
84 #include <sys/types.h>
85 #include <linux/unistd.h>
86 #endif
87 #ifdef __sun
88 #include <thread.h>
89 #endif
90
91 namespace gdcm 
92 {
93 const std::string Util::GDCM_UID = "1.2.826.0.1.3680043.2.1143";
94 std::string Util::RootUID        = GDCM_UID;
95
96 /**
97  * \brief Provide a better 'c++' approach for sprintf
98  * For example c code is:
99  * sprintf(trash, "%04x|%04x", group , elem);
100  *
101  * c++ code is 
102  * std::ostringstream buf;
103  * buf << std::right << std::setw(4) << std::setfill('0') << std::hex
104  *     << group << "|" << std::right << std::setw(4) << std::setfill('0') 
105  *     << std::hex <<  elem;
106  * buf.str();
107  *
108  * gdcm style code is
109  * Format("%04x|%04x", group , elem);
110  */
111
112 std::string Util::Format(const char *format, ...)
113 {
114    char buffer[2048];
115    va_list args;
116    va_start(args, format);
117    vsprintf(buffer, format, args);  //might be a security flaw
118    va_end(args); // Each invocation of va_start should be matched 
119                  // by a corresponding invocation of va_end
120                  // args is then 'undefined'
121    return buffer;
122 }
123
124
125 /**
126  * \brief Because not available in C++ (?)
127  */
128 void Util::Tokenize (const std::string &str,
129                      std::vector<std::string> &tokens,
130                      const std::string& delimiters)
131 {
132    std::string::size_type lastPos = str.find_first_not_of(delimiters,0);
133    std::string::size_type pos     = str.find_first_of    (delimiters,lastPos);
134    while (std::string::npos != pos || std::string::npos != lastPos)
135    {
136       tokens.push_back(str.substr(lastPos, pos - lastPos));
137       lastPos = str.find_first_not_of(delimiters, pos);
138       pos     = str.find_first_of    (delimiters, lastPos);
139    }
140 }
141
142 /**
143  * \brief Because not available in C++ (?)
144  *        Counts the number of occurences of a substring within a string
145  */
146  
147 int Util::CountSubstring (const std::string &str,
148                           const std::string &subStr)
149 {
150    int count = 0;   // counts how many times it appears
151    std::string::size_type x = 0;       // The index position in the string
152
153    do
154    {
155       x = str.find(subStr,x);       // Find the substring
156       if (x != std::string::npos)   // If present
157       {
158          count++;                  // increase the count
159          x += subStr.length();     // Skip this word
160       }
161    }
162    while (x != std::string::npos);  // Carry on until not present
163
164    return count;
165 }
166
167 /**
168  * \brief  Weed out a string from the non-printable characters (in order
169  *         to avoid corrupting the terminal of invocation when printing)
170  * @param s string to remove non printable characters from
171  */
172 std::string Util::CreateCleanString(std::string const &s)
173 {
174    std::string str = s;
175
176    for(unsigned int i=0; i<str.size(); i++)
177    {
178       if(!isprint((unsigned char)str[i]))
179       {
180          str[i] = '.';
181       }
182    }
183
184    if(str.size() > 0)
185    {
186       if(!isprint((unsigned char)s[str.size()-1]))
187       {
188          if(s[str.size()-1] == 0)
189          {
190             str[str.size()-1] = ' ';
191          }
192       }
193    }
194
195    return str;
196 }
197
198 /**
199  * \brief   Add a SEPARATOR to the end of the name is necessary
200  * @param   pathname file/directory name to normalize 
201  */
202 std::string Util::NormalizePath(std::string const &pathname)
203 {
204    const char SEPARATOR_X      = '/';
205    const char SEPARATOR_WIN    = '\\';
206    const std::string SEPARATOR = "/";
207    std::string name = pathname;
208    int size = name.size();
209
210    if( name[size-1] != SEPARATOR_X && name[size-1] != SEPARATOR_WIN )
211    {
212       name += SEPARATOR;
213    }
214    return name;
215 }
216
217 /**
218  * \brief   Get the (directory) path from a full path file name
219  * @param   fullName file/directory name to extract Path from
220  */
221 std::string Util::GetPath(std::string const &fullName)
222 {
223    std::string res = fullName;
224    int pos1 = res.rfind("/");
225    int pos2 = res.rfind("\\");
226    if( pos1 > pos2)
227    {
228       res.resize(pos1);
229    }
230    else
231    {
232       res.resize(pos2);
233    }
234
235    return res;
236 }
237
238 /**
239  * \brief   Get the (last) name of a full path file name
240  * @param   fullName file/directory name to extract end name from
241  */
242 std::string Util::GetName(std::string const &fullName)
243 {   
244   std::string filename = fullName;
245
246   std::string::size_type slash_pos = filename.rfind("/");
247   std::string::size_type backslash_pos = filename.rfind("\\");
248   slash_pos = slash_pos > backslash_pos ? slash_pos : backslash_pos;
249   if(slash_pos != std::string::npos)
250     {
251     return filename.substr(slash_pos + 1);
252     }
253   else
254     {
255     return filename;
256     }
257
258
259 /**
260  * \brief   Get the current date of the system in a dicom string
261  */
262 std::string Util::GetCurrentDate()
263 {
264     char tmp[512];
265     time_t tloc;
266     time (&tloc);    
267     strftime(tmp,512,"%Y%m%d", localtime(&tloc) );
268     return tmp;
269 }
270
271 /**
272  * \brief   Get the current time of the system in a dicom string
273  */
274 std::string Util::GetCurrentTime()
275 {
276     char tmp[512];
277     time_t tloc;
278     time (&tloc);
279     strftime(tmp,512,"%H%M%S", localtime(&tloc) );
280     return tmp;  
281 }
282
283 /**
284  * \brief  Get both the date and time at the same time to avoid problem 
285  * around midnight where two call could be before and after midnight
286  */
287 std::string Util::GetCurrentDateTime()
288 {
289    char tmp[40];
290    long milliseconds;
291    time_t timep;
292   
293    // We need implementation specific functions to obtain millisecond precision
294 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
295    struct timeb tb;
296    ::ftime(&tb);
297    timep = tb.time;
298    milliseconds = tb.millitm;
299 #else
300    struct timeval tv;
301    gettimeofday (&tv, NULL);
302    timep = tv.tv_sec;
303    // Compute milliseconds from microseconds.
304    milliseconds = tv.tv_usec / 1000;
305 #endif
306    // Obtain the time of day, and convert it to a tm struct.
307    struct tm *ptm = localtime (&timep);
308    // Format the date and time, down to a single second.
309    strftime (tmp, sizeof (tmp), "%Y%m%d%H%M%S", ptm);
310
311    // Add milliseconds
312    std::string r = tmp;
313    r += Format("%03ld", milliseconds);
314
315    return r;
316 }
317
318 /**
319  * \brief Create a /DICOM/ string:
320  * It should a of even length (no odd length ever)
321  * It can contain as many (if you are reading this from your
322  * editor the following character is is backslash followed by zero
323  * that needed to be escaped with an extra backslash for doxygen) \\0
324  * as you want.
325  */
326 std::string Util::DicomString(const char *s, size_t l)
327 {
328    std::string r(s, s+l);
329    gdcmAssertMacro( !(r.size() % 2) ); // == basically 'l' is even
330    return r;
331 }
332
333 /**
334  * \brief Create a /DICOM/ string:
335  * It should a of even length (no odd length ever)
336  * It can contain as many (if you are reading this from your
337  * editor the following character is is backslash followed by zero
338  * that needed to be escaped with an extra backslash for doxygen) \\0
339  * as you want.
340  * This function is similar to DicomString(const char*), 
341  * except it doesn't take a length. 
342  * It only pad with a null character if length is odd
343  */
344 std::string Util::DicomString(const char *s)
345 {
346    size_t l = strlen(s);
347    if( l%2 )
348    {
349       l++;
350    }
351    std::string r(s, s+l);
352    gdcmAssertMacro( !(r.size() % 2) );
353    return r;
354 }
355
356 /**
357  * \brief Safely compare two Dicom String:
358  *        - Both string should be of even length
359  *        - We allow padding of even length string by either a null 
360  *          character of a space
361  */
362 bool Util::DicomStringEqual(const std::string &s1, const char *s2)
363 {
364   // s2 is the string from the DICOM reference: 'MONOCHROME1'
365   std::string s1_even = s1; //Never change input parameter
366   std::string s2_even = DicomString( s2 );
367   if( s1_even[s1_even.size()-1] == ' ')
368   {
369     s1_even[s1_even.size()-1] = '\0'; //replace space character by null
370   }
371   return s1_even == s2_even;
372 }
373
374 /**
375  * \brief   tells us if the processor we are working with is BigEndian or not
376  */
377 bool Util::IsCurrentProcessorBigEndian()
378 {
379 #ifdef GDCM_WORDS_BIGENDIAN
380    return true;
381 #else
382    return false;
383 #endif
384 }
385
386
387
388 #ifdef _WIN32
389 typedef BOOL(WINAPI * pSnmpExtensionInit) (
390         IN DWORD dwTimeZeroReference,
391         OUT HANDLE * hPollForTrapEvent,
392         OUT AsnObjectIdentifier * supportedView);
393
394 typedef BOOL(WINAPI * pSnmpExtensionTrap) (
395         OUT AsnObjectIdentifier * enterprise,
396         OUT AsnInteger * genericTrap,
397         OUT AsnInteger * specificTrap,
398         OUT AsnTimeticks * timeStamp,
399         OUT RFC1157VarBindList * variableBindings);
400
401 typedef BOOL(WINAPI * pSnmpExtensionQuery) (
402         IN BYTE requestType,
403         IN OUT RFC1157VarBindList * variableBindings,
404         OUT AsnInteger * errorStatus,
405         OUT AsnInteger * errorIndex);
406
407 typedef BOOL(WINAPI * pSnmpExtensionInitEx) (
408         OUT AsnObjectIdentifier * supportedView);
409 #endif //_WIN32
410
411
412 int GetMacAddrSys ( unsigned char *addr )
413 {
414 #ifdef _WIN32
415    WSADATA WinsockData;
416    if (WSAStartup(MAKEWORD(2, 0), &WinsockData) != 0) 
417    {
418       std::cerr << "This program requires Winsock 2.x!" << std::endl;
419       return -1;
420    }
421
422    HANDLE PollForTrapEvent;
423    AsnObjectIdentifier SupportedView;
424    UINT OID_ifEntryType[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 3 };
425    UINT OID_ifEntryNum[] = { 1, 3, 6, 1, 2, 1, 2, 1 };
426    UINT OID_ipMACEntAddr[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 6 };
427    AsnObjectIdentifier MIB_ifMACEntAddr = {
428        sizeof(OID_ipMACEntAddr) / sizeof(UINT), OID_ipMACEntAddr };
429    AsnObjectIdentifier MIB_ifEntryType = {
430        sizeof(OID_ifEntryType) / sizeof(UINT), OID_ifEntryType };
431    AsnObjectIdentifier MIB_ifEntryNum = {
432        sizeof(OID_ifEntryNum) / sizeof(UINT), OID_ifEntryNum };
433    RFC1157VarBindList varBindList;
434    RFC1157VarBind varBind[2];
435    AsnInteger errorStatus;
436    AsnInteger errorIndex;
437    AsnObjectIdentifier MIB_NULL = { 0, 0 };
438    int ret;
439    int dtmp;
440    int j = 0;
441
442    // Load the SNMP dll and get the addresses of the functions necessary
443    HINSTANCE m_hInst = LoadLibrary("inetmib1.dll");
444    if (m_hInst < (HINSTANCE) HINSTANCE_ERROR)
445    {
446       return -1;
447    }
448    pSnmpExtensionInit m_Init =
449        (pSnmpExtensionInit) GetProcAddress(m_hInst, "SnmpExtensionInit");
450    pSnmpExtensionQuery m_Query =
451        (pSnmpExtensionQuery) GetProcAddress(m_hInst, "SnmpExtensionQuery");
452    m_Init(GetTickCount(), &PollForTrapEvent, &SupportedView);
453
454    /* Initialize the variable list to be retrieved by m_Query */
455    varBindList.list = varBind;
456    varBind[0].name = MIB_NULL;
457    varBind[1].name = MIB_NULL;
458
459    // Copy in the OID to find the number of entries in the
460    // Inteface table
461    varBindList.len = 1;        // Only retrieving one item
462    SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryNum);
463    m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
464                  &errorIndex);
465 //   printf("# of adapters in this system : %i\n",
466 //          varBind[0].value.asnValue.number);
467    varBindList.len = 2;
468
469    // Copy in the OID of ifType, the type of interface
470    SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryType);
471
472    // Copy in the OID of ifPhysAddress, the address
473    SNMP_oidcpy(&varBind[1].name, &MIB_ifMACEntAddr);
474
475    do
476    {
477       // Submit the query.  Responses will be loaded into varBindList.
478       // We can expect this call to succeed a # of times corresponding
479       // to the # of adapters reported to be in the system
480       ret = m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
481                     &errorIndex); 
482       if (!ret)
483       {
484          ret = 1;
485       }
486       else
487       {
488          // Confirm that the proper type has been returned
489          ret = SNMP_oidncmp(&varBind[0].name, &MIB_ifEntryType,
490                             MIB_ifEntryType.idLength);
491       }
492       if (!ret)
493       {
494          j++;
495          dtmp = varBind[0].value.asnValue.number;
496
497          // Type 6 describes ethernet interfaces
498          if (dtmp == 6)
499          {
500             // Confirm that we have an address here
501             ret = SNMP_oidncmp(&varBind[1].name, &MIB_ifMACEntAddr,
502                                MIB_ifMACEntAddr.idLength);
503             if ( !ret && varBind[1].value.asnValue.address.stream != NULL )
504             {
505                if ( (varBind[1].value.asnValue.address.stream[0] == 0x44)
506                  && (varBind[1].value.asnValue.address.stream[1] == 0x45)
507                  && (varBind[1].value.asnValue.address.stream[2] == 0x53)
508                  && (varBind[1].value.asnValue.address.stream[3] == 0x54)
509                  && (varBind[1].value.asnValue.address.stream[4] == 0x00) )
510                {
511                    // Ignore all dial-up networking adapters
512                    std::cerr << "Interface #" << j << " is a DUN adapter\n";
513                    continue;
514                }
515                if ( (varBind[1].value.asnValue.address.stream[0] == 0x00)
516                  && (varBind[1].value.asnValue.address.stream[1] == 0x00)
517                  && (varBind[1].value.asnValue.address.stream[2] == 0x00)
518                  && (varBind[1].value.asnValue.address.stream[3] == 0x00)
519                  && (varBind[1].value.asnValue.address.stream[4] == 0x00)
520                  && (varBind[1].value.asnValue.address.stream[5] == 0x00) )
521                {
522                   // Ignore NULL addresses returned by other network
523                   // interfaces
524                   std::cerr << "Interface #" << j << " is a NULL address\n";
525                   continue;
526                }
527                memcpy( addr, varBind[1].value.asnValue.address.stream, 6);
528             }
529          }
530       }
531    } while (!ret);
532
533    // Free the bindings
534    SNMP_FreeVarBind(&varBind[0]);
535    SNMP_FreeVarBind(&varBind[1]);
536    return 0;
537 #endif //Win32 version
538
539
540 // implementation for POSIX system
541 #ifdef __sun
542    //The POSIX version is broken anyway on Solaris, plus would require full
543    //root power
544    struct  arpreq          parpreq;
545    struct  sockaddr_in     *psa;
546    struct  hostent         *phost;
547    char                    hostname[MAXHOSTNAMELEN];
548    char                    **paddrs;
549    int                     sock, status=0;
550
551    if(gethostname(hostname,  MAXHOSTNAMELEN) != 0)
552    {
553       perror("gethostname");
554       return -1;
555    }
556    phost = gethostbyname(hostname);
557    paddrs = phost->h_addr_list;
558
559    sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
560    if(sock == -1)
561    {
562       perror("sock");
563       return -1;
564    }
565    memset(&parpreq, 0, sizeof(struct arpreq));
566    psa = (struct sockaddr_in *) &parpreq.arp_pa;
567
568    memset(psa, 0, sizeof(struct sockaddr_in));
569    psa->sin_family = AF_INET;
570    memcpy(&psa->sin_addr, *paddrs, sizeof(struct in_addr));
571
572    status = ioctl(sock, SIOCGARP, &parpreq);
573    if(status == -1)
574    {
575       perror("SIOCGARP");
576       return -1;
577    }
578    memcpy(addr, parpreq.arp_ha.sa_data, 6);
579
580    return 0;
581 #else
582 #ifdef CMAKE_HAVE_NET_IF_H
583    int       sd;
584    struct ifreq    ifr, *ifrp;
585    struct ifconf    ifc;
586    char buf[1024];
587    int      n, i;
588    unsigned char    *a;
589 #if defined(AF_LINK) && (!defined(SIOCGIFHWADDR) && !defined(SIOCGENADDR))
590    struct sockaddr_dl *sdlp;
591 #endif
592
593 //
594 // BSD 4.4 defines the size of an ifreq to be
595 // max(sizeof(ifreq), sizeof(ifreq.ifr_name)+ifreq.ifr_addr.sa_len
596 // However, under earlier systems, sa_len isn't present, so the size is 
597 // just sizeof(struct ifreq)
598 // We should investiage the use of SIZEOF_ADDR_IFREQ
599 //
600 #ifdef HAVE_SA_LEN
601 #ifndef max
602 #define max(a,b) ((a) > (b) ? (a) : (b))
603 #endif
604 #define ifreq_size(i) max(sizeof(struct ifreq),\
605      sizeof((i).ifr_name)+(i).ifr_addr.sa_len)
606 #else
607 #define ifreq_size(i) sizeof(struct ifreq)
608 #endif // HAVE_SA_LEN
609
610    if( (sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) < 0 )
611    {
612       return -1;
613    }
614    memset(buf, 0, sizeof(buf));
615    ifc.ifc_len = sizeof(buf);
616    ifc.ifc_buf = buf;
617    if (ioctl (sd, SIOCGIFCONF, (char *)&ifc) < 0)
618    {
619       close(sd);
620       return -1;
621    }
622    n = ifc.ifc_len;
623    for (i = 0; i < n; i+= ifreq_size(*ifrp) )
624    {
625       ifrp = (struct ifreq *)((char *) ifc.ifc_buf+i);
626       strncpy(ifr.ifr_name, ifrp->ifr_name, IFNAMSIZ);
627 #ifdef SIOCGIFHWADDR
628       if (ioctl(sd, SIOCGIFHWADDR, &ifr) < 0)
629          continue;
630       a = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
631 #else
632 #ifdef SIOCGENADDR
633       // In theory this call should also work on Sun Solaris, but apparently
634       // SIOCGENADDR is not implemented properly thus the call 
635       // ioctl(sd, SIOCGENADDR, &ifr) always returns errno=2 
636       // (No such file or directory)
637       // Furthermore the DLAPI seems to require full root access
638       if (ioctl(sd, SIOCGENADDR, &ifr) < 0)
639          continue;
640       a = (unsigned char *) ifr.ifr_enaddr;
641 #else
642 #ifdef AF_LINK
643       sdlp = (struct sockaddr_dl *) &ifrp->ifr_addr;
644       if ((sdlp->sdl_family != AF_LINK) || (sdlp->sdl_alen != 6))
645          continue;
646       a = (unsigned char *) &sdlp->sdl_data[sdlp->sdl_nlen];
647 #else
648       perror("No way to access hardware");
649       close(sd);
650       return -1;
651 #endif // AF_LINK
652 #endif // SIOCGENADDR
653 #endif // SIOCGIFHWADDR
654       if (!a[0] && !a[1] && !a[2] && !a[3] && !a[4] && !a[5]) continue;
655
656       if (addr) 
657       {
658          memcpy(addr, a, 6);
659          close(sd);
660          return 0;
661       }
662    }
663    close(sd);
664 #endif
665    // Not implemented platforms
666    perror("There was a configuration problem on your plateform");
667    memset(addr,0,6);
668    return -1;
669 #endif //__sun
670 }
671
672 /**
673  * Mini function to return the last digit from a number express in base 256
674  * pre condition data contain an array of 6 unsigned char
675  * post condition carry contain the last digit
676  */
677 inline int getlastdigit(unsigned char *data)
678 {
679   int extended, carry = 0;
680   for(int i=0;i<6;i++)
681     {
682     extended = (carry << 8) + data[i];
683     data[i] = extended / 10;
684     carry = extended % 10;
685     }
686   return carry;
687 }
688
689 /**
690  * \brief Encode the mac address on a fixed lenght string of 15 characters.
691  * we save space this way.
692  */
693 std::string Util::GetMACAddress()
694 {
695    // This code is the result of a long internet search to find something
696    // as compact as possible (not OS independant). We only have to separate
697    // 3 OS: Win32, SunOS and 'real' POSIX
698    // http://groups-beta.google.com/group/comp.unix.solaris/msg/ad36929d783d63be
699    // http://bdn.borland.com/article/0,1410,26040,00.html
700    unsigned char addr[6];
701
702    int stat = GetMacAddrSys(addr);
703    if (stat == 0)
704    {
705       // We need to convert a 6 digit number from base 256 to base 10, using integer
706       // would requires a 48bits one. To avoid this we have to reimplement the div + modulo 
707       // with string only
708       bool zero = false;
709       int res;
710       std::string sres;
711       while(!zero)
712       {
713          res = getlastdigit(addr);
714          sres += ('0' + res);
715          zero = (addr[0] == 0) && (addr[1] == 0) && (addr[2] == 0) && (addr[3] == 0) && (addr[4] == 0) && (addr[5] == 0);
716       }
717       // Since we push back the proper number is reversed:
718       std::reverse(sres.begin(),sres.end());
719
720       return sres;
721    }
722    else
723    {
724       gdcmVerboseMacro("Problem in finding the MAC Address");
725       return "";
726    }
727 }
728
729 /**
730  * \brief   Return the IP adress of the machine writting the DICOM image
731  */
732 std::string Util::GetIPAddress()
733 {
734    // This is a rip from 
735    // http://www.codeguru.com/Cpp/I-N/internet/network/article.php/c3445/
736 #ifndef HOST_NAME_MAX
737    // SUSv2 guarantees that `Host names are limited to 255 bytes'.
738    // POSIX 1003.1-2001 guarantees that `Host names (not including the
739    // terminating NUL) are limited to HOST_NAME_MAX bytes'.
740 #  define HOST_NAME_MAX 255
741    // In this case we should maybe check the string was not truncated.
742    // But I don't known how to check that...
743 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
744    // with WinSock DLL we need to initialize the WinSock before using gethostname
745    WORD wVersionRequested = MAKEWORD(1,0);
746    WSADATA WSAData;
747    int err = WSAStartup(wVersionRequested,&WSAData);
748    if (err != 0)
749    {
750       // Tell the user that we could not find a usable
751       // WinSock DLL.
752       WSACleanup();
753       return "127.0.0.1";
754    }
755 #endif
756   
757 #endif //HOST_NAME_MAX
758
759    std::string str;
760    char szHostName[HOST_NAME_MAX+1];
761    int r = gethostname(szHostName, HOST_NAME_MAX);
762  
763    if( r == 0 )
764    {
765       // Get host adresses
766       struct hostent *pHost = gethostbyname(szHostName);
767  
768       for( int i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
769       {
770          for( int j = 0; j<pHost->h_length; j++ )
771          {
772             if( j > 0 ) str += ".";
773  
774             str += Util::Format("%u", 
775                 (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);
776          }
777          // str now contains one local IP address 
778  
779 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
780    WSACleanup();
781 #endif
782
783       }
784    }
785    // If an error occur r == -1
786    // Most of the time it will return 127.0.0.1...
787    return str;
788 }
789
790 unsigned int Util::GetCurrentThreadID()
791 {
792 // FIXME the implementation is far from complete
793 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
794   return (unsigned int)GetCurrentThreadId();
795 #endif
796 #ifdef __linux__
797    return 0;
798    // Doesn't work on fedora, but is in the man page...
799    //return (unsigned int)gettid();
800 #endif
801 #ifdef __sun
802    return (unsigned int)thr_self();
803 #else
804    //default implementation
805    return 0;
806 #endif
807 }
808
809 unsigned int Util::GetCurrentProcessID()
810 {
811 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
812   // NOTE: There is also a _getpid()...
813   return (unsigned int)GetCurrentProcessId();
814 #else
815   // get process identification, POSIX
816   return (unsigned int)getpid();
817 #endif
818
819 }
820
821 /**
822  * \brief Creates a new UID. As stipulate in the DICOM ref
823  *        each time a DICOM image is create it should have 
824  *        a unique identifier (URI)
825  * @param root is the DICOM prefix assigned by IOS group
826  */
827 std::string Util::CreateUniqueUID(const std::string &root)
828 {
829    std::string prefix;
830    std::string append;
831    if( root.empty() )
832    {
833       // gdcm UID prefix, as supplied by http://www.medicalconnections.co.uk
834       prefix = RootUID; 
835    }
836    else
837    {
838       prefix = root;
839    }
840
841    // A root was specified use it to forge our new UID:
842    append += ".";
843    append += Util::GetMACAddress();
844    append += ".";
845    append += Util::GetCurrentDateTime();
846
847    //Also add a mini random number just in case:
848    int r = (int) (100.0*rand()/RAND_MAX);
849    append += Format("%02d", r);
850
851    // If append is too long we need to rehash it
852    if( (prefix + append).size() > 64 )
853    {
854       gdcmErrorMacro( "Size of UID is too long." );
855       // we need a hash function to truncate this number
856       // if only md5 was cross plateform
857       // MD5(append);
858    }
859
860    return prefix + append;
861 }
862
863 void Util::SetRootUID(const std::string &root)
864 {
865    if( root.empty() )
866       RootUID = GDCM_UID;
867    else
868       RootUID = root;
869 }
870
871 const std::string &Util::GetRootUID()
872 {
873    return RootUID;
874 }
875
876 /**
877  * \brief
878  * @param os ostream to write to
879  * @param val val
880  */ 
881 template <class T>
882 std::ostream &binary_write(std::ostream &os, const T &val)
883 {
884    return os.write(reinterpret_cast<const char*>(&val), sizeof val);
885 }
886
887 /**
888  * \brief binary_write binary_write
889  * @param os ostream to write to 
890  * @param val val
891  */ 
892 std::ostream &binary_write(std::ostream &os, const uint16_t &val)
893 {
894 #ifdef GDCM_WORDS_BIGENDIAN
895    uint16_t swap;
896    swap = ((( val << 8 ) & 0x0ff00 ) | (( val >> 8 ) & 0x00ff ) );
897    return os.write(reinterpret_cast<const char*>(&swap), 2);
898 #else
899    return os.write(reinterpret_cast<const char*>(&val), 2);
900 #endif //GDCM_WORDS_BIGENDIAN
901 }
902
903 /**
904  * \brief binary_write binary_write
905  * @param os ostream to write to
906  * @param val val
907  */ 
908 std::ostream &binary_write(std::ostream &os, const uint32_t &val)
909 {
910 #ifdef GDCM_WORDS_BIGENDIAN
911    uint32_t swap;
912    swap = ( ((val<<24) & 0xff000000) | ((val<<8)  & 0x00ff0000) | 
913             ((val>>8)  & 0x0000ff00) | ((val>>24) & 0x000000ff) );
914    return os.write(reinterpret_cast<const char*>(&swap), 4);
915 #else
916    return os.write(reinterpret_cast<const char*>(&val), 4);
917 #endif //GDCM_WORDS_BIGENDIAN
918 }
919
920 /**
921  * \brief  binary_write binary_write
922  * @param os ostream to write to
923  * @param val val
924  */ 
925 std::ostream &binary_write(std::ostream &os, const char *val)
926 {
927    return os.write(val, strlen(val));
928 }
929
930 /**
931  * \brief
932  * @param os ostream to write to
933  * @param val val
934  */ 
935 std::ostream &binary_write(std::ostream &os, std::string const &val)
936 {
937    return os.write(val.c_str(), val.size());
938 }
939
940 } // end namespace gdcm
941