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