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