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