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