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