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