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