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