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