]> Creatis software - gdcm.git/blob - src/gdcmUtil.cxx
BUG: This should solve the last Seg Fault. In a loop you need to reinitalizaze your...
[gdcm.git] / src / gdcmUtil.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmUtil.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/02/14 16:20:30 $
7   Version:   $Revision: 1.145 $
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 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
29 #include <sys/timeb.h>
30 #else
31 #include <sys/time.h>
32 #endif
33
34 #include <stdarg.h>  //only included in implementation file
35 #include <stdio.h>   //only included in implementation file
36
37 #if defined(_MSC_VER) || defined(__MINGW32__)
38    #include <winsock.h>  // for gethostname and gethostbyname
39    #undef GetCurrentTime
40 #else
41 #ifndef __BORLANDC__
42    #include <unistd.h>  // for gethostname
43    #include <netdb.h>   // for gethostbyname
44 #endif
45 #endif
46
47 // For GetMACAddress
48 #ifdef _WIN32
49    #include <snmp.h>
50    #include <conio.h>
51 #else
52    #include <unistd.h>
53    #include <stdlib.h>
54    #include <string.h>
55    #include <sys/types.h>
56 #endif
57
58 #ifdef CMAKE_HAVE_SYS_IOCTL_H
59    #include <sys/ioctl.h>  // For SIOCGIFCONF on Linux
60 #endif
61 #ifdef CMAKE_HAVE_SYS_SOCKET_H
62    #include <sys/socket.h>
63 #endif
64 #ifdef CMAKE_HAVE_SYS_SOCKIO_H
65    #include <sys/sockio.h>  // For SIOCGIFCONF on SunOS
66 #endif
67 #ifdef CMAKE_HAVE_NET_IF_H
68    #include <net/if.h>
69 #endif
70 #ifdef CMAKE_HAVE_NETINET_IN_H
71    #include <netinet/in.h>   //For IPPROTO_IP
72 #endif
73 #ifdef CMAKE_HAVE_NET_IF_DL_H
74    #include <net/if_dl.h>
75 #endif
76 #if defined(CMAKE_HAVE_NET_IF_ARP_H) && defined(__sun)
77    // This is absolutely necessary on SunOS
78    #include <net/if_arp.h>
79 #endif
80
81 // For GetCurrentThreadID()
82 #ifdef __linux__
83    #include <sys/types.h>
84    #include <linux/unistd.h>
85 #endif
86 #ifdef __sun
87    #include <thread.h>
88 #endif
89
90 namespace gdcm 
91 {
92 //-------------------------------------------------------------------------
93 const std::string Util::GDCM_UID = "1.2.826.0.1.3680043.2.1143";
94 std::string Util::RootUID        = GDCM_UID;
95
96 //-------------------------------------------------------------------------
97 // Public
98 /**
99  * \brief Provide a better 'c++' approach for sprintf
100  * For example c code is:
101  * char result[200]; // hope 200 is enough
102  * sprintf(result, "%04x|%04x", group , elem);
103  *
104  * c++ code is 
105  * std::ostringstream buf;
106  * buf << std::right << std::setw(4) << std::setfill('0') << std::hex
107  *     << group << "|" << std::right << std::setw(4) << std::setfill('0') 
108  *     << std::hex <<  elem;
109  * buf.str();
110  *
111  * gdcm style code is
112  * string result;
113  * result = gdcm::Util::Format("%04x|%04x", group , elem);
114  */
115 std::string Util::Format(const char *format, ...)
116 {
117    char buffer[2048];
118    va_list args;
119    va_start(args, format);
120    vsprintf(buffer, format, args);  //might be a security flaw
121    va_end(args); // Each invocation of va_start should be matched 
122                  // by a corresponding invocation of va_end
123                  // args is then 'undefined'
124    return buffer;
125 }
126
127
128 /**
129  * \brief Because not available in C++ (?)
130  * @param str string to check
131  * @param tokens std::vector to receive the tokenized substrings
132  * @param delimiters string containing the character delimitors
133  
134  */
135 void Util::Tokenize (const std::string &str,
136                      std::vector<std::string> &tokens,
137                      const std::string &delimiters)
138 {
139    std::string::size_type lastPos = str.find_first_not_of(delimiters,0);
140    std::string::size_type pos     = str.find_first_of    (delimiters,lastPos);
141    while (std::string::npos != pos || std::string::npos != lastPos)
142    {
143       tokens.push_back(str.substr(lastPos, pos - lastPos));
144       lastPos = str.find_first_not_of(delimiters, pos);
145       pos     = str.find_first_of    (delimiters, lastPos);
146    }
147 }
148
149 /**
150  * \brief Because not available in C++ (?)
151  *        Counts the number of occurences of a substring within a string
152  * @param str string to check
153  * @param subStr substring to count
154  */
155  
156 int Util::CountSubstring (const std::string &str,
157                           const std::string &subStr)
158 {
159    int count = 0;                 // counts how many times it appears
160    std::string::size_type x = 0;  // The index position in the string
161
162    do
163    {
164       x = str.find(subStr,x);     // Find the substring
165       if (x != std::string::npos) // If present
166       {
167          count++;                 // increase the count
168          x += subStr.length();    // Skip this word
169       }
170    }
171    while (x != std::string::npos);// Carry on until not present
172
173    return count;
174 }
175
176 /**
177  * \brief  Weed out a string from the non-printable characters (in order
178  *         to avoid corrupting the terminal of invocation when printing)
179  * @param s string to remove non printable characters from
180  */
181 std::string Util::CreateCleanString(std::string const &s)
182 {
183    std::string str = s;
184
185    for(unsigned int i=0; i<str.size(); i++)
186    {
187       if(!isprint((unsigned char)str[i]))
188       {
189          str[i] = '.';
190       }
191    }
192
193    if(str.size() > 0)
194    {
195       if(!isprint((unsigned char)s[str.size()-1]))
196       {
197          if(s[str.size()-1] == 0)
198          {
199             str[str.size()-1] = ' ';
200          }
201       }
202    }
203
204    return str;
205 }
206
207 /**
208  * \brief   Add a SEPARATOR to the end of the name is necessary
209  * @param   pathname file/directory name to normalize 
210  */
211 std::string Util::NormalizePath(std::string const &pathname)
212 {
213    const char SEPARATOR_X      = '/';
214    const char SEPARATOR_WIN    = '\\';
215    const std::string SEPARATOR = "/";
216    std::string name = pathname;
217    int size = name.size();
218
219    if( name[size-1] != SEPARATOR_X && name[size-1] != SEPARATOR_WIN )
220    {
221       name += SEPARATOR;
222    }
223    return name;
224 }
225
226 /**
227  * \brief   Get the (directory) path from a full path file name
228  * @param   fullName file/directory name to extract Path from
229  */
230 std::string Util::GetPath(std::string const &fullName)
231 {
232    std::string res = fullName;
233    int pos1 = res.rfind("/");
234    int pos2 = res.rfind("\\");
235    if( pos1 > pos2)
236    {
237       res.resize(pos1);
238    }
239    else
240    {
241       res.resize(pos2);
242    }
243
244    return res;
245 }
246
247 /**
248  * \brief   Get the (last) name of a full path file name
249  * @param   fullName file/directory name to extract end name from
250  */
251 std::string Util::GetName(std::string const &fullName)
252 {   
253   std::string filename = fullName;
254
255   std::string::size_type slash_pos = filename.rfind("/");
256   std::string::size_type backslash_pos = filename.rfind("\\");
257   slash_pos = slash_pos > backslash_pos ? slash_pos : backslash_pos;
258   if(slash_pos != std::string::npos)
259     {
260     return filename.substr(slash_pos + 1);
261     }
262   else
263     {
264     return filename;
265     }
266
267
268 /**
269  * \brief   Get the current date of the system in a dicom string
270  */
271 std::string Util::GetCurrentDate()
272 {
273     char tmp[512];
274     time_t tloc;
275     time (&tloc);    
276     strftime(tmp,512,"%Y%m%d", localtime(&tloc) );
277     return tmp;
278 }
279
280 /**
281  * \brief   Get the current time of the system in a dicom string
282  */
283 std::string Util::GetCurrentTime()
284 {
285     char tmp[512];
286     time_t tloc;
287     time (&tloc);
288     strftime(tmp,512,"%H%M%S", localtime(&tloc) );
289     return tmp;  
290 }
291
292 /**
293  * \brief  Get both the date and time at the same time to avoid problem 
294  * around midnight where two call could be before and after midnight
295  */
296 std::string Util::GetCurrentDateTime()
297 {
298    char tmp[40];
299    long milliseconds;
300    time_t timep;
301   
302    // We need implementation specific functions to obtain millisecond precision
303 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
304    struct timeb tb;
305    ::ftime(&tb);
306    timep = tb.time;
307    milliseconds = tb.millitm;
308 #else
309    struct timeval tv;
310    gettimeofday (&tv, NULL);
311    timep = tv.tv_sec;
312    // Compute milliseconds from microseconds.
313    milliseconds = tv.tv_usec / 1000;
314 #endif
315    // Obtain the time of day, and convert it to a tm struct.
316    struct tm *ptm = localtime (&timep);
317    // Format the date and time, down to a single second.
318    strftime (tmp, sizeof (tmp), "%Y%m%d%H%M%S", ptm);
319
320    // Add milliseconds
321    std::string r = tmp;
322    r += Format("%03ld", milliseconds);
323
324    return r;
325 }
326
327 unsigned int Util::GetCurrentThreadID()
328 {
329 // FIXME the implementation is far from complete
330 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
331   return (unsigned int)GetCurrentThreadId();
332 #endif
333 #ifdef __linux__
334    return 0;
335    // Doesn't work on fedora, but is in the man page...
336    //return (unsigned int)gettid();
337 #endif
338 #ifdef __sun
339    return (unsigned int)thr_self();
340 #else
341    //default implementation
342    return 0;
343 #endif
344 }
345
346 unsigned int Util::GetCurrentProcessID()
347 {
348 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
349   // NOTE: There is also a _getpid()...
350   return (unsigned int)GetCurrentProcessId();
351 #else
352   // get process identification, POSIX
353   return (unsigned int)getpid();
354 #endif
355 }
356
357 /**
358  * \brief   tells us if the processor we are working with is BigEndian or not
359  */
360 bool Util::IsCurrentProcessorBigEndian()
361 {
362 #if defined(GDCM_WORDS_BIGENDIAN)
363    return true;
364 #else
365    return false;
366 #endif
367 }
368
369 /**
370  * \brief Create a /DICOM/ string:
371  * It should a of even length (no odd length ever)
372  * It can contain as many (if you are reading this from your
373  * editor the following character is is backslash followed by zero
374  * that needed to be escaped with an extra backslash for doxygen) \\0
375  * as you want.
376  */
377 std::string Util::DicomString(const char *s, size_t l)
378 {
379    std::string r(s, s+l);
380    gdcmAssertMacro( !(r.size() % 2) ); // == basically 'l' is even
381    return r;
382 }
383
384 /**
385  * \brief Create a /DICOM/ string:
386  * It should a of even length (no odd length ever)
387  * It can contain as many (if you are reading this from your
388  * editor the following character is is backslash followed by zero
389  * that needed to be escaped with an extra backslash for doxygen) \\0
390  * as you want.
391  * This function is similar to DicomString(const char*), 
392  * except it doesn't take a length. 
393  * It only pad with a null character if length is odd
394  */
395 std::string Util::DicomString(const char *s)
396 {
397    size_t l = strlen(s);
398    if( l%2 )
399    {
400       l++;
401    }
402    std::string r(s, s+l);
403    gdcmAssertMacro( !(r.size() % 2) );
404    return r;
405 }
406
407 /**
408  * \brief Safely compare two Dicom String:
409  *        - Both string should be of even length
410  *        - We allow padding of even length string by either a null 
411  *          character of a space
412  */
413 bool Util::DicomStringEqual(const std::string &s1, const char *s2)
414 {
415   // s2 is the string from the DICOM reference: 'MONOCHROME1'
416   std::string s1_even = s1; //Never change input parameter
417   std::string s2_even = DicomString( s2 );
418   if( s1_even[s1_even.size()-1] == ' ')
419   {
420     s1_even[s1_even.size()-1] = '\0'; //replace space character by null
421   }
422   return s1_even == s2_even;
423 }
424
425 #ifdef _WIN32
426    typedef BOOL(WINAPI * pSnmpExtensionInit) (
427            IN DWORD dwTimeZeroReference,
428            OUT HANDLE * hPollForTrapEvent,
429            OUT AsnObjectIdentifier * supportedView);
430
431    typedef BOOL(WINAPI * pSnmpExtensionTrap) (
432            OUT AsnObjectIdentifier * enterprise,
433            OUT AsnInteger * genericTrap,
434            OUT AsnInteger * specificTrap,
435            OUT AsnTimeticks * timeStamp,
436            OUT RFC1157VarBindList * variableBindings);
437
438    typedef BOOL(WINAPI * pSnmpExtensionQuery) (
439            IN BYTE requestType,
440            IN OUT RFC1157VarBindList * variableBindings,
441            OUT AsnInteger * errorStatus,
442            OUT AsnInteger * errorIndex);
443
444    typedef BOOL(WINAPI * pSnmpExtensionInitEx) (
445            OUT AsnObjectIdentifier * supportedView);
446 #endif //_WIN32
447
448 /// \brief gets current M.A.C adress (for internal use only)
449 int GetMacAddrSys ( unsigned char *addr )
450 {
451 #ifdef _WIN32
452    WSADATA WinsockData;
453    if (WSAStartup(MAKEWORD(2, 0), &WinsockData) != 0) 
454    {
455       std::cerr << "This program requires Winsock 2.x!" << std::endl;
456       return -1;
457    }
458
459    HANDLE PollForTrapEvent;
460    AsnObjectIdentifier SupportedView;
461    UINT OID_ifEntryType[]  = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 3 };
462    UINT OID_ifEntryNum[]   = { 1, 3, 6, 1, 2, 1, 2, 1 };
463    UINT OID_ipMACEntAddr[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 6 };
464    AsnObjectIdentifier MIB_ifMACEntAddr = {
465        sizeof(OID_ipMACEntAddr) / sizeof(UINT), OID_ipMACEntAddr };
466    AsnObjectIdentifier MIB_ifEntryType = {
467        sizeof(OID_ifEntryType) / sizeof(UINT), OID_ifEntryType };
468    AsnObjectIdentifier MIB_ifEntryNum = {
469        sizeof(OID_ifEntryNum) / sizeof(UINT), OID_ifEntryNum };
470    RFC1157VarBindList varBindList;
471    RFC1157VarBind varBind[2];
472    AsnInteger errorStatus;
473    AsnInteger errorIndex;
474    AsnObjectIdentifier MIB_NULL = { 0, 0 };
475    int ret;
476    int dtmp;
477    int j = 0;
478
479    // Load the SNMP dll and get the addresses of the functions necessary
480    HINSTANCE m_hInst = LoadLibrary("inetmib1.dll");
481    if (m_hInst < (HINSTANCE) HINSTANCE_ERROR)
482    {
483       return -1;
484    }
485    pSnmpExtensionInit m_Init =
486        (pSnmpExtensionInit) GetProcAddress(m_hInst, "SnmpExtensionInit");
487    pSnmpExtensionQuery m_Query =
488        (pSnmpExtensionQuery) GetProcAddress(m_hInst, "SnmpExtensionQuery");
489    m_Init(GetTickCount(), &PollForTrapEvent, &SupportedView);
490
491    /* Initialize the variable list to be retrieved by m_Query */
492    varBindList.list = varBind;
493    varBind[0].name = MIB_NULL;
494    varBind[1].name = MIB_NULL;
495
496    // Copy in the OID to find the number of entries in the
497    // Inteface table
498    varBindList.len = 1;        // Only retrieving one item
499    SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryNum);
500    m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
501                  &errorIndex);
502 //   printf("# of adapters in this system : %i\n",
503 //          varBind[0].value.asnValue.number);
504    varBindList.len = 2;
505
506    // Copy in the OID of ifType, the type of interface
507    SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryType);
508
509    // Copy in the OID of ifPhysAddress, the address
510    SNMP_oidcpy(&varBind[1].name, &MIB_ifMACEntAddr);
511
512    do
513    {
514       // Submit the query.  Responses will be loaded into varBindList.
515       // We can expect this call to succeed a # of times corresponding
516       // to the # of adapters reported to be in the system
517       ret = m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
518                     &errorIndex); 
519       if (!ret)
520       {
521          ret = 1;
522       }
523       else
524       {
525          // Confirm that the proper type has been returned
526          ret = SNMP_oidncmp(&varBind[0].name, &MIB_ifEntryType,
527                             MIB_ifEntryType.idLength);
528       }
529       if (!ret)
530       {
531          j++;
532          dtmp = varBind[0].value.asnValue.number;
533
534          // Type 6 describes ethernet interfaces
535          if (dtmp == 6)
536          {
537             // Confirm that we have an address here
538             ret = SNMP_oidncmp(&varBind[1].name, &MIB_ifMACEntAddr,
539                                MIB_ifMACEntAddr.idLength);
540             if ( !ret && varBind[1].value.asnValue.address.stream != NULL )
541             {
542                if ( (varBind[1].value.asnValue.address.stream[0] == 0x44)
543                  && (varBind[1].value.asnValue.address.stream[1] == 0x45)
544                  && (varBind[1].value.asnValue.address.stream[2] == 0x53)
545                  && (varBind[1].value.asnValue.address.stream[3] == 0x54)
546                  && (varBind[1].value.asnValue.address.stream[4] == 0x00) )
547                {
548                    // Ignore all dial-up networking adapters
549                    std::cerr << "Interface #" << j << " is a DUN adapter\n";
550                    continue;
551                }
552                if ( (varBind[1].value.asnValue.address.stream[0] == 0x00)
553                  && (varBind[1].value.asnValue.address.stream[1] == 0x00)
554                  && (varBind[1].value.asnValue.address.stream[2] == 0x00)
555                  && (varBind[1].value.asnValue.address.stream[3] == 0x00)
556                  && (varBind[1].value.asnValue.address.stream[4] == 0x00)
557                  && (varBind[1].value.asnValue.address.stream[5] == 0x00) )
558                {
559                   // Ignore NULL addresses returned by other network
560                   // interfaces
561                   std::cerr << "Interface #" << j << " is a NULL address\n";
562                   continue;
563                }
564                memcpy( addr, varBind[1].value.asnValue.address.stream, 6);
565             }
566          }
567       }
568    } while (!ret);
569
570    // Free the bindings
571    SNMP_FreeVarBind(&varBind[0]);
572    SNMP_FreeVarBind(&varBind[1]);
573    return 0;
574 #endif //Win32 version
575
576
577 // implementation for POSIX system
578 #ifdef __sun
579    //The POSIX version is broken anyway on Solaris, plus would require full
580    //root power
581    struct  arpreq          parpreq;
582    struct  sockaddr_in     *psa;
583    struct  hostent         *phost;
584    char                    hostname[MAXHOSTNAMELEN];
585    char                    **paddrs;
586    int                     sock, status=0;
587
588    if(gethostname(hostname,  MAXHOSTNAMELEN) != 0)
589    {
590       perror("gethostname");
591       return -1;
592    }
593    phost = gethostbyname(hostname);
594    paddrs = phost->h_addr_list;
595
596    sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
597    if(sock == -1)
598    {
599       perror("sock");
600       return -1;
601    }
602    memset(&parpreq, 0, sizeof(struct arpreq));
603    psa = (struct sockaddr_in *) &parpreq.arp_pa;
604
605    memset(psa, 0, sizeof(struct sockaddr_in));
606    psa->sin_family = AF_INET;
607    memcpy(&psa->sin_addr, *paddrs, sizeof(struct in_addr));
608
609    status = ioctl(sock, SIOCGARP, &parpreq);
610    if(status == -1)
611    {
612       perror("SIOCGARP");
613       return -1;
614    }
615    memcpy(addr, parpreq.arp_ha.sa_data, 6);
616
617    return 0;
618 #else
619 #ifdef CMAKE_HAVE_NET_IF_H
620    int       sd;
621    struct ifreq    ifr, *ifrp;
622    struct ifconf    ifc;
623    char buf[1024];
624    int      n, i;
625    unsigned char    *a;
626 #if defined(AF_LINK) && (!defined(SIOCGIFHWADDR) && !defined(SIOCGENADDR))
627    struct sockaddr_dl *sdlp;
628 #endif
629
630 //
631 // BSD 4.4 defines the size of an ifreq to be
632 // max(sizeof(ifreq), sizeof(ifreq.ifr_name)+ifreq.ifr_addr.sa_len
633 // However, under earlier systems, sa_len isn't present, so the size is 
634 // just sizeof(struct ifreq)
635 // We should investiage the use of SIZEOF_ADDR_IFREQ
636 //
637 #ifdef HAVE_SA_LEN
638    #ifndef max
639       #define max(a,b) ((a) > (b) ? (a) : (b))
640    #endif
641    #define ifreq_size(i) max(sizeof(struct ifreq),\
642         sizeof((i).ifr_name)+(i).ifr_addr.sa_len)
643 #else
644    #define ifreq_size(i) sizeof(struct ifreq)
645 #endif // HAVE_SA_LEN
646
647    if( (sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) < 0 )
648    {
649       return -1;
650    }
651    memset(buf, 0, sizeof(buf));
652    ifc.ifc_len = sizeof(buf);
653    ifc.ifc_buf = buf;
654    if (ioctl (sd, SIOCGIFCONF, (char *)&ifc) < 0)
655    {
656       close(sd);
657       return -1;
658    }
659    n = ifc.ifc_len;
660    for (i = 0; i < n; i+= ifreq_size(*ifrp) )
661    {
662       ifrp = (struct ifreq *)((char *) ifc.ifc_buf+i);
663       strncpy(ifr.ifr_name, ifrp->ifr_name, IFNAMSIZ);
664 #ifdef SIOCGIFHWADDR
665       if (ioctl(sd, SIOCGIFHWADDR, &ifr) < 0)
666          continue;
667       a = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
668 #else
669 #ifdef SIOCGENADDR
670       // In theory this call should also work on Sun Solaris, but apparently
671       // SIOCGENADDR is not implemented properly thus the call 
672       // ioctl(sd, SIOCGENADDR, &ifr) always returns errno=2 
673       // (No such file or directory)
674       // Furthermore the DLAPI seems to require full root access
675       if (ioctl(sd, SIOCGENADDR, &ifr) < 0)
676          continue;
677       a = (unsigned char *) ifr.ifr_enaddr;
678 #else
679 #ifdef AF_LINK
680       sdlp = (struct sockaddr_dl *) &ifrp->ifr_addr;
681       if ((sdlp->sdl_family != AF_LINK) || (sdlp->sdl_alen != 6))
682          continue;
683       a = (unsigned char *) &sdlp->sdl_data[sdlp->sdl_nlen];
684 #else
685       perror("No way to access hardware");
686       close(sd);
687       return -1;
688 #endif // AF_LINK
689 #endif // SIOCGENADDR
690 #endif // SIOCGIFHWADDR
691       if (!a[0] && !a[1] && !a[2] && !a[3] && !a[4] && !a[5]) continue;
692
693       if (addr) 
694       {
695          memcpy(addr, a, 6);
696          close(sd);
697          return 0;
698       }
699    }
700    close(sd);
701 #endif
702    // Not implemented platforms
703    perror("There was a configuration problem on your plateform");
704    memset(addr,0,6);
705    return -1;
706 #endif //__sun
707 }
708
709 /**
710  * \brief Mini function to return the last digit from a number express in base 256
711  *        pre condition data contain an array of 6 unsigned char
712  *        post condition carry contain the last digit
713  */
714 inline int getlastdigit(unsigned char *data)
715 {
716   int extended, carry = 0;
717   for(int i=0;i<6;i++)
718     {
719     extended = (carry << 8) + data[i];
720     data[i] = extended / 10;
721     carry = extended % 10;
722     }
723   return carry;
724 }
725
726 /**
727  * \brief Encode the mac address on a fixed lenght string of 15 characters.
728  * we save space this way.
729  */
730 std::string Util::GetMACAddress()
731 {
732    // This code is the result of a long internet search to find something
733    // as compact as possible (not OS independant). We only have to separate
734    // 3 OS: Win32, SunOS and 'real' POSIX
735    // http://groups-beta.google.com/group/comp.unix.solaris/msg/ad36929d783d63be
736    // http://bdn.borland.com/article/0,1410,26040,00.html
737    unsigned char addr[6];
738
739    int stat = GetMacAddrSys(addr);
740    if (stat == 0)
741    {
742       // We need to convert a 6 digit number from base 256 to base 10, using integer
743       // would requires a 48bits one. To avoid this we have to reimplement the div + modulo 
744       // with string only
745       bool zero = false;
746       int res;
747       std::string sres;
748       while(!zero)
749       {
750          res = getlastdigit(addr);
751          sres.insert(sres.begin(), '0' + res);
752          zero = (addr[0] == 0) && (addr[1] == 0) && (addr[2] == 0) 
753              && (addr[3] == 0) && (addr[4] == 0) && (addr[5] == 0);
754       }
755
756       return sres;
757    }
758    else
759    {
760       gdcmWarningMacro("Problem in finding the MAC Address");
761       return "";
762    }
763 }
764
765 /**
766  * \brief Creates a new UID. As stipulate in the DICOM ref
767  *        each time a DICOM image is create it should have 
768  *        a unique identifier (URI)
769  * @param root is the DICOM prefix assigned by IOS group
770  */
771 std::string Util::CreateUniqueUID(const std::string &root)
772 {
773    std::string prefix;
774    std::string append;
775    if( root.empty() )
776    {
777       // gdcm UID prefix, as supplied by http://www.medicalconnections.co.uk
778       prefix = RootUID; 
779    }
780    else
781    {
782       prefix = root;
783    }
784
785    // A root was specified use it to forge our new UID:
786    append += ".";
787    append += Util::GetMACAddress();
788    append += ".";
789    append += Util::GetCurrentDateTime();
790
791    //Also add a mini random number just in case:
792    int r = (int) (100.0*rand()/RAND_MAX);
793    append += Format("%02d", r);
794
795    // If append is too long we need to rehash it
796    if( (prefix + append).size() > 64 )
797    {
798       gdcmErrorMacro( "Size of UID is too long." );
799       // we need a hash function to truncate this number
800       // if only md5 was cross plateform
801       // MD5(append);
802    }
803
804    return prefix + append;
805 }
806
807 void Util::SetRootUID(const std::string &root)
808 {
809    if( root.empty() )
810       RootUID = GDCM_UID;
811    else
812       RootUID = root;
813 }
814
815 const std::string &Util::GetRootUID()
816 {
817    return RootUID;
818 }
819
820 //-------------------------------------------------------------------------
821 /**
822  * \brief binary_write binary_write
823  * @param os ostream to write to 
824  * @param val val
825  */ 
826 std::ostream &binary_write(std::ostream &os, const uint16_t &val)
827 {
828 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
829    uint16_t swap;
830    //swap = ((( val << 8 ) & 0xff00 ) | (( val >> 8 ) & 0x00ff ) );
831    //save CPU time
832    swap = ( val << 8 |  val >> 8  );
833
834    return os.write(reinterpret_cast<const char*>(&swap), 2);
835 #else
836    return os.write(reinterpret_cast<const char*>(&val), 2);
837 #endif //GDCM_WORDS_BIGENDIAN
838 }
839
840 /**
841  * \brief binary_write binary_write
842  * @param os ostream to write to
843  * @param val val
844  */ 
845 std::ostream &binary_write(std::ostream &os, const uint32_t &val)
846 {
847 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
848    uint32_t swap;
849 //   swap = ( ((val<<24) & 0xff000000) | ((val<<8)  & 0x00ff0000) | 
850 //            ((val>>8)  & 0x0000ff00) | ((val>>24) & 0x000000ff) );
851 // save CPU time
852    swap = (  (val<<24)               | ((val<<8)  & 0x00ff0000) | 
853             ((val>>8)  & 0x0000ff00) |  (val>>24)               );
854    return os.write(reinterpret_cast<const char*>(&swap), 4);
855 #else
856    return os.write(reinterpret_cast<const char*>(&val), 4);
857 #endif //GDCM_WORDS_BIGENDIAN
858 }
859
860 /**
861  * \brief  binary_write binary_write
862  * @param os ostream to write to
863  * @param val val
864  */ 
865 std::ostream &binary_write(std::ostream &os, const char *val)
866 {
867    return os.write(val, strlen(val));
868 }
869
870 /**
871  * \brief
872  * @param os ostream to write to
873  * @param val val
874  */ 
875 std::ostream &binary_write(std::ostream &os, std::string const &val)
876 {
877    return os.write(val.c_str(), val.size());
878 }
879
880 /**
881  * \brief  binary_write binary_write
882  * @param os ostream to write to
883  * @param val value
884  * @param len length of the 'value' to be written
885  */ 
886 std::ostream &binary_write(std::ostream &os, const uint8_t *val, size_t len)
887 {
888    // We are writting sizeof(char) thus no need to swap bytes
889    return os.write(reinterpret_cast<const char*>(val), len);
890 }
891
892 /**
893  * \brief  binary_write binary_write
894  * @param os ostream to write to
895  * @param val val
896  * @param len length of the 'value' to be written 
897  */ 
898 std::ostream &binary_write(std::ostream &os, const uint16_t *val, size_t len)
899 {
900 // This is tricky since we are writting two bytes buffer. 
901 // Be carefull with little endian vs big endian. 
902 // Also this other trick is to allocate a small (efficient) buffer that store
903 // intermediate result before writting it.
904 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
905    const int BUFFER_SIZE = 4096;
906    static char buffer[BUFFER_SIZE];
907    uint16_t *binArea16 = (uint16_t*)val; //for the const
908  
909    // how many BUFFER_SIZE long pieces in binArea ?
910    int nbPieces = len/BUFFER_SIZE; //(16 bits = 2 Bytes)
911    int remainingSize = len%BUFFER_SIZE;
912
913    for (int j=0;j<nbPieces;j++)
914    {
915       uint16_t *pbuffer  = (uint16_t*)buffer; //reinitialize pbuffer
916       for (int i = 0; i < BUFFER_SIZE/2; i++)
917       {
918          *pbuffer = *binArea16 >> 8 | *binArea16 << 8;
919          pbuffer++;
920          binArea16++;
921       }
922       os.write ( buffer, BUFFER_SIZE );
923    }
924    if ( remainingSize > 0)
925    {
926       uint16_t *pbuffer  = (uint16_t*)buffer; //reinitialize pbuffer
927       for (int i = 0; i < remainingSize/2; i++)
928       {
929          *pbuffer = *binArea16 >> 8 | *binArea16 << 8;
930          pbuffer++;
931          binArea16++;
932       }
933       os.write ( buffer, remainingSize );
934    }
935    return os;
936 #else
937    return os.write(reinterpret_cast<const char*>(val), len);
938 #endif
939 }
940
941 //-------------------------------------------------------------------------
942 // Protected
943
944 //-------------------------------------------------------------------------
945 // Private
946 /**
947  * \brief   Return the IP adress of the machine writting the DICOM image
948  */
949 std::string Util::GetIPAddress()
950 {
951    // This is a rip from 
952    // http://www.codeguru.com/Cpp/I-N/internet/network/article.php/c3445/
953 #ifndef HOST_NAME_MAX
954    // SUSv2 guarantees that `Host names are limited to 255 bytes'.
955    // POSIX 1003.1-2001 guarantees that `Host names (not including the
956    // terminating NUL) are limited to HOST_NAME_MAX bytes'.
957 #define HOST_NAME_MAX 255
958    // In this case we should maybe check the string was not truncated.
959    // But I don't known how to check that...
960 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
961    // with WinSock DLL we need to initialize the WinSock before using gethostname
962    WORD wVersionRequested = MAKEWORD(1,0);
963    WSADATA WSAData;
964    int err = WSAStartup(wVersionRequested,&WSAData);
965    if (err != 0)
966    {
967       // Tell the user that we could not find a usable
968       // WinSock DLL.
969       WSACleanup();
970       return "127.0.0.1";
971    }
972 #endif
973   
974 #endif //HOST_NAME_MAX
975
976    std::string str;
977    char szHostName[HOST_NAME_MAX+1];
978    int r = gethostname(szHostName, HOST_NAME_MAX);
979  
980    if( r == 0 )
981    {
982       // Get host adresses
983       struct hostent *pHost = gethostbyname(szHostName);
984  
985       for( int i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
986       {
987          for( int j = 0; j<pHost->h_length; j++ )
988          {
989             if( j > 0 ) str += ".";
990  
991             str += Util::Format("%u", 
992                 (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);
993          }
994          // str now contains one local IP address 
995  
996 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
997    WSACleanup();
998 #endif
999
1000       }
1001    }
1002    // If an error occur r == -1
1003    // Most of the time it will return 127.0.0.1...
1004    return str;
1005 }
1006
1007 //-------------------------------------------------------------------------
1008 } // end namespace gdcm
1009