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