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