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