]> Creatis software - gdcm.git/blob - src/gdcmUtil.cxx
BUG: Solve -hopefully- problem on MacOSX where gdcm seemed to stop working. More...
[gdcm.git] / src / gdcmUtil.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmUtil.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/01/09 00:13:26 $
7   Version:   $Revision: 1.86 $
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 namespace gdcm 
42 {
43 /**
44  * \ingroup Globals
45  * \brief Provide a better 'c++' approach for sprintf
46  * For example c code is:
47  * sprintf(trash, "%04x|%04x", group , element);
48  *
49  * c++ is 
50  * std::ostringstream buf;
51  * buf << std::right << std::setw(4) << std::setfill('0') << std::hex
52  *     << group << "|" << std::right << std::setw(4) << std::setfill('0') 
53  *     << std::hex <<  element;
54  * buf.str();
55  */
56
57 std::string Util::Format(const char *format, ...)
58 {
59    char buffer[2048];
60    va_list args;
61    va_start(args, format);
62    vsprintf(buffer, format, args);  //might be a security flaw
63    va_end(args); // Each invocation of va_start should be matched 
64                  // by a corresponding invocation of va_end
65                  // args is then 'undefined'
66    return buffer;
67 }
68
69
70 /**
71  * \ingroup Globals
72  * \brief Because not available in C++ (?)
73  */
74 void Util::Tokenize (const std::string &str,
75                      std::vector<std::string> &tokens,
76                      const std::string& delimiters)
77 {
78    std::string::size_type lastPos = str.find_first_not_of(delimiters,0);
79    std::string::size_type pos     = str.find_first_of    (delimiters,lastPos);
80    while (std::string::npos != pos || std::string::npos != lastPos)
81    {
82       tokens.push_back(str.substr(lastPos, pos - lastPos));
83       lastPos = str.find_first_not_of(delimiters, pos);
84       pos     = str.find_first_of    (delimiters, lastPos);
85    }
86 }
87
88 /**
89  * \ingroup Globals
90  * \brief Because not available in C++ (?)
91  *        Counts the number of occurences of a substring within a string
92  */
93  
94 int Util::CountSubstring (const std::string &str,
95                           const std::string &subStr)
96 {
97    int count = 0;   // counts how many times it appears
98    std::string::size_type x = 0;       // The index position in the string
99
100    do
101    {
102       x = str.find(subStr,x);       // Find the substring
103       if (x != std::string::npos)   // If present
104       {
105          count++;                  // increase the count
106          x += subStr.length();     // Skip this word
107       }
108    }
109    while (x != std::string::npos);  // Carry on until not present
110
111    return count;
112 }
113
114 /**
115  * \ingroup Globals
116  * \brief  Weed out a string from the non-printable characters (in order
117  *         to avoid corrupting the terminal of invocation when printing)
118  * @param s string to remove non printable characters from
119  */
120 std::string Util::CreateCleanString(std::string const &s)
121 {
122    std::string str = s;
123
124    for(unsigned int i=0; i<str.size(); i++)
125    {
126       if(!isprint((unsigned char)str[i]))
127       {
128          str[i] = '.';
129       }
130    }
131
132    if(str.size() > 0)
133    {
134       if(!isprint((unsigned char)s[str.size()-1]))
135       {
136          if(s[str.size()-1] == 0)
137          {
138             str[str.size()-1] = ' ';
139          }
140       }
141    }
142
143    return str;
144 }
145
146 /**
147  * \ingroup Globals
148  * \brief   Add a SEPARATOR to the end of the name is necessary
149  * @param   pathname file/directory name to normalize 
150  */
151 std::string Util::NormalizePath(std::string const &pathname)
152 {
153    const char SEPARATOR_X      = '/';
154    const char SEPARATOR_WIN    = '\\';
155    const std::string SEPARATOR = "/";
156    std::string name = pathname;
157    int size = name.size();
158
159    if( name[size-1] != SEPARATOR_X && name[size-1] != SEPARATOR_WIN )
160    {
161       name += SEPARATOR;
162    }
163    return name;
164 }
165
166 /**
167  * \ingroup Globals
168  * \brief   Get the (directory) path from a full path file name
169  * @param   fullName file/directory name to extract Path from
170  */
171 std::string Util::GetPath(std::string const &fullName)
172 {
173    std::string res = fullName;
174    int pos1 = res.rfind("/");
175    int pos2 = res.rfind("\\");
176    if( pos1 > pos2)
177    {
178       res.resize(pos1);
179    }
180    else
181    {
182       res.resize(pos2);
183    }
184
185    return res;
186 }
187
188 /**
189  * \ingroup Util
190  * \brief   Get the (last) name of a full path file name
191  * @param   fullName file/directory name to extract end name from
192  */
193 std::string Util::GetName(std::string const &fullName)
194 {   
195   std::string filename = fullName;
196
197   std::string::size_type slash_pos = filename.rfind("/");
198   std::string::size_type backslash_pos = filename.rfind("\\");
199   slash_pos = slash_pos > backslash_pos ? slash_pos : backslash_pos;
200   if(slash_pos != std::string::npos)
201     {
202     return filename.substr(slash_pos + 1);
203     }
204   else
205     {
206     return filename;
207     }
208
209
210 /**
211  * \ingroup Util
212  * \brief   Get the current date of the system in a dicom string
213  */
214 std::string Util::GetCurrentDate()
215 {
216     char tmp[512];
217     time_t tloc;
218     time (&tloc);    
219     strftime(tmp,512,"%Y%m%d", localtime(&tloc) );
220     return tmp;
221 }
222
223 /**
224  * \ingroup Util
225  * \brief   Get the current time of the system in a dicom string
226  */
227 std::string Util::GetCurrentTime()
228 {
229     char tmp[512];
230     time_t tloc;
231     time (&tloc);
232     strftime(tmp,512,"%H%M%S", localtime(&tloc) );
233     return tmp;  
234 }
235
236 /**
237  * \brief Create a /DICOM/ string:
238  * It should a of even length (no odd length ever)
239  * It can contain as many (if you are reading this from your
240  * editor the following character is is backslash followed by zero
241  * that needed to be escaped with an extra backslash for doxygen) \\0
242  * as you want.
243  */
244 std::string Util::DicomString(const char *s, size_t l)
245 {
246    std::string r(s, s+l);
247    gdcmAssertMacro( !(r.size() % 2) ); // == basically 'l' is even
248    return r;
249 }
250
251 /**
252  * \ingroup Util
253  * \brief Create a /DICOM/ string:
254  * It should a of even lenght (no odd length ever)
255  * It can contain as many (if you are reading this from your
256  * editor the following character is is backslash followed by zero
257  * that needed to be escaped with an extra backslash for doxygen) \\0
258  * as you want.
259  * This function is similar to DicomString(const char*), 
260  * except it doesn't take a lenght. 
261  * It only pad with a null character if length is odd
262  */
263 std::string Util::DicomString(const char *s)
264 {
265    size_t l = strlen(s);
266    if( l%2 )
267    {
268       l++;
269    }
270    std::string r(s, s+l);
271    gdcmAssertMacro( !(r.size() % 2) );
272    return r;
273 }
274
275 /**
276  * \ingroup Util
277  * \brief Safely compare two Dicom String:
278  *        - Both string should be of even lenght
279  *        - We allow padding of even lenght string by either a null 
280  *          character of a space
281  */
282 bool Util::DicomStringEqual(const std::string &s1, const char *s2)
283 {
284   // s2 is the string from the DICOM reference: 'MONOCHROME1'
285   std::string s1_even = s1; //Never change input parameter
286   std::string s2_even = DicomString( s2 );
287   if( s1_even[s1_even.size()-1] == ' ')
288   {
289     s1_even[s1_even.size()-1] = '\0'; //replace space character by null
290   }
291   return s1_even == s2_even;
292 }
293
294
295
296 /**
297  * \ingroup Util
298  * \brief   tells us if the processor we are working with is BigEndian or not
299  */
300 bool Util::IsCurrentProcessorBigEndian()
301 {
302    uint16_t intVal = 1;
303    uint8_t bigEndianRepr[4] = { 0x00, 0x00, 0x00, 0x01 };
304    int res = memcmp(reinterpret_cast<const void*>(&intVal),
305                     reinterpret_cast<const void*>(bigEndianRepr), 4);
306    if (res == 0)
307       return true;
308    else
309       return false;
310 }
311
312
313 #include <fcntl.h>
314 #include <stdlib.h>
315 #include <string.h>
316
317 #ifdef _WIN32
318 #include <snmp.h>
319 #include <conio.h>
320 typedef BOOL(WINAPI * pSnmpExtensionInit) (
321         IN DWORD dwTimeZeroReference,
322         OUT HANDLE * hPollForTrapEvent,
323         OUT AsnObjectIdentifier * supportedView);
324
325 typedef BOOL(WINAPI * pSnmpExtensionTrap) (
326         OUT AsnObjectIdentifier * enterprise,
327         OUT AsnInteger * genericTrap,
328         OUT AsnInteger * specificTrap,
329         OUT AsnTimeticks * timeStamp,
330         OUT RFC1157VarBindList * variableBindings);
331
332 typedef BOOL(WINAPI * pSnmpExtensionQuery) (
333         IN BYTE requestType,
334         IN OUT RFC1157VarBindList * variableBindings,
335         OUT AsnInteger * errorStatus,
336         OUT AsnInteger * errorIndex);
337
338 typedef BOOL(WINAPI * pSnmpExtensionInitEx) (
339         OUT AsnObjectIdentifier * supportedView);
340 #else
341 #include <strings.h> //for bzero on unix
342 #endif //_WIN32
343
344 #ifdef __linux__
345 #include <sys/ioctl.h>
346 #include <sys/types.h>
347 #include <sys/socket.h>
348 #include <netinet/in.h>
349 #include <linux/if.h>
350 #endif
351
352 #ifdef __FreeBSD__
353 #include <sys/types.h>
354 #include <sys/socket.h>
355 #include <ifaddrs.h>
356 #include <net/if_dl.h>
357 #endif
358
359 #ifdef __HP_aCC
360 #include <netio.h>
361 #endif
362
363 #ifdef _AIX
364 #include <sys/ndd_var.h>
365 #include <sys/kinfo.h>
366 #endif
367
368 #ifdef __APPLE__
369 #include <CoreFoundation/CoreFoundation.h>
370 #include <IOKit/IOKitLib.h>
371 #include <IOKit/network/IOEthernetInterface.h>
372 #include <IOKit/network/IONetworkInterface.h>
373 #include <IOKit/network/IOEthernetController.h>
374
375 //static kern_return_t FindEthernetInterfaces(io_iterator_t *matchingServices);
376 //static kern_return_t GetMACAddress(io_iterator_t intfIterator, UInt8 *MACAddress);
377
378 // Returns an iterator containing the primary (built-in) Ethernet interface. The caller is responsible for
379 // releasing the iterator after the caller is done with it.
380 static kern_return_t FindEthernetInterfaces(io_iterator_t *matchingServices)
381 {
382     kern_return_t   kernResult; 
383     mach_port_t     masterPort;
384     CFMutableDictionaryRef  matchingDict;
385     CFMutableDictionaryRef  propertyMatchDict;
386     
387     // Retrieve the Mach port used to initiate communication with I/O Kit
388     kernResult = IOMasterPort(MACH_PORT_NULL, &masterPort);
389     if (KERN_SUCCESS != kernResult)
390     {
391         printf("IOMasterPort returned %d\n", kernResult);
392         return kernResult;
393     }
394     
395     // Ethernet interfaces are instances of class kIOEthernetInterfaceClass. 
396     // IOServiceMatching is a convenience function to create a dictionary with the key kIOProviderClassKey and 
397     // the specified value.
398     matchingDict = IOServiceMatching(kIOEthernetInterfaceClass);
399
400     // Note that another option here would be:
401     // matchingDict = IOBSDMatching("en0");
402         
403     if (NULL == matchingDict)
404     {
405         printf("IOServiceMatching returned a NULL dictionary.\n");
406     }
407     else {
408         // Each IONetworkInterface object has a Boolean property with the key kIOPrimaryInterface. Only the
409         // primary (built-in) interface has this property set to TRUE.
410         
411         // IOServiceGetMatchingServices uses the default matching criteria defined by IOService. This considers
412         // only the following properties plus any family-specific matching in this order of precedence 
413         // (see IOService::passiveMatch):
414         //
415         // kIOProviderClassKey (IOServiceMatching)
416         // kIONameMatchKey (IOServiceNameMatching)
417         // kIOPropertyMatchKey
418         // kIOPathMatchKey
419         // kIOMatchedServiceCountKey
420         // family-specific matching
421         // kIOBSDNameKey (IOBSDNameMatching)
422         // kIOLocationMatchKey
423         
424         // The IONetworkingFamily does not define any family-specific matching. This means that in            
425         // order to have IOServiceGetMatchingServices consider the kIOPrimaryInterface property, we must
426         // add that property to a separate dictionary and then add that to our matching dictionary
427         // specifying kIOPropertyMatchKey.
428             
429         propertyMatchDict = CFDictionaryCreateMutable( kCFAllocatorDefault, 0,
430                                                        &kCFTypeDictionaryKeyCallBacks,
431                                                        &kCFTypeDictionaryValueCallBacks);
432     
433         if (NULL == propertyMatchDict)
434         {
435             printf("CFDictionaryCreateMutable returned a NULL dictionary.\n");
436         }
437         else {
438             // Set the value in the dictionary of the property with the given key, or add the key 
439             // to the dictionary if it doesn't exist. This call retains the value object passed in.
440             CFDictionarySetValue(propertyMatchDict, CFSTR(kIOPrimaryInterface), kCFBooleanTrue); 
441             
442             // Now add the dictionary containing the matching value for kIOPrimaryInterface to our main
443             // matching dictionary. This call will retain propertyMatchDict, so we can release our reference 
444             // on propertyMatchDict after adding it to matchingDict.
445             CFDictionarySetValue(matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
446             CFRelease(propertyMatchDict);
447         }
448     }
449     
450     // IOServiceGetMatchingServices retains the returned iterator, so release the iterator when we're done with it.
451     // IOServiceGetMatchingServices also consumes a reference on the matching dictionary so we don't need to release
452     // the dictionary explicitly.
453     kernResult = IOServiceGetMatchingServices(masterPort, matchingDict, matchingServices);    
454     if (KERN_SUCCESS != kernResult)
455     {
456         printf("IOServiceGetMatchingServices returned %d\n", kernResult);
457     }
458         
459     return kernResult;
460 }
461     
462 // Given an iterator across a set of Ethernet interfaces, return the MAC address of the last one.
463 // If no interfaces are found the MAC address is set to an empty string.
464 // In this sample the iterator should contain just the primary interface.
465 static kern_return_t GetMACAddress_MAC(io_iterator_t intfIterator, UInt8 *MACAddress)
466 {
467     io_object_t   intfService;
468     io_object_t   controllerService;
469     kern_return_t kernResult = KERN_FAILURE;
470     
471     // Initialize the returned address
472     bzero(MACAddress, kIOEthernetAddressSize);
473     
474     // IOIteratorNext retains the returned object, so release it when we're done with it.
475     while ( (intfService = IOIteratorNext(intfIterator)))
476     {
477         CFTypeRef MACAddressAsCFData;        
478
479         // IONetworkControllers can't be found directly by the IOServiceGetMatchingServices call, 
480         // since they are hardware nubs and do not participate in driver matching. In other words,
481         // registerService() is never called on them. So we've found the IONetworkInterface and will 
482         // get its parent controller by asking for it specifically.
483         
484         // IORegistryEntryGetParentEntry retains the returned object, so release it when we're done with it.
485         kernResult = IORegistryEntryGetParentEntry( intfService,
486                                                     kIOServicePlane,
487                                                     &controllerService );
488
489         if (KERN_SUCCESS != kernResult)
490         {
491             printf("IORegistryEntryGetParentEntry returned 0x%08x\n", kernResult);
492         }
493         else {
494             // Retrieve the MAC address property from the I/O Registry in the form of a CFData
495             MACAddressAsCFData = IORegistryEntryCreateCFProperty( controllerService,
496                                                                   CFSTR(kIOMACAddress),
497                                                                   kCFAllocatorDefault,
498                                                                   0);
499             if (MACAddressAsCFData)
500             {
501                 CFShow(MACAddressAsCFData); // for display purposes only; output goes to stderr
502                 
503                 // Get the raw bytes of the MAC address from the CFData
504                 CFDataGetBytes(MACAddressAsCFData, CFRangeMake(0, kIOEthernetAddressSize), MACAddress);
505                 CFRelease(MACAddressAsCFData);
506             }
507                 
508             // Done with the parent Ethernet controller object so we release it.
509             (void) IOObjectRelease(controllerService);
510         }
511         
512         // Done with the Ethernet interface object so we release it.
513         (void) IOObjectRelease(intfService);
514     }
515         
516     return kernResult;
517 }
518 #endif
519
520 long GetMacAddrSys ( u_char *addr)
521 {
522 #ifdef _WIN32
523    WSADATA WinsockData;
524    if (WSAStartup(MAKEWORD(2, 0), &WinsockData) != 0) {
525        fprintf(stderr, "This program requires Winsock 2.x!\n");
526        return -1;
527    }
528
529    HINSTANCE m_hInst;
530    pSnmpExtensionInit m_Init;
531    pSnmpExtensionInitEx m_InitEx;
532    pSnmpExtensionQuery m_Query;
533    pSnmpExtensionTrap m_Trap;
534    HANDLE PollForTrapEvent;
535    AsnObjectIdentifier SupportedView;
536    UINT OID_ifEntryType[] = {
537        1, 3, 6, 1, 2, 1, 2, 2, 1, 3
538    };
539    UINT OID_ifEntryNum[] = {
540        1, 3, 6, 1, 2, 1, 2, 1
541    };
542    UINT OID_ipMACEntAddr[] = {
543        1, 3, 6, 1, 2, 1, 2, 2, 1, 6
544    };                          //, 1 ,6 };
545    AsnObjectIdentifier MIB_ifMACEntAddr =
546        { sizeof(OID_ipMACEntAddr) / sizeof(UINT), OID_ipMACEntAddr };
547    AsnObjectIdentifier MIB_ifEntryType = {
548        sizeof(OID_ifEntryType) / sizeof(UINT), OID_ifEntryType
549    };
550    AsnObjectIdentifier MIB_ifEntryNum = {
551        sizeof(OID_ifEntryNum) / sizeof(UINT), OID_ifEntryNum
552    };
553    RFC1157VarBindList varBindList;
554    RFC1157VarBind varBind[2];
555    AsnInteger errorStatus;
556    AsnInteger errorIndex;
557    AsnObjectIdentifier MIB_NULL = {
558        0, 0
559    };
560    int ret;
561    int dtmp;
562    int i = 0, j = 0;
563    BOOL found = FALSE;
564    m_Init = NULL;
565    m_InitEx = NULL;
566    m_Query = NULL;
567    m_Trap = NULL;
568
569    /* Load the SNMP dll and get the addresses of the functions
570       necessary */
571    m_hInst = LoadLibrary("inetmib1.dll");
572    if (m_hInst < (HINSTANCE) HINSTANCE_ERROR) {
573        m_hInst = NULL;
574        return -1;
575    }
576    m_Init =
577        (pSnmpExtensionInit) GetProcAddress(m_hInst, "SnmpExtensionInit");
578    m_InitEx =
579        (pSnmpExtensionInitEx) GetProcAddress(m_hInst,
580                                              "SnmpExtensionInitEx");
581    m_Query =
582        (pSnmpExtensionQuery) GetProcAddress(m_hInst,
583                                             "SnmpExtensionQuery");
584    m_Trap =
585        (pSnmpExtensionTrap) GetProcAddress(m_hInst, "SnmpExtensionTrap");
586    m_Init(GetTickCount(), &PollForTrapEvent, &SupportedView);
587
588    /* Initialize the variable list to be retrieved by m_Query */
589    varBindList.list = varBind;
590    varBind[0].name = MIB_NULL;
591    varBind[1].name = MIB_NULL;
592
593    /* Copy in the OID to find the number of entries in the
594       Inteface table */
595    varBindList.len = 1;        /* Only retrieving one item */
596    SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryNum);
597    ret =
598        m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
599                &errorIndex);
600    printf("# of adapters in this system : %i\n",
601           varBind[0].value.asnValue.number); varBindList.len = 2;
602
603    /* Copy in the OID of ifType, the type of interface */
604    SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryType);
605
606    /* Copy in the OID of ifPhysAddress, the address */
607    SNMP_oidcpy(&varBind[1].name, &MIB_ifMACEntAddr);
608
609    do {
610
611        /* Submit the query.  Responses will be loaded into varBindList.
612           We can expect this call to succeed a # of times corresponding
613           to the # of adapters reported to be in the system */
614        ret =
615            m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
616                    &errorIndex); if (!ret) ret = 1;
617
618        else
619            /* Confirm that the proper type has been returned */
620            ret =
621                SNMP_oidncmp(&varBind[0].name, &MIB_ifEntryType,
622                             MIB_ifEntryType.idLength); if (!ret) {
623            j++;
624            dtmp = varBind[0].value.asnValue.number;
625            printf("Interface #%i type : %i\n", j, dtmp);
626
627            /* Type 6 describes ethernet interfaces */
628            if (dtmp == 6) {
629
630                /* Confirm that we have an address here */
631                ret =
632                    SNMP_oidncmp(&varBind[1].name, &MIB_ifMACEntAddr,
633                                 MIB_ifMACEntAddr.idLength);
634                if ((!ret)
635                    && (varBind[1].value.asnValue.address.stream != NULL)) {
636                    if (
637                        (varBind[1].value.asnValue.address.stream[0] ==
638                         0x44)
639                        && (varBind[1].value.asnValue.address.stream[1] ==
640                            0x45)
641                        && (varBind[1].value.asnValue.address.stream[2] ==
642                            0x53)
643                        && (varBind[1].value.asnValue.address.stream[3] ==
644                            0x54)
645                        && (varBind[1].value.asnValue.address.stream[4] ==
646                            0x00)) {
647
648                        /* Ignore all dial-up networking adapters */
649                        printf("Interface #%i is a DUN adapter\n", j);
650                        continue;
651                    }
652                    if (
653                        (varBind[1].value.asnValue.address.stream[0] ==
654                         0x00)
655                        && (varBind[1].value.asnValue.address.stream[1] ==
656                            0x00)
657                        && (varBind[1].value.asnValue.address.stream[2] ==
658                            0x00)
659                        && (varBind[1].value.asnValue.address.stream[3] ==
660                            0x00)
661                        && (varBind[1].value.asnValue.address.stream[4] ==
662                            0x00)
663                        && (varBind[1].value.asnValue.address.stream[5] ==
664                            0x00)) {
665
666                        /* Ignore NULL addresses returned by other network
667                           interfaces */
668                        printf("Interface #%i is a NULL address\n", j);
669                        continue;
670                    }
671                    //sprintf((char*)addr, "%02x%02x%02x%02x%02x%02x",
672                    //        varBind[1].value.asnValue.address.stream[0],
673                    //        varBind[1].value.asnValue.address.stream[1],
674                    //        varBind[1].value.asnValue.address.stream[2],
675                    //        varBind[1].value.asnValue.address.stream[3],
676                    //        varBind[1].value.asnValue.address.stream[4],
677                    //        varBind[1].value.asnValue.address.stream[5]);
678                    memcpy( addr, varBind[1].value.asnValue.address.stream, 6);
679                    //printf("MAC Address of interface #%i: %s\n", j, addr);
680               }
681            }
682        }
683    } while (!ret);         /* Stop only on an error.  An error will occur
684                               when we go exhaust the list of interfaces to
685                               be examined */
686    //getch();
687
688    /* Free the bindings */
689    SNMP_FreeVarBind(&varBind[0]);
690    SNMP_FreeVarBind(&varBind[1]);
691    return 0;
692 #endif //_WIN32
693
694 /* implementation for Linux */
695 #ifdef __linux__
696    struct ifreq ifr;
697    struct ifreq *IFR;
698    struct ifconf ifc;
699    char buf[1024];
700    int s, i;
701    int ok = 0;
702
703    s = socket(AF_INET, SOCK_DGRAM, 0);
704    if (s==-1) {
705        return -1;
706    }
707
708    ifc.ifc_len = sizeof(buf);
709    ifc.ifc_buf = buf;
710    ioctl(s, SIOCGIFCONF, &ifc);
711  
712    IFR = ifc.ifc_req;
713    for (i = ifc.ifc_len / sizeof(struct ifreq); --i >= 0; IFR++) {
714
715        strcpy(ifr.ifr_name, IFR->ifr_name);
716        if (ioctl(s, SIOCGIFFLAGS, &ifr) == 0) {
717            if (! (ifr.ifr_flags & IFF_LOOPBACK)) {
718                if (ioctl(s, SIOCGIFHWADDR, &ifr) == 0) {
719                    ok = 1;
720                    break;
721                }
722            }
723        }
724    }
725
726    close(s);
727    if (ok) {
728        bcopy( ifr.ifr_hwaddr.sa_data, addr, 6);
729    }
730    else {
731        return -1;
732    }
733    return 0;
734 #endif
735
736 /* implementation for FreeBSD */
737 #ifdef __FreeBSD__
738    struct ifaddrs *ifap, *ifaphead;
739    int rtnerr;
740    const struct sockaddr_dl *sdl;
741    caddr_t ap;
742    int alen;
743  
744    rtnerr = getifaddrs(&ifaphead);
745    if (rtnerr) {
746      //perror(NULL);
747      return -1;
748    }
749  
750    for (ifap = ifaphead; ifap; ifap = ifap->ifa_next) {
751  
752      if (ifap->ifa_addr->sa_family == AF_LINK) {
753        sdl = (const struct sockaddr_dl *) ifap->ifa_addr;
754        ap = ((caddr_t)((sdl)->sdl_data + (sdl)->sdl_nlen));
755        alen = sdl->sdl_alen;
756        if (ap && alen > 0) {
757          int i;
758  
759          //printf ("%s:", ifap->ifa_name);
760          //for (i = 0; i < alen; i++, ap++)
761            {
762            //printf("%c%02x", i > 0 ? ':' : ' ', 0xff&*ap);
763            }
764          bcopy( ap, addr, 6);
765          //putchar('\n');
766        }
767      }
768    }
769    //putchar('\n');
770  
771    freeifaddrs(ifaphead);
772    return 0;
773 #endif //FreeBSD
774
775 /* implementation for HP-UX */
776 #ifdef __HP_aCC
777
778 #define LAN_DEV0 "/dev/lan0"
779
780     int fd;
781     struct fis iocnt_block;
782     int i;
783     char net_buf[sizeof(LAN_DEV0)+1];
784     char *p;
785
786     (void)sprintf(net_buf, "%s", LAN_DEV0);
787     p = net_buf + strlen(net_buf) - 1;
788
789     /* 
790      * Get 802.3 address from card by opening the driver and interrogating it.
791      */
792     for (i = 0; i < 10; i++, (*p)++) {
793         if ((fd = open (net_buf, O_RDONLY)) != -1) {
794       iocnt_block.reqtype = LOCAL_ADDRESS;
795       ioctl (fd, NETSTAT, &iocnt_block);
796       close (fd);
797
798             if (iocnt_block.vtype == 6)
799                 break;
800         }
801     }
802
803     if (fd == -1 || iocnt_block.vtype != 6) {
804         return -1;
805     }
806
807   bcopy( &iocnt_block.value.s[0], addr, 6);
808   return 0;
809
810 #endif /* HPUX */
811
812 /* implementation for AIX */
813 #ifdef _AIX
814
815     int size;
816     struct kinfo_ndd *nddp;
817
818     size = getkerninfo(KINFO_NDD, 0, 0, 0);
819     if (size <= 0) {
820         return -1;
821     }
822     nddp = (struct kinfo_ndd *)malloc(size);
823           
824     if (!nddp) {
825         return -1;
826     }
827     if (getkerninfo(KINFO_NDD, nddp, &size, 0) < 0) {
828         free(nddp);
829         return -1;
830     }
831     bcopy(nddp->ndd_addr, addr, 6);
832     free(nddp);
833     return 0;
834 #endif //_AIX
835
836 #ifdef __APPLE__
837     kern_return_t kernResult = KERN_SUCCESS; // on PowerPC this is an int (4 bytes)
838 /*
839  *  error number layout as follows (see mach/error.h and IOKit/IOReturn.h):
840  *
841  *  hi             lo
842  * | system(6) | subsystem(12) | code(14) |
843  */
844
845     io_iterator_t intfIterator;
846     UInt8 MACAddress[ kIOEthernetAddressSize ];
847  
848     kernResult = FindEthernetInterfaces(&intfIterator);
849     
850     if (KERN_SUCCESS != kernResult)
851     {
852         printf("FindEthernetInterfaces returned 0x%08x\n", kernResult);
853     }
854     else {
855         kernResult = GetMACAddress_MAC(intfIterator, MACAddress);
856         
857         if (KERN_SUCCESS != kernResult)
858         {
859             printf("GetMACAddress returned 0x%08x\n", kernResult);
860         }
861     }
862     
863     (void) IOObjectRelease(intfIterator); // Release the iterator.
864         
865     memcpy(addr, MACAddress, kIOEthernetAddressSize);
866     return kernResult;
867 #endif //APPLE
868
869 /* Not implemented platforms */
870   memset(addr,0,6);
871   return -1;
872 }
873
874 std::string Util::GetMACAddress()
875 {
876    // This is a rip from: http://cplus.kompf.de/macaddr.html for Linux, HPUX and AIX 
877    // and http://tangentsoft.net/wskfaq/examples/src/snmpmac.cpp for windows version
878    // and http://groups-beta.google.com/group/sol.lists.freebsd.hackers/msg/0d0f862e05fce6c0 for the FreeBSD version
879    // and http://developer.apple.com/samplecode/GetPrimaryMACAddress/GetPrimaryMACAddress.html for MacOSX version
880    long stat;
881    u_char addr[6];
882    std::string macaddr;
883  
884    stat = GetMacAddrSys( addr);
885    if (0 == stat)
886    {
887       //printf( "MAC address = ");
888         for (int i=0; i<6; ++i) 
889         {
890             //printf("%2.2x", addr[i]);
891             macaddr += Format("%2.2x", addr[i]);
892         }
893        // printf( "\n");
894       return macaddr;
895    }
896    else
897    {
898       //printf( "No MAC address !\n" );
899       return "";
900    }
901 }
902
903 /**
904  * \ingroup Util
905  * \brief   Return the IP adress of the machine writting the DICOM image
906  */
907 std::string Util::GetIPAddress()
908 {
909   // This is a rip from http://www.codeguru.com/Cpp/I-N/internet/network/article.php/c3445/
910 #ifndef HOST_NAME_MAX
911   // SUSv2 guarantees that `Host names are limited to 255 bytes'.
912   // POSIX 1003.1-2001 guarantees that `Host names (not including the
913   // terminating NUL) are limited to HOST_NAME_MAX bytes'.
914 #  define HOST_NAME_MAX 255
915   // In this case we should maybe check the string was not truncated.
916   // But I don't known how to check that...
917 #if defined(_MSC_VER) || defined(__BORLANDC__)
918   // with WinSock DLL we need to initialise the WinSock before using gethostname
919   WORD wVersionRequested = MAKEWORD(1,0);
920   WSADATA WSAData;
921   int err = WSAStartup(wVersionRequested,&WSAData);
922   if (err != 0) {
923       /* Tell the user that we could not find a usable */
924       /* WinSock DLL.                                  */
925       WSACleanup();
926       return "127.0.0.1";
927   }
928 #endif
929   
930 #endif //HOST_NAME_MAX
931
932   std::string str;
933   char szHostName[HOST_NAME_MAX+1];
934   int r = gethostname(szHostName, HOST_NAME_MAX);
935
936   if( r == 0 )
937   {
938     // Get host adresses
939     struct hostent *pHost = gethostbyname(szHostName);
940
941     for( int i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
942     {
943       for( int j = 0; j<pHost->h_length; j++ )
944       {
945         if( j > 0 ) str += ".";
946
947         str += Util::Format("%u", 
948             (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);
949       }
950       // str now contains one local IP address 
951
952 #if defined(_MSC_VER) || defined(__BORLANDC__)
953   WSACleanup();
954 #endif
955   
956     }
957   }
958   // If an error occur r == -1
959   // Most of the time it will return 127.0.0.1...
960   return str;
961 }
962
963 /**
964  * \ingroup Util
965  * \brief Creates a new UID. As stipulate in the DICOM ref
966  *        each time a DICOM image is create it should have 
967  *        a unique identifier (URI)
968  */
969 std::string Util::CreateUniqueUID(const std::string &root)
970 {
971   // The code works as follow:
972   // echo "gdcm" | od -b
973   // 0000000 147 144 143 155 012
974   // Therefore we return
975   // radical + 147.144.143.155 + IP + time()
976   std::string radical = root;
977   if( !root.size() ) //anything better ?
978   {
979     radical = "0.0."; // Is this really usefull ?
980   }
981   // else
982   // A root was specified use it to forge our new UID:
983   radical += "147.144.143.155"; // gdcm
984   radical += ".";
985   radical += Util::GetIPAddress();
986   radical += ".";
987   radical += Util::GetCurrentDate();
988   radical += ".";
989   radical += Util::GetCurrentTime();
990
991   return radical;
992 }
993
994 template <class T>
995 std::ostream &binary_write(std::ostream &os, const T &val)
996 {
997     return os.write(reinterpret_cast<const char*>(&val), sizeof val);
998 }
999
1000 std::ostream &binary_write(std::ostream &os, const uint16_t &val)
1001 {
1002 #ifdef GDCM_WORDS_BIGENDIAN
1003     uint16_t swap;
1004     swap = ((( val << 8 ) & 0x0ff00 ) | (( val >> 8 ) & 0x00ff ) );
1005     return os.write(reinterpret_cast<const char*>(&swap), 2);
1006 #else
1007     return os.write(reinterpret_cast<const char*>(&val), 2);
1008 #endif //GDCM_WORDS_BIGENDIAN
1009 }
1010
1011 std::ostream &binary_write(std::ostream &os, const uint32_t &val)
1012 {
1013 #ifdef GDCM_WORDS_BIGENDIAN
1014     uint32_t swap;
1015     swap = ( ((val<<24) & 0xff000000) | ((val<<8)  & 0x00ff0000) | 
1016              ((val>>8)  & 0x0000ff00) | ((val>>24) & 0x000000ff) );
1017     return os.write(reinterpret_cast<const char*>(&swap), 4);
1018 #else
1019     return os.write(reinterpret_cast<const char*>(&val), 4);
1020 #endif //GDCM_WORDS_BIGENDIAN
1021 }
1022
1023 std::ostream &binary_write(std::ostream &os, const char *val)
1024 {
1025     return os.write(val, strlen(val));
1026 }
1027
1028 std::ostream &binary_write(std::ostream &os, std::string const &val)
1029 {
1030     return os.write(val.c_str(), val.size());
1031 }
1032
1033 } // end namespace gdcm
1034