]> Creatis software - gdcm.git/blob - src/gdcmUtil.cxx
ENH: Seriously rewrote the GetMacAddress stuff. There is lot less redundancy. I could...
[gdcm.git] / src / gdcmUtil.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmUtil.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/01/15 20:24:02 $
7   Version:   $Revision: 1.92 $
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 #include <stdarg.h>  //only included in implementation file
29 #include <stdio.h>   //only included in implementation file
30
31 #if defined(_MSC_VER)
32    #include <winsock.h>  // for gethostname & gethostbyname
33    #undef GetCurrentTime
34 #else
35 #ifndef __BORLANDC__
36    #include <unistd.h>  // for gethostname
37    #include <netdb.h>   // for gethostbyname
38 #endif
39 #endif
40
41 // For GetMACAddress
42 #ifdef _WIN32
43 #include <snmp.h>
44 #include <conio.h>
45 #else
46 #include <unistd.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <fcntl.h>
50 //#include <errno.h>
51 #include <sys/types.h>
52 #include <sys/time.h>
53 #include <sys/stat.h>
54 #include <sys/file.h>
55 #ifdef CMAKE_HAVE_SYS_IOCTL_H
56 #include <sys/ioctl.h>  // For SIOCGIFCONF on Linux
57 #endif
58 #ifdef CMAKE_HAVE_SYS_SOCKET_H
59 #include <sys/socket.h>
60 #endif
61 #ifdef CMAKE_HAVE_SYS_SOCKIO_H
62 #include <sys/sockio.h>  // For SIOCGIFCONF on SunOS
63 #endif
64 #ifdef CMAKE_HAVE_NET_IF_H
65 #include <net/if.h>
66 #endif
67 #ifdef CMAKE_HAVE_NETINET_IN_H
68 #include <netinet/in.h>   //For IPPROTO_IP
69 #endif
70 #ifdef CMAKE_HAVE_NET_IF_DL_H
71 #include <net/if_dl.h>
72 #endif
73
74 // How do I do that in CMake ?
75 #ifdef __APPLE__
76 #define HAVE_SA_LEN
77 #endif //APPLE
78
79 #endif //_WIN32
80
81 namespace gdcm 
82 {
83 /**
84  * \ingroup Globals
85  * \brief Provide a better 'c++' approach for sprintf
86  * For example c code is:
87  * sprintf(trash, "%04x|%04x", group , elem);
88  *
89  * c++ code is 
90  * std::ostringstream buf;
91  * buf << std::right << std::setw(4) << std::setfill('0') << std::hex
92  *     << group << "|" << std::right << std::setw(4) << std::setfill('0') 
93  *     << std::hex <<  elem;
94  * buf.str();
95  *
96  * gdcm style code is
97  * Format("%04x|%04x", group , elem);
98  */
99
100 std::string Util::Format(const char *format, ...)
101 {
102    char buffer[2048];
103    va_list args;
104    va_start(args, format);
105    vsprintf(buffer, format, args);  //might be a security flaw
106    va_end(args); // Each invocation of va_start should be matched 
107                  // by a corresponding invocation of va_end
108                  // args is then 'undefined'
109    return buffer;
110 }
111
112
113 /**
114  * \ingroup Globals
115  * \brief Because not available in C++ (?)
116  */
117 void Util::Tokenize (const std::string &str,
118                      std::vector<std::string> &tokens,
119                      const std::string& delimiters)
120 {
121    std::string::size_type lastPos = str.find_first_not_of(delimiters,0);
122    std::string::size_type pos     = str.find_first_of    (delimiters,lastPos);
123    while (std::string::npos != pos || std::string::npos != lastPos)
124    {
125       tokens.push_back(str.substr(lastPos, pos - lastPos));
126       lastPos = str.find_first_not_of(delimiters, pos);
127       pos     = str.find_first_of    (delimiters, lastPos);
128    }
129 }
130
131 /**
132  * \ingroup Globals
133  * \brief Because not available in C++ (?)
134  *        Counts the number of occurences of a substring within a string
135  */
136  
137 int Util::CountSubstring (const std::string &str,
138                           const std::string &subStr)
139 {
140    int count = 0;   // counts how many times it appears
141    std::string::size_type x = 0;       // The index position in the string
142
143    do
144    {
145       x = str.find(subStr,x);       // Find the substring
146       if (x != std::string::npos)   // If present
147       {
148          count++;                  // increase the count
149          x += subStr.length();     // Skip this word
150       }
151    }
152    while (x != std::string::npos);  // Carry on until not present
153
154    return count;
155 }
156
157 /**
158  * \ingroup Globals
159  * \brief  Weed out a string from the non-printable characters (in order
160  *         to avoid corrupting the terminal of invocation when printing)
161  * @param s string to remove non printable characters from
162  */
163 std::string Util::CreateCleanString(std::string const &s)
164 {
165    std::string str = s;
166
167    for(unsigned int i=0; i<str.size(); i++)
168    {
169       if(!isprint((unsigned char)str[i]))
170       {
171          str[i] = '.';
172       }
173    }
174
175    if(str.size() > 0)
176    {
177       if(!isprint((unsigned char)s[str.size()-1]))
178       {
179          if(s[str.size()-1] == 0)
180          {
181             str[str.size()-1] = ' ';
182          }
183       }
184    }
185
186    return str;
187 }
188
189 /**
190  * \ingroup Globals
191  * \brief   Add a SEPARATOR to the end of the name is necessary
192  * @param   pathname file/directory name to normalize 
193  */
194 std::string Util::NormalizePath(std::string const &pathname)
195 {
196    const char SEPARATOR_X      = '/';
197    const char SEPARATOR_WIN    = '\\';
198    const std::string SEPARATOR = "/";
199    std::string name = pathname;
200    int size = name.size();
201
202    if( name[size-1] != SEPARATOR_X && name[size-1] != SEPARATOR_WIN )
203    {
204       name += SEPARATOR;
205    }
206    return name;
207 }
208
209 /**
210  * \ingroup Globals
211  * \brief   Get the (directory) path from a full path file name
212  * @param   fullName file/directory name to extract Path from
213  */
214 std::string Util::GetPath(std::string const &fullName)
215 {
216    std::string res = fullName;
217    int pos1 = res.rfind("/");
218    int pos2 = res.rfind("\\");
219    if( pos1 > pos2)
220    {
221       res.resize(pos1);
222    }
223    else
224    {
225       res.resize(pos2);
226    }
227
228    return res;
229 }
230
231 /**
232  * \ingroup Util
233  * \brief   Get the (last) name of a full path file name
234  * @param   fullName file/directory name to extract end name from
235  */
236 std::string Util::GetName(std::string const &fullName)
237 {   
238   std::string filename = fullName;
239
240   std::string::size_type slash_pos = filename.rfind("/");
241   std::string::size_type backslash_pos = filename.rfind("\\");
242   slash_pos = slash_pos > backslash_pos ? slash_pos : backslash_pos;
243   if(slash_pos != std::string::npos)
244     {
245     return filename.substr(slash_pos + 1);
246     }
247   else
248     {
249     return filename;
250     }
251
252
253 /**
254  * \ingroup Util
255  * \brief   Get the current date of the system in a dicom string
256  */
257 std::string Util::GetCurrentDate()
258 {
259     char tmp[512];
260     time_t tloc;
261     time (&tloc);    
262     strftime(tmp,512,"%Y%m%d", localtime(&tloc) );
263     return tmp;
264 }
265
266 /**
267  * \ingroup Util
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 Create a /DICOM/ string:
281  * It should a of even length (no odd length ever)
282  * It can contain as many (if you are reading this from your
283  * editor the following character is is backslash followed by zero
284  * that needed to be escaped with an extra backslash for doxygen) \\0
285  * as you want.
286  */
287 std::string Util::DicomString(const char *s, size_t l)
288 {
289    std::string r(s, s+l);
290    gdcmAssertMacro( !(r.size() % 2) ); // == basically 'l' is even
291    return r;
292 }
293
294 /**
295  * \ingroup Util
296  * \brief Create a /DICOM/ string:
297  * It should a of even lenght (no odd length ever)
298  * It can contain as many (if you are reading this from your
299  * editor the following character is is backslash followed by zero
300  * that needed to be escaped with an extra backslash for doxygen) \\0
301  * as you want.
302  * This function is similar to DicomString(const char*), 
303  * except it doesn't take a lenght. 
304  * It only pad with a null character if length is odd
305  */
306 std::string Util::DicomString(const char *s)
307 {
308    size_t l = strlen(s);
309    if( l%2 )
310    {
311       l++;
312    }
313    std::string r(s, s+l);
314    gdcmAssertMacro( !(r.size() % 2) );
315    return r;
316 }
317
318 /**
319  * \ingroup Util
320  * \brief Safely compare two Dicom String:
321  *        - Both string should be of even lenght
322  *        - We allow padding of even lenght string by either a null 
323  *          character of a space
324  */
325 bool Util::DicomStringEqual(const std::string &s1, const char *s2)
326 {
327   // s2 is the string from the DICOM reference: 'MONOCHROME1'
328   std::string s1_even = s1; //Never change input parameter
329   std::string s2_even = DicomString( s2 );
330   if( s1_even[s1_even.size()-1] == ' ')
331   {
332     s1_even[s1_even.size()-1] = '\0'; //replace space character by null
333   }
334   return s1_even == s2_even;
335 }
336
337
338
339 /**
340  * \ingroup Util
341  * \brief   tells us if the processor we are working with is BigEndian or not
342  */
343 bool Util::IsCurrentProcessorBigEndian()
344 {
345 #ifdef GDCM_WORDS_BIGENDIAN
346    return true;
347 #else
348    return false;
349 #endif
350 }
351
352
353
354 #ifdef _WIN32
355 typedef BOOL(WINAPI * pSnmpExtensionInit) (
356         IN DWORD dwTimeZeroReference,
357         OUT HANDLE * hPollForTrapEvent,
358         OUT AsnObjectIdentifier * supportedView);
359
360 typedef BOOL(WINAPI * pSnmpExtensionTrap) (
361         OUT AsnObjectIdentifier * enterprise,
362         OUT AsnInteger * genericTrap,
363         OUT AsnInteger * specificTrap,
364         OUT AsnTimeticks * timeStamp,
365         OUT RFC1157VarBindList * variableBindings);
366
367 typedef BOOL(WINAPI * pSnmpExtensionQuery) (
368         IN BYTE requestType,
369         IN OUT RFC1157VarBindList * variableBindings,
370         OUT AsnInteger * errorStatus,
371         OUT AsnInteger * errorIndex);
372
373 typedef BOOL(WINAPI * pSnmpExtensionInitEx) (
374         OUT AsnObjectIdentifier * supportedView);
375 #endif //_WIN32
376
377
378 long GetMacAddrSys ( unsigned char *addr)
379 {
380 #ifdef _WIN32
381    WSADATA WinsockData;
382    if (WSAStartup(MAKEWORD(2, 0), &WinsockData) != 0) 
383    {
384       std::cerr << "This program requires Winsock 2.x!" << std::endl;
385       return -1;
386    }
387
388    HANDLE PollForTrapEvent;
389    AsnObjectIdentifier SupportedView;
390    UINT OID_ifEntryType[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 3 };
391    UINT OID_ifEntryNum[] = { 1, 3, 6, 1, 2, 1, 2, 1 };
392    UINT OID_ipMACEntAddr[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 6 };
393    AsnObjectIdentifier MIB_ifMACEntAddr = {
394        sizeof(OID_ipMACEntAddr) / sizeof(UINT), OID_ipMACEntAddr };
395    AsnObjectIdentifier MIB_ifEntryType = {
396        sizeof(OID_ifEntryType) / sizeof(UINT), OID_ifEntryType };
397    AsnObjectIdentifier MIB_ifEntryNum = {
398        sizeof(OID_ifEntryNum) / sizeof(UINT), OID_ifEntryNum };
399    RFC1157VarBindList varBindList;
400    RFC1157VarBind varBind[2];
401    AsnInteger errorStatus;
402    AsnInteger errorIndex;
403    AsnObjectIdentifier MIB_NULL = { 0, 0 };
404    int ret;
405    int dtmp;
406    int i = 0, j = 0;
407    BOOL found = FALSE;
408
409    // Load the SNMP dll and get the addresses of the functions necessary
410    HINSTANCE m_hInst = LoadLibrary("inetmib1.dll");
411    if (m_hInst < (HINSTANCE) HINSTANCE_ERROR)
412    {
413       m_hInst = NULL;
414       return -1;
415    }
416    pSnmpExtensionInit m_Init =
417        (pSnmpExtensionInit) GetProcAddress(m_hInst, "SnmpExtensionInit");
418    pSnmpExtensionInitEx m_InitEx =
419        (pSnmpExtensionInitEx) GetProcAddress(m_hInst, "SnmpExtensionInitEx");
420    pSnmpExtensionQuery m_Query =
421        (pSnmpExtensionQuery) GetProcAddress(m_hInst, "SnmpExtensionQuery");
422    pSnmpExtensionTrap m_Trap =
423        (pSnmpExtensionTrap) GetProcAddress(m_hInst, "SnmpExtensionTrap");
424    m_Init(GetTickCount(), &PollForTrapEvent, &SupportedView);
425
426    /* Initialize the variable list to be retrieved by m_Query */
427    varBindList.list = varBind;
428    varBind[0].name = MIB_NULL;
429    varBind[1].name = MIB_NULL;
430
431    // Copy in the OID to find the number of entries in the
432    // Inteface table
433    varBindList.len = 1;        // Only retrieving one item
434    SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryNum);
435    ret = m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
436                  &errorIndex);
437 //   printf("# of adapters in this system : %i\n",
438 //          varBind[0].value.asnValue.number); varBindList.len = 2;
439
440    // Copy in the OID of ifType, the type of interface
441    SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryType);
442
443    // Copy in the OID of ifPhysAddress, the address
444    SNMP_oidcpy(&varBind[1].name, &MIB_ifMACEntAddr);
445
446    do
447    {
448       // Submit the query.  Responses will be loaded into varBindList.
449       // We can expect this call to succeed a # of times corresponding
450       // to the # of adapters reported to be in the system
451       ret = m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
452                     &errorIndex); 
453       if (!ret)
454       {
455          ret = 1;
456       }
457       else
458       {
459          // Confirm that the proper type has been returned
460          ret = SNMP_oidncmp(&varBind[0].name, &MIB_ifEntryType,
461                             MIB_ifEntryType.idLength);
462       }
463       if (!ret)
464       {
465          j++;
466          dtmp = varBind[0].value.asnValue.number;
467          printf("Interface #%i type : %i\n", j, dtmp);
468
469          // Type 6 describes ethernet interfaces
470          if (dtmp == 6)
471          {
472             // Confirm that we have an address here
473             ret = SNMP_oidncmp(&varBind[1].name, &MIB_ifMACEntAddr,
474                                MIB_ifMACEntAddr.idLength);
475             if ( !ret && varBind[1].value.asnValue.address.stream != NULL )
476             {
477                if ( (varBind[1].value.asnValue.address.stream[0] == 0x44)
478                  && (varBind[1].value.asnValue.address.stream[1] == 0x45)
479                  && (varBind[1].value.asnValue.address.stream[2] == 0x53)
480                  && (varBind[1].value.asnValue.address.stream[3] == 0x54)
481                  && (varBind[1].value.asnValue.address.stream[4] == 0x00) )
482                {
483                    // Ignore all dial-up networking adapters
484                    printf("Interface #%i is a DUN adapter\n", j);
485                    continue;
486                }
487                if ( (varBind[1].value.asnValue.address.stream[0] == 0x00)
488                  && (varBind[1].value.asnValue.address.stream[1] == 0x00)
489                  && (varBind[1].value.asnValue.address.stream[2] == 0x00)
490                  && (varBind[1].value.asnValue.address.stream[3] == 0x00)
491                  && (varBind[1].value.asnValue.address.stream[4] == 0x00)
492                  && (varBind[1].value.asnValue.address.stream[5] == 0x00) )
493                {
494                   // Ignore NULL addresses returned by other network
495                   // interfaces
496                   printf("Interface #%i is a NULL address\n", j);
497                   continue;
498                }
499                memcpy( addr, varBind[1].value.asnValue.address.stream, 6);
500             }
501          }
502       }
503    } while (!ret);
504
505    // Free the bindings
506    SNMP_FreeVarBind(&varBind[0]);
507    SNMP_FreeVarBind(&varBind[1]);
508    return 0;
509 #else
510 // implementation for POSIX system
511 #ifdef CMAKE_HAVE_NET_IF_H
512    int       sd;
513    struct ifreq    ifr, *ifrp;
514    struct ifconf    ifc;
515    char buf[1024];
516    int      n, i;
517    unsigned char    *a;
518 #ifdef AF_LINK
519    struct sockaddr_dl *sdlp;
520 #endif
521
522 //
523 // BSD 4.4 defines the size of an ifreq to be
524 // max(sizeof(ifreq), sizeof(ifreq.ifr_name)+ifreq.ifr_addr.sa_len
525 // However, under earlier systems, sa_len isn't present, so the size is 
526 // just sizeof(struct ifreq)
527 // We should investiage the use of SIZEOF_ADDR_IFREQ
528 //
529 #ifdef HAVE_SA_LEN
530 #ifndef max
531 #define max(a,b) ((a) > (b) ? (a) : (b))
532 #endif
533 #define ifreq_size(i) max(sizeof(struct ifreq),\
534      sizeof((i).ifr_name)+(i).ifr_addr.sa_len)
535 #else
536 #define ifreq_size(i) sizeof(struct ifreq)
537 #endif // HAVE_SA_LEN
538
539    if( (sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) < 0 )
540    {
541       return -1;
542    }
543    memset(buf, 0, sizeof(buf));
544    ifc.ifc_len = sizeof(buf);
545    ifc.ifc_buf = buf;
546    if (ioctl (sd, SIOCGIFCONF, (char *)&ifc) < 0)
547    {
548       close(sd);
549       return -1;
550    }
551    n = ifc.ifc_len;
552    for (i = 0; i < n; i+= ifreq_size(*ifrp) )
553    {
554       ifrp = (struct ifreq *)((char *) ifc.ifc_buf+i);
555       strncpy(ifr.ifr_name, ifrp->ifr_name, IFNAMSIZ);
556 #ifdef SIOCGIFHWADDR
557       if (ioctl(sd, SIOCGIFHWADDR, &ifr) < 0)
558          continue;
559       a = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
560 #else
561 #ifdef SIOCGENADDR
562       if (ioctl(sd, SIOCGENADDR, &ifr) < 0)
563          continue;
564       a = (unsigned char *) ifr.ifr_enaddr;
565 #else
566 #ifdef AF_LINK
567       sdlp = (struct sockaddr_dl *) &ifrp->ifr_addr;
568       if ((sdlp->sdl_family != AF_LINK) || (sdlp->sdl_alen != 6))
569          continue;
570       a = (unsigned char *) &sdlp->sdl_data[sdlp->sdl_nlen];
571 #else
572       /*
573        * XXX we don't have a way of getting the hardware
574        * address
575        */
576       close(sd);
577       return -1;
578 #endif // AF_LINK
579 #endif // SIOCGENADDR
580 #endif // SIOCGIFHWADDR
581       if (!a[0] && !a[1] && !a[2] && !a[3] && !a[4] && !a[5]) continue;
582
583       if (addr) 
584       {
585          memcpy(addr, a, 6);
586          close(sd);
587          return 0;
588       }
589    }
590    close(sd);
591 #endif
592    return -1;
593 #endif //_WIN32
594
595 }
596
597 std::string Util::GetMACAddress()
598 {
599    // This is a rip from: http://cplus.kompf.de/macaddr.html for Linux/CYGWIN, HPUX and AIX 
600    // and http://tangentsoft.net/wskfaq/examples/src/snmpmac.cpp for windows version
601    // and http://groups-beta.google.com/group/sol.lists.freebsd.hackers/msg/0d0f862e05fce6c0 for the FreeBSD version
602    // and http://developer.apple.com/samplecode/GetPrimaryMACAddress/GetPrimaryMACAddress.html for MacOSX version
603    u_char addr[6];
604    std::string macaddr;
605  
606    long stat = GetMacAddrSys(addr);
607    if (0 == stat)
608    {
609       //printf( "MAC address = ");
610       for (int i=0; i<6; ++i) 
611       {
612          //printf("%2.2x", addr[i]);
613          macaddr += Format("%2.2x", addr[i]);
614       }
615        //printf( "\n");
616       return macaddr;
617    }
618    else
619    {
620       //printf( "No MAC address !\n" );
621       return "";
622    }
623 }
624
625 /**
626  * \ingroup Util
627  * \brief   Return the IP adress of the machine writting the DICOM image
628  */
629 std::string Util::GetIPAddress()
630 {
631   // This is a rip from 
632   // http://www.codeguru.com/Cpp/I-N/internet/network/article.php/c3445/
633 #ifndef HOST_NAME_MAX
634   // SUSv2 guarantees that `Host names are limited to 255 bytes'.
635   // POSIX 1003.1-2001 guarantees that `Host names (not including the
636   // terminating NUL) are limited to HOST_NAME_MAX bytes'.
637 #  define HOST_NAME_MAX 255
638   // In this case we should maybe check the string was not truncated.
639   // But I don't known how to check that...
640 #if defined(_MSC_VER) || defined(__BORLANDC__)
641   // with WinSock DLL we need to initialise the WinSock before using gethostname
642   WORD wVersionRequested = MAKEWORD(1,0);
643   WSADATA WSAData;
644   int err = WSAStartup(wVersionRequested,&WSAData);
645   if (err != 0)
646   {
647       // Tell the user that we could not find a usable
648       // WinSock DLL.
649       WSACleanup();
650       return "127.0.0.1";
651   }
652 #endif
653   
654 #endif //HOST_NAME_MAX
655
656   std::string str;
657   char szHostName[HOST_NAME_MAX+1];
658   int r = gethostname(szHostName, HOST_NAME_MAX);
659
660   if( r == 0 )
661   {
662     // Get host adresses
663     struct hostent *pHost = gethostbyname(szHostName);
664
665     for( int i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
666     {
667       for( int j = 0; j<pHost->h_length; j++ )
668       {
669         if( j > 0 ) str += ".";
670
671         str += Util::Format("%u", 
672             (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);
673       }
674       // str now contains one local IP address 
675
676 #if defined(_MSC_VER) || defined(__BORLANDC__)
677   WSACleanup();
678 #endif
679   
680     }
681   }
682   // If an error occur r == -1
683   // Most of the time it will return 127.0.0.1...
684   return str;
685 }
686
687 /**
688  * \ingroup Util
689  * \brief Creates a new UID. As stipulate in the DICOM ref
690  *        each time a DICOM image is create it should have 
691  *        a unique identifier (URI)
692  */
693 std::string Util::CreateUniqueUID(const std::string &root)
694 {
695   // The code works as follow:
696   // echo "gdcm" | od -b
697   // 0000000 147 144 143 155 012
698   // Therefore we return
699   // radical + 147.144.143.155 + IP + time()
700   std::string radical = root;
701   if( !root.size() ) //anything better ?
702   {
703     radical = "0.0."; // Is this really usefull ?
704   }
705   // else
706   // A root was specified use it to forge our new UID:
707   radical += "147.144.143.155"; // gdcm
708   radical += ".";
709   radical += Util::GetIPAddress();
710   radical += ".";
711   radical += Util::GetCurrentDate();
712   radical += ".";
713   radical += Util::GetCurrentTime();
714
715   return radical;
716 }
717
718 template <class T>
719 std::ostream &binary_write(std::ostream &os, const T &val)
720 {
721     return os.write(reinterpret_cast<const char*>(&val), sizeof val);
722 }
723
724 std::ostream &binary_write(std::ostream &os, const uint16_t &val)
725 {
726 #ifdef GDCM_WORDS_BIGENDIAN
727     uint16_t swap;
728     swap = ((( val << 8 ) & 0x0ff00 ) | (( val >> 8 ) & 0x00ff ) );
729     return os.write(reinterpret_cast<const char*>(&swap), 2);
730 #else
731     return os.write(reinterpret_cast<const char*>(&val), 2);
732 #endif //GDCM_WORDS_BIGENDIAN
733 }
734
735 std::ostream &binary_write(std::ostream &os, const uint32_t &val)
736 {
737 #ifdef GDCM_WORDS_BIGENDIAN
738     uint32_t swap;
739     swap = ( ((val<<24) & 0xff000000) | ((val<<8)  & 0x00ff0000) | 
740              ((val>>8)  & 0x0000ff00) | ((val>>24) & 0x000000ff) );
741     return os.write(reinterpret_cast<const char*>(&swap), 4);
742 #else
743     return os.write(reinterpret_cast<const char*>(&val), 4);
744 #endif //GDCM_WORDS_BIGENDIAN
745 }
746
747 std::ostream &binary_write(std::ostream &os, const char *val)
748 {
749     return os.write(val, strlen(val));
750 }
751
752 std::ostream &binary_write(std::ostream &os, std::string const &val)
753 {
754     return os.write(val.c_str(), val.size());
755 }
756
757 } // end namespace gdcm
758