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