]> Creatis software - gdcm.git/blob - src/gdcmUtil.cxx
c56e707b41ab74d2bac047a2f984fbb81448ba17
[gdcm.git] / src / gdcmUtil.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmUtil.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/01/08 23:00:23 $
7   Version:   $Revision: 1.85 $
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
370 #include <CoreFoundation/CoreFoundation.h>
371
372 #include <IOKit/IOKitLib.h>
373 #include <IOKit/network/IOEthernetInterface.h>
374 #include <IOKit/network/IONetworkInterface.h>
375 #include <IOKit/network/IOEthernetController.h>
376
377 //static kern_return_t FindEthernetInterfaces(io_iterator_t *matchingServices);
378 //static kern_return_t GetMACAddress(io_iterator_t intfIterator, UInt8 *MACAddress);
379
380 // Returns an iterator containing the primary (built-in) Ethernet interface. The caller is responsible for
381 // releasing the iterator after the caller is done with it.
382 static kern_return_t FindEthernetInterfaces(io_iterator_t *matchingServices)
383 {
384     kern_return_t   kernResult; 
385     mach_port_t     masterPort;
386     CFMutableDictionaryRef  matchingDict;
387     CFMutableDictionaryRef  propertyMatchDict;
388     
389     // Retrieve the Mach port used to initiate communication with I/O Kit
390     kernResult = IOMasterPort(MACH_PORT_NULL, &masterPort);
391     if (KERN_SUCCESS != kernResult)
392     {
393         printf("IOMasterPort returned %d\n", kernResult);
394         return kernResult;
395     }
396     
397     // Ethernet interfaces are instances of class kIOEthernetInterfaceClass. 
398     // IOServiceMatching is a convenience function to create a dictionary with the key kIOProviderClassKey and 
399     // the specified value.
400     matchingDict = IOServiceMatching(kIOEthernetInterfaceClass);
401
402     // Note that another option here would be:
403     // matchingDict = IOBSDMatching("en0");
404         
405     if (NULL == matchingDict)
406     {
407         printf("IOServiceMatching returned a NULL dictionary.\n");
408     }
409     else {
410         // Each IONetworkInterface object has a Boolean property with the key kIOPrimaryInterface. Only the
411         // primary (built-in) interface has this property set to TRUE.
412         
413         // IOServiceGetMatchingServices uses the default matching criteria defined by IOService. This considers
414         // only the following properties plus any family-specific matching in this order of precedence 
415         // (see IOService::passiveMatch):
416         //
417         // kIOProviderClassKey (IOServiceMatching)
418         // kIONameMatchKey (IOServiceNameMatching)
419         // kIOPropertyMatchKey
420         // kIOPathMatchKey
421         // kIOMatchedServiceCountKey
422         // family-specific matching
423         // kIOBSDNameKey (IOBSDNameMatching)
424         // kIOLocationMatchKey
425         
426         // The IONetworkingFamily does not define any family-specific matching. This means that in            
427         // order to have IOServiceGetMatchingServices consider the kIOPrimaryInterface property, we must
428         // add that property to a separate dictionary and then add that to our matching dictionary
429         // specifying kIOPropertyMatchKey.
430             
431         propertyMatchDict = CFDictionaryCreateMutable( kCFAllocatorDefault, 0,
432                                                        &kCFTypeDictionaryKeyCallBacks,
433                                                        &kCFTypeDictionaryValueCallBacks);
434     
435         if (NULL == propertyMatchDict)
436         {
437             printf("CFDictionaryCreateMutable returned a NULL dictionary.\n");
438         }
439         else {
440             // Set the value in the dictionary of the property with the given key, or add the key 
441             // to the dictionary if it doesn't exist. This call retains the value object passed in.
442             CFDictionarySetValue(propertyMatchDict, CFSTR(kIOPrimaryInterface), kCFBooleanTrue); 
443             
444             // Now add the dictionary containing the matching value for kIOPrimaryInterface to our main
445             // matching dictionary. This call will retain propertyMatchDict, so we can release our reference 
446             // on propertyMatchDict after adding it to matchingDict.
447             CFDictionarySetValue(matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
448             CFRelease(propertyMatchDict);
449         }
450     }
451     
452     // IOServiceGetMatchingServices retains the returned iterator, so release the iterator when we're done with it.
453     // IOServiceGetMatchingServices also consumes a reference on the matching dictionary so we don't need to release
454     // the dictionary explicitly.
455     kernResult = IOServiceGetMatchingServices(masterPort, matchingDict, matchingServices);    
456     if (KERN_SUCCESS != kernResult)
457     {
458         printf("IOServiceGetMatchingServices returned %d\n", kernResult);
459     }
460         
461     return kernResult;
462 }
463     
464 // Given an iterator across a set of Ethernet interfaces, return the MAC address of the last one.
465 // If no interfaces are found the MAC address is set to an empty string.
466 // In this sample the iterator should contain just the primary interface.
467 static kern_return_t GetMACAddress_MAC(io_iterator_t intfIterator, UInt8 *MACAddress)
468 {
469     io_object_t   intfService;
470     io_object_t   controllerService;
471     kern_return_t kernResult = KERN_FAILURE;
472     
473     // Initialize the returned address
474     bzero(MACAddress, kIOEthernetAddressSize);
475     
476     // IOIteratorNext retains the returned object, so release it when we're done with it.
477     while ( (intfService = IOIteratorNext(intfIterator)))
478     {
479         CFTypeRef MACAddressAsCFData;        
480
481         // IONetworkControllers can't be found directly by the IOServiceGetMatchingServices call, 
482         // since they are hardware nubs and do not participate in driver matching. In other words,
483         // registerService() is never called on them. So we've found the IONetworkInterface and will 
484         // get its parent controller by asking for it specifically.
485         
486         // IORegistryEntryGetParentEntry retains the returned object, so release it when we're done with it.
487         kernResult = IORegistryEntryGetParentEntry( intfService,
488                                                     kIOServicePlane,
489                                                     &controllerService );
490
491         if (KERN_SUCCESS != kernResult)
492         {
493             printf("IORegistryEntryGetParentEntry returned 0x%08x\n", kernResult);
494         }
495         else {
496             // Retrieve the MAC address property from the I/O Registry in the form of a CFData
497             MACAddressAsCFData = IORegistryEntryCreateCFProperty( controllerService,
498                                                                   CFSTR(kIOMACAddress),
499                                                                   kCFAllocatorDefault,
500                                                                   0);
501             if (MACAddressAsCFData)
502             {
503                 CFShow(MACAddressAsCFData); // for display purposes only; output goes to stderr
504                 
505                 // Get the raw bytes of the MAC address from the CFData
506                 CFDataGetBytes(MACAddressAsCFData, CFRangeMake(0, kIOEthernetAddressSize), MACAddress);
507                 CFRelease(MACAddressAsCFData);
508             }
509                 
510             // Done with the parent Ethernet controller object so we release it.
511             (void) IOObjectRelease(controllerService);
512         }
513         
514         // Done with the Ethernet interface object so we release it.
515         (void) IOObjectRelease(intfService);
516     }
517         
518     return kernResult;
519 }
520 #endif
521
522 long GetMacAddrSys ( u_char *addr)
523 {
524 #ifdef _WIN32
525    WSADATA WinsockData;
526    if (WSAStartup(MAKEWORD(2, 0), &WinsockData) != 0) {
527        fprintf(stderr, "This program requires Winsock 2.x!\n");
528        return -1;
529    }
530
531    HINSTANCE m_hInst;
532    pSnmpExtensionInit m_Init;
533    pSnmpExtensionInitEx m_InitEx;
534    pSnmpExtensionQuery m_Query;
535    pSnmpExtensionTrap m_Trap;
536    HANDLE PollForTrapEvent;
537    AsnObjectIdentifier SupportedView;
538    UINT OID_ifEntryType[] = {
539        1, 3, 6, 1, 2, 1, 2, 2, 1, 3
540    };
541    UINT OID_ifEntryNum[] = {
542        1, 3, 6, 1, 2, 1, 2, 1
543    };
544    UINT OID_ipMACEntAddr[] = {
545        1, 3, 6, 1, 2, 1, 2, 2, 1, 6
546    };                          //, 1 ,6 };
547    AsnObjectIdentifier MIB_ifMACEntAddr =
548        { sizeof(OID_ipMACEntAddr) / sizeof(UINT), OID_ipMACEntAddr };
549    AsnObjectIdentifier MIB_ifEntryType = {
550        sizeof(OID_ifEntryType) / sizeof(UINT), OID_ifEntryType
551    };
552    AsnObjectIdentifier MIB_ifEntryNum = {
553        sizeof(OID_ifEntryNum) / sizeof(UINT), OID_ifEntryNum
554    };
555    RFC1157VarBindList varBindList;
556    RFC1157VarBind varBind[2];
557    AsnInteger errorStatus;
558    AsnInteger errorIndex;
559    AsnObjectIdentifier MIB_NULL = {
560        0, 0
561    };
562    int ret;
563    int dtmp;
564    int i = 0, j = 0;
565    BOOL found = FALSE;
566    m_Init = NULL;
567    m_InitEx = NULL;
568    m_Query = NULL;
569    m_Trap = NULL;
570
571    /* Load the SNMP dll and get the addresses of the functions
572       necessary */
573    m_hInst = LoadLibrary("inetmib1.dll");
574    if (m_hInst < (HINSTANCE) HINSTANCE_ERROR) {
575        m_hInst = NULL;
576        return -1;
577    }
578    m_Init =
579        (pSnmpExtensionInit) GetProcAddress(m_hInst, "SnmpExtensionInit");
580    m_InitEx =
581        (pSnmpExtensionInitEx) GetProcAddress(m_hInst,
582                                              "SnmpExtensionInitEx");
583    m_Query =
584        (pSnmpExtensionQuery) GetProcAddress(m_hInst,
585                                             "SnmpExtensionQuery");
586    m_Trap =
587        (pSnmpExtensionTrap) GetProcAddress(m_hInst, "SnmpExtensionTrap");
588    m_Init(GetTickCount(), &PollForTrapEvent, &SupportedView);
589
590    /* Initialize the variable list to be retrieved by m_Query */
591    varBindList.list = varBind;
592    varBind[0].name = MIB_NULL;
593    varBind[1].name = MIB_NULL;
594
595    /* Copy in the OID to find the number of entries in the
596       Inteface table */
597    varBindList.len = 1;        /* Only retrieving one item */
598    SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryNum);
599    ret =
600        m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
601                &errorIndex);
602    printf("# of adapters in this system : %i\n",
603           varBind[0].value.asnValue.number); varBindList.len = 2;
604
605    /* Copy in the OID of ifType, the type of interface */
606    SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryType);
607
608    /* Copy in the OID of ifPhysAddress, the address */
609    SNMP_oidcpy(&varBind[1].name, &MIB_ifMACEntAddr);
610
611    do {
612
613        /* Submit the query.  Responses will be loaded into varBindList.
614           We can expect this call to succeed a # of times corresponding
615           to the # of adapters reported to be in the system */
616        ret =
617            m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
618                    &errorIndex); if (!ret) ret = 1;
619
620        else
621            /* Confirm that the proper type has been returned */
622            ret =
623                SNMP_oidncmp(&varBind[0].name, &MIB_ifEntryType,
624                             MIB_ifEntryType.idLength); if (!ret) {
625            j++;
626            dtmp = varBind[0].value.asnValue.number;
627            printf("Interface #%i type : %i\n", j, dtmp);
628
629            /* Type 6 describes ethernet interfaces */
630            if (dtmp == 6) {
631
632                /* Confirm that we have an address here */
633                ret =
634                    SNMP_oidncmp(&varBind[1].name, &MIB_ifMACEntAddr,
635                                 MIB_ifMACEntAddr.idLength);
636                if ((!ret)
637                    && (varBind[1].value.asnValue.address.stream != NULL)) {
638                    if (
639                        (varBind[1].value.asnValue.address.stream[0] ==
640                         0x44)
641                        && (varBind[1].value.asnValue.address.stream[1] ==
642                            0x45)
643                        && (varBind[1].value.asnValue.address.stream[2] ==
644                            0x53)
645                        && (varBind[1].value.asnValue.address.stream[3] ==
646                            0x54)
647                        && (varBind[1].value.asnValue.address.stream[4] ==
648                            0x00)) {
649
650                        /* Ignore all dial-up networking adapters */
651                        printf("Interface #%i is a DUN adapter\n", j);
652                        continue;
653                    }
654                    if (
655                        (varBind[1].value.asnValue.address.stream[0] ==
656                         0x00)
657                        && (varBind[1].value.asnValue.address.stream[1] ==
658                            0x00)
659                        && (varBind[1].value.asnValue.address.stream[2] ==
660                            0x00)
661                        && (varBind[1].value.asnValue.address.stream[3] ==
662                            0x00)
663                        && (varBind[1].value.asnValue.address.stream[4] ==
664                            0x00)
665                        && (varBind[1].value.asnValue.address.stream[5] ==
666                            0x00)) {
667
668                        /* Ignore NULL addresses returned by other network
669                           interfaces */
670                        printf("Interface #%i is a NULL address\n", j);
671                        continue;
672                    }
673                    //sprintf((char*)addr, "%02x%02x%02x%02x%02x%02x",
674                    //        varBind[1].value.asnValue.address.stream[0],
675                    //        varBind[1].value.asnValue.address.stream[1],
676                    //        varBind[1].value.asnValue.address.stream[2],
677                    //        varBind[1].value.asnValue.address.stream[3],
678                    //        varBind[1].value.asnValue.address.stream[4],
679                    //        varBind[1].value.asnValue.address.stream[5]);
680                    memcpy( addr, varBind[1].value.asnValue.address.stream, 6);
681                    //printf("MAC Address of interface #%i: %s\n", j, addr);
682               }
683            }
684        }
685    } while (!ret);         /* Stop only on an error.  An error will occur
686                               when we go exhaust the list of interfaces to
687                               be examined */
688    //getch();
689
690    /* Free the bindings */
691    SNMP_FreeVarBind(&varBind[0]);
692    SNMP_FreeVarBind(&varBind[1]);
693    return 0;
694 #endif //_WIN32
695
696 /* implementation for Linux */
697 #ifdef __linux__
698    struct ifreq ifr;
699    struct ifreq *IFR;
700    struct ifconf ifc;
701    char buf[1024];
702    int s, i;
703    int ok = 0;
704
705    s = socket(AF_INET, SOCK_DGRAM, 0);
706    if (s==-1) {
707        return -1;
708    }
709
710    ifc.ifc_len = sizeof(buf);
711    ifc.ifc_buf = buf;
712    ioctl(s, SIOCGIFCONF, &ifc);
713  
714    IFR = ifc.ifc_req;
715    for (i = ifc.ifc_len / sizeof(struct ifreq); --i >= 0; IFR++) {
716
717        strcpy(ifr.ifr_name, IFR->ifr_name);
718        if (ioctl(s, SIOCGIFFLAGS, &ifr) == 0) {
719            if (! (ifr.ifr_flags & IFF_LOOPBACK)) {
720                if (ioctl(s, SIOCGIFHWADDR, &ifr) == 0) {
721                    ok = 1;
722                    break;
723                }
724            }
725        }
726    }
727
728    close(s);
729    if (ok) {
730        bcopy( ifr.ifr_hwaddr.sa_data, addr, 6);
731    }
732    else {
733        return -1;
734    }
735    return 0;
736 #endif
737
738 /* implementation for FreeBSD */
739 #ifdef __FreeBSD__
740    struct ifaddrs *ifap, *ifaphead;
741    int rtnerr;
742    const struct sockaddr_dl *sdl;
743    caddr_t ap;
744    int alen;
745  
746    rtnerr = getifaddrs(&ifaphead);
747    if (rtnerr) {
748      //perror(NULL);
749      return -1;
750    }
751  
752    for (ifap = ifaphead; ifap; ifap = ifap->ifa_next) {
753  
754      if (ifap->ifa_addr->sa_family == AF_LINK) {
755        sdl = (const struct sockaddr_dl *) ifap->ifa_addr;
756        ap = ((caddr_t)((sdl)->sdl_data + (sdl)->sdl_nlen));
757        alen = sdl->sdl_alen;
758        if (ap && alen > 0) {
759          int i;
760  
761          //printf ("%s:", ifap->ifa_name);
762          //for (i = 0; i < alen; i++, ap++)
763            {
764            //printf("%c%02x", i > 0 ? ':' : ' ', 0xff&*ap);
765            }
766          bcopy( ap, addr, 6);
767          //putchar('\n');
768        }
769      }
770    }
771    //putchar('\n');
772  
773    freeifaddrs(ifaphead);
774    return 0;
775 #endif //FreeBSD
776
777 /* implementation for HP-UX */
778 #ifdef __HP_aCC
779
780 #define LAN_DEV0 "/dev/lan0"
781
782     int fd;
783     struct fis iocnt_block;
784     int i;
785     char net_buf[sizeof(LAN_DEV0)+1];
786     char *p;
787
788     (void)sprintf(net_buf, "%s", LAN_DEV0);
789     p = net_buf + strlen(net_buf) - 1;
790
791     /* 
792      * Get 802.3 address from card by opening the driver and interrogating it.
793      */
794     for (i = 0; i < 10; i++, (*p)++) {
795         if ((fd = open (net_buf, O_RDONLY)) != -1) {
796       iocnt_block.reqtype = LOCAL_ADDRESS;
797       ioctl (fd, NETSTAT, &iocnt_block);
798       close (fd);
799
800             if (iocnt_block.vtype == 6)
801                 break;
802         }
803     }
804
805     if (fd == -1 || iocnt_block.vtype != 6) {
806         return -1;
807     }
808
809   bcopy( &iocnt_block.value.s[0], addr, 6);
810   return 0;
811
812 #endif /* HPUX */
813
814 /* implementation for AIX */
815 #ifdef _AIX
816
817     int size;
818     struct kinfo_ndd *nddp;
819
820     size = getkerninfo(KINFO_NDD, 0, 0, 0);
821     if (size <= 0) {
822         return -1;
823     }
824     nddp = (struct kinfo_ndd *)malloc(size);
825           
826     if (!nddp) {
827         return -1;
828     }
829     if (getkerninfo(KINFO_NDD, nddp, &size, 0) < 0) {
830         free(nddp);
831         return -1;
832     }
833     bcopy(nddp->ndd_addr, addr, 6);
834     free(nddp);
835     return 0;
836 #endif //_AIX
837
838 #ifdef __APPLE__
839     kern_return_t kernResult = KERN_SUCCESS; // on PowerPC this is an int (4 bytes)
840 /*
841  *  error number layout as follows (see mach/error.h and IOKit/IOReturn.h):
842  *
843  *  hi             lo
844  * | system(6) | subsystem(12) | code(14) |
845  */
846
847     io_iterator_t intfIterator;
848     UInt8 MACAddress[ kIOEthernetAddressSize ];
849  
850     kernResult = FindEthernetInterfaces(&intfIterator);
851     
852     if (KERN_SUCCESS != kernResult)
853     {
854         printf("FindEthernetInterfaces returned 0x%08x\n", kernResult);
855     }
856     else {
857         kernResult = GetMACAddress_MAC(intfIterator, MACAddress);
858         
859         if (KERN_SUCCESS != kernResult)
860         {
861             printf("GetMACAddress returned 0x%08x\n", kernResult);
862         }
863     }
864     
865     (void) IOObjectRelease(intfIterator); // Release the iterator.
866         
867     memcpy(addr, MACAddress, kIOEthernetAddressSize);
868     return kernResult;
869 #endif //APPLE
870
871 /* Not implemented platforms */
872   memset(addr,0,6);
873   return -1;
874 }
875
876 std::string Util::GetMACAddress()
877 {
878    // This is a rip from: http://cplus.kompf.de/macaddr.html for Linux, HPUX and AIX 
879    // and http://tangentsoft.net/wskfaq/examples/src/snmpmac.cpp for windows version
880    // and http://groups-beta.google.com/group/sol.lists.freebsd.hackers/msg/0d0f862e05fce6c0 for the FreeBSD version
881    // and http://developer.apple.com/samplecode/GetPrimaryMACAddress/GetPrimaryMACAddress.html for MacOSX version
882    long stat;
883    u_char addr[6];
884    std::string macaddr;
885  
886    stat = GetMacAddrSys( addr);
887    if (0 == stat)
888    {
889       //printf( "MAC address = ");
890         for (int i=0; i<6; ++i) 
891         {
892             //printf("%2.2x", addr[i]);
893             macaddr += Format("%2.2x", addr[i]);
894         }
895        // printf( "\n");
896       return macaddr;
897    }
898    else
899    {
900       //printf( "No MAC address !\n" );
901       return "";
902    }
903 }
904
905 /**
906  * \ingroup Util
907  * \brief   Return the IP adress of the machine writting the DICOM image
908  */
909 std::string Util::GetIPAddress()
910 {
911   // This is a rip from http://www.codeguru.com/Cpp/I-N/internet/network/article.php/c3445/
912 #ifndef HOST_NAME_MAX
913   // SUSv2 guarantees that `Host names are limited to 255 bytes'.
914   // POSIX 1003.1-2001 guarantees that `Host names (not including the
915   // terminating NUL) are limited to HOST_NAME_MAX bytes'.
916 #  define HOST_NAME_MAX 255
917   // In this case we should maybe check the string was not truncated.
918   // But I don't known how to check that...
919 #if defined(_MSC_VER) || defined(__BORLANDC__)
920   // with WinSock DLL we need to initialise the WinSock before using gethostname
921   WORD wVersionRequested = MAKEWORD(1,0);
922   WSADATA WSAData;
923   int err = WSAStartup(wVersionRequested,&WSAData);
924   if (err != 0) {
925       /* Tell the user that we could not find a usable */
926       /* WinSock DLL.                                  */
927       WSACleanup();
928       return "127.0.0.1";
929   }
930 #endif
931   
932 #endif //HOST_NAME_MAX
933
934   std::string str;
935   char szHostName[HOST_NAME_MAX+1];
936   int r = gethostname(szHostName, HOST_NAME_MAX);
937
938   if( r == 0 )
939   {
940     // Get host adresses
941     struct hostent *pHost = gethostbyname(szHostName);
942
943     for( int i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
944     {
945       for( int j = 0; j<pHost->h_length; j++ )
946       {
947         if( j > 0 ) str += ".";
948
949         str += Util::Format("%u", 
950             (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);
951       }
952       // str now contains one local IP address 
953
954 #if defined(_MSC_VER) || defined(__BORLANDC__)
955   WSACleanup();
956 #endif
957   
958     }
959   }
960   // If an error occur r == -1
961   // Most of the time it will return 127.0.0.1...
962   return str;
963 }
964
965 /**
966  * \ingroup Util
967  * \brief Creates a new UID. As stipulate in the DICOM ref
968  *        each time a DICOM image is create it should have 
969  *        a unique identifier (URI)
970  */
971 std::string Util::CreateUniqueUID(const std::string &root)
972 {
973   // The code works as follow:
974   // echo "gdcm" | od -b
975   // 0000000 147 144 143 155 012
976   // Therefore we return
977   // radical + 147.144.143.155 + IP + time()
978   std::string radical = root;
979   if( !root.size() ) //anything better ?
980   {
981     radical = "0.0."; // Is this really usefull ?
982   }
983   // else
984   // A root was specified use it to forge our new UID:
985   radical += "147.144.143.155"; // gdcm
986   radical += ".";
987   radical += Util::GetIPAddress();
988   radical += ".";
989   radical += Util::GetCurrentDate();
990   radical += ".";
991   radical += Util::GetCurrentTime();
992
993   return radical;
994 }
995
996 template <class T>
997 std::ostream &binary_write(std::ostream &os, const T &val)
998 {
999     return os.write(reinterpret_cast<const char*>(&val), sizeof val);
1000 }
1001
1002 std::ostream &binary_write(std::ostream &os, const uint16_t &val)
1003 {
1004 #ifdef GDCM_WORDS_BIGENDIAN
1005     uint16_t swap;
1006     swap = ((( val << 8 ) & 0x0ff00 ) | (( val >> 8 ) & 0x00ff ) );
1007     return os.write(reinterpret_cast<const char*>(&swap), 2);
1008 #else
1009     return os.write(reinterpret_cast<const char*>(&val), 2);
1010 #endif //GDCM_WORDS_BIGENDIAN
1011 }
1012
1013 std::ostream &binary_write(std::ostream &os, const uint32_t &val)
1014 {
1015 #ifdef GDCM_WORDS_BIGENDIAN
1016     uint32_t swap;
1017     swap = ( ((val<<24) & 0xff000000) | ((val<<8)  & 0x00ff0000) | 
1018              ((val>>8)  & 0x0000ff00) | ((val>>24) & 0x000000ff) );
1019     return os.write(reinterpret_cast<const char*>(&swap), 4);
1020 #else
1021     return os.write(reinterpret_cast<const char*>(&val), 4);
1022 #endif //GDCM_WORDS_BIGENDIAN
1023 }
1024
1025 std::ostream &binary_write(std::ostream &os, const char *val)
1026 {
1027     return os.write(val, strlen(val));
1028 }
1029
1030 std::ostream &binary_write(std::ostream &os, std::string const &val)
1031 {
1032     return os.write(val.c_str(), val.size());
1033 }
1034
1035 } // end namespace gdcm
1036