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