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