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