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