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