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