1 /*=========================================================================
4 Module: $RCSfile: gdcmUtil.cxx,v $
6 Date: $Date: 2006/01/10 15:54:03 $
7 Version: $Revision: 1.182 $
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.
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.
17 =========================================================================*/
20 #include "gdcmDebug.h"
23 #include <stdarg.h> // for va_list
25 // For GetCurrentDate, GetCurrentTime
27 #include <sys/types.h>
30 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
31 #include <sys/timeb.h>
36 #include <stdarg.h> //only included in implementation file
37 #include <stdio.h> //only included in implementation file
39 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
40 #include <winsock.h> // for gethostname and gethostbyname and GetTickCount...
41 // I haven't find a way to determine wether we need to under GetCurrentTime or not...
42 // I think the best solution would simply to get rid of this problematic function
43 // and use a 'less' common name...
44 #if !defined(__BORLANDC__) || (__BORLANDC__ >= 0x0560)
48 #include <unistd.h> // for gethostname
49 #include <netdb.h> // for gethostbyname
60 #include <sys/types.h>
63 #ifdef CMAKE_HAVE_SYS_IOCTL_H
64 #include <sys/ioctl.h> // For SIOCGIFCONF on Linux
66 #ifdef CMAKE_HAVE_SYS_SOCKET_H
67 #include <sys/socket.h>
69 #ifdef CMAKE_HAVE_SYS_SOCKIO_H
70 #include <sys/sockio.h> // For SIOCGIFCONF on SunOS
72 #ifdef CMAKE_HAVE_NET_IF_H
75 #ifdef CMAKE_HAVE_NETINET_IN_H
76 #include <netinet/in.h> //For IPPROTO_IP
78 #ifdef CMAKE_HAVE_NET_IF_DL_H
79 #include <net/if_dl.h>
81 #if defined(CMAKE_HAVE_NET_IF_ARP_H) && defined(__sun)
82 // This is absolutely necessary on SunOS
83 #include <net/if_arp.h>
86 // For GetCurrentThreadID()
88 #include <sys/types.h>
89 #include <linux/unistd.h>
97 //-------------------------------------------------------------------------
98 const std::string Util::GDCM_UID = "1.2.826.0.1.3680043.2.1143";
99 std::string Util::RootUID = GDCM_UID;
101 * File Meta Information Version (0002,0001) shall contain a two byte OB
102 * value consisting of a 0x00 byte, followed by 0x01 byte, and not the
103 * value 0x0001 encoded as a little endian 16 bit short value,
104 * which would be the other way around...
106 const uint16_t Util::FMIV = 0x0100;
107 uint8_t *Util::FileMetaInformationVersion = (uint8_t *)&FMIV;
108 std::string Util::GDCM_MAC_ADRESS = GetMACAddress();
110 //-------------------------------------------------------------------------
113 * \brief Provide a better 'c++' approach for sprintf
114 * For example c code is:
115 * char result[2048]; // hope 2048 is enough
116 * sprintf(result, "%04x|%04x", group , elem);
119 * std::ostringstream buf;
120 * buf << std::right << std::setw(4) << std::setfill('0') << std::hex
121 * << group << "|" << std::right << std::setw(4) << std::setfill('0')
122 * << std::hex << elem;
127 * result = gdcm::Util::Format("%04x|%04x", group , elem);
129 std::string Util::Format(const char *format, ...)
131 char buffer[2048]; // hope 2048 is enough
133 va_start(args, format);
134 vsprintf(buffer, format, args); //might be a security flaw
135 va_end(args); // Each invocation of va_start should be matched
136 // by a corresponding invocation of va_end
137 // args is then 'undefined'
143 * \brief Because not available in C++ (?)
144 * @param str string to check
145 * @param tokens std::vector to receive the tokenized substrings
146 * @param delimiters string containing the character delimitors
149 void Util::Tokenize (const std::string &str,
150 std::vector<std::string> &tokens,
151 const std::string &delimiters)
153 std::string::size_type lastPos = str.find_first_not_of(delimiters,0);
154 std::string::size_type pos = str.find_first_of (delimiters,lastPos);
155 while (std::string::npos != pos || std::string::npos != lastPos)
157 tokens.push_back(str.substr(lastPos, pos - lastPos));
158 lastPos = str.find_first_not_of(delimiters, pos);
159 pos = str.find_first_of (delimiters, lastPos);
164 * \brief Because not available in C++ (?)
165 * Counts the number of occurences of a substring within a string
166 * @param str string to check
167 * @param subStr substring to count
170 int Util::CountSubstring (const std::string &str,
171 const std::string &subStr)
173 int count = 0; // counts how many times it appears
174 std::string::size_type x = 0; // The index position in the string
178 x = str.find(subStr,x); // Find the substring
179 if (x != std::string::npos) // If present
181 count++; // increase the count
182 x += subStr.length(); // Skip this word
185 while (x != std::string::npos);// Carry on until not present
191 * \brief Checks whether a 'string' is printable or not (in order
192 * to avoid corrupting the terminal of invocation when printing)
193 * @param s string to check
195 bool Util::IsCleanString(std::string const &s)
197 for(unsigned int i=0; i<s.size(); i++)
199 if (!isprint((unsigned char)s[i]) )
208 * \brief Checks whether an 'area' is printable or not (in order
209 * to avoid corrupting the terminal of invocation when printing)
210 * @param s area to check (uint8_t is just for prototyping. feel free to cast)
211 * @param l area length to check
213 bool Util::IsCleanArea(uint8_t *s, int l)
215 for( int i=0; i<l; i++)
217 if (!isprint((unsigned char)s[i]) )
225 * \brief Weed out a string from the non-printable characters (in order
226 * to avoid corrupting the terminal of invocation when printing)
227 * @param s string to check (uint8_t is just for prototyping. feel free to cast)
229 std::string Util::CreateCleanString(std::string const &s)
233 for(unsigned int i=0; i<str.size(); i++)
235 if (!isprint((unsigned char)str[i]) )
243 if (!isprint((unsigned char)s[str.size()-1]) )
245 if (s[str.size()-1] == 0 )
247 str[str.size()-1] = ' ';
256 * \brief Weed out a string from the non-printable characters (in order
257 * to avoid corrupting the terminal of invocation when printing)
258 * @param s area to process (uint8_t is just for prototyping. feel free to cast)
259 * @param l area length to check
261 std::string Util::CreateCleanString(uint8_t *s, int l)
265 for( int i=0; i<l; i++)
267 if (!isprint((unsigned char)s[i]) )
273 str = str + (char )s[i];
280 * \brief Add a SEPARATOR to the end of the name if necessary
281 * @param pathname file/directory name to normalize
283 std::string Util::NormalizePath(std::string const &pathname)
286 const char SEPARATOR_X = '/';
287 const char SEPARATOR_WIN = '\\';
289 const std::string SEPARATOR = "\\";
291 const std::string SEPARATOR = "/";
294 std::string name = pathname;
295 int size = name.size();
297 // if ( name[size-1] != SEPARATOR_X && name[size-1] != SEPARATOR_WIN )
298 if ( name[size-1] != GDCM_FILESEPARATOR )
300 name += GDCM_FILESEPARATOR;
306 * \brief Get the (directory) path from a full path file name
307 * @param fullName file/directory name to extract Path from
309 std::string Util::GetPath(std::string const &fullName)
311 std::string res = fullName;
314 int pos1 = res.rfind("/");
315 int pos2 = res.rfind("\\");
325 int pos = res.rfind(GDCM_FILESEPARATOR);
331 * \brief Get the (last) name of a full path file name
332 * @param fullName file/directory name to extract end name from
334 std::string Util::GetName(std::string const &fullName)
336 std::string filename = fullName;
338 std::string::size_type slash_pos = filename.rfind("/");
339 std::string::size_type backslash_pos = filename.rfind("\\");
340 // At least with my gcc4.0.1, unfound char results in pos =4294967295 ...
341 //slash_pos = slash_pos > backslash_pos ? slash_pos : backslash_pos;
342 slash_pos = slash_pos < backslash_pos ? slash_pos : backslash_pos;
344 std::string::size_type slash_pos = filename.rfind(GDCM_FILESEPARATOR);
345 if (slash_pos != std::string::npos )
347 return filename.substr(slash_pos + 1);
356 * \brief Get the current date of the system in a dicom string
358 std::string Util::GetCurrentDate()
363 strftime(tmp,512,"%Y%m%d", localtime(&tloc) );
368 * \brief Get the current time of the system in a dicom string
370 std::string Util::GetCurrentTime()
375 strftime(tmp,512,"%H%M%S", localtime(&tloc) );
380 * \brief Get both the date and time at the same time to avoid problem
381 * around midnight where the two calls could be before and after midnight
383 std::string Util::GetCurrentDateTime()
389 // We need implementation specific functions to obtain millisecond precision
390 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
394 milliseconds = tb.millitm;
397 gettimeofday (&tv, NULL);
399 // Compute milliseconds from microseconds.
400 milliseconds = tv.tv_usec / 1000;
402 // Obtain the time of day, and convert it to a tm struct.
403 struct tm *ptm = localtime (&timep);
404 // Format the date and time, down to a single second.
405 strftime (tmp, sizeof (tmp), "%Y%m%d%H%M%S", ptm);
408 // Don't use Util::Format to accelerate execution of code
410 sprintf(tmpAll,"%s%03ld",tmp,milliseconds);
415 unsigned int Util::GetCurrentThreadID()
417 // FIXME the implementation is far from complete
418 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
419 return (unsigned int)GetCurrentThreadId();
423 // Doesn't work on fedora, but is in the man page...
424 //return (unsigned int)gettid();
427 return (unsigned int)thr_self();
429 //default implementation
436 unsigned int Util::GetCurrentProcessID()
438 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
439 // NOTE: There is also a _getpid()...
440 return (unsigned int)GetCurrentProcessId();
442 // get process identification, POSIX
443 return (unsigned int)getpid();
448 * \brief tells us whether the processor we are working with is BigEndian or not
450 bool Util::IsCurrentProcessorBigEndian()
452 #if defined(GDCM_WORDS_BIGENDIAN)
460 * \brief Create a /DICOM/ string:
461 * It should a of even length (no odd length ever)
462 * It can contain as many (if you are reading this from your
463 * editor the following character is backslash followed by zero
464 * that needed to be escaped with an extra backslash for doxygen) \\0
467 std::string Util::DicomString(const char *s, size_t l)
469 std::string r(s, s+l);
470 gdcmAssertMacro( !(r.size() % 2) ); // == basically 'l' is even
475 * \brief Create a /DICOM/ string:
476 * It should a of even length (no odd length ever)
477 * It can contain as many (if you are reading this from your
478 * editor the following character is backslash followed by zero
479 * that needed to be escaped with an extra backslash for doxygen) \\0
481 * This function is similar to DicomString(const char*),
482 * except it doesn't take a length.
483 * It only pad with a null character if length is odd
485 std::string Util::DicomString(const char *s)
487 size_t l = strlen(s);
492 std::string r(s, s+l);
493 gdcmAssertMacro( !(r.size() % 2) );
498 * \brief Safely check the equality of two Dicom String:
499 * - Both strings should be of even length
500 * - We allow padding of even length string by either
501 * a null character of a space
503 bool Util::DicomStringEqual(const std::string &s1, const char *s2)
505 // s2 is the string from the DICOM reference e.g. : 'MONOCHROME1'
506 std::string s1_even = s1; //Never change input parameter
507 std::string s2_even = DicomString( s2 );
508 if ( s1_even[s1_even.size()-1] == ' ' )
510 s1_even[s1_even.size()-1] = '\0'; //replace space character by null
512 return s1_even == s2_even;
516 * \brief Safely compare two Dicom String:
517 * - Both strings should be of even length
518 * - We allow padding of even length string by either
519 * a null character of a space
521 bool Util::CompareDicomString(const std::string &s1, const char *s2, int op)
523 // s2 is the string from the DICOM reference e.g. : 'MONOCHROME1'
524 std::string s1_even = s1; //Never change input parameter
525 std::string s2_even = DicomString( s2 );
526 if ( s1_even[s1_even.size()-1] == ' ' )
528 s1_even[s1_even.size()-1] = '\0'; //replace space character by null
533 return s1_even == s2_even;
534 case GDCM_DIFFERENT :
535 return s1_even != s2_even;
537 return s1_even > s2_even;
538 case GDCM_GREATEROREQUAL :
539 return s1_even >= s2_even;
541 return s1_even < s2_even;
542 case GDCM_LESSOREQUAL :
543 return s1_even <= s2_even;
545 gdcmDebugMacro(" Wrong operator : " << op);
551 typedef BOOL(WINAPI * pSnmpExtensionInit) (
552 IN DWORD dwTimeZeroReference,
553 OUT HANDLE * hPollForTrapEvent,
554 OUT AsnObjectIdentifier * supportedView);
556 typedef BOOL(WINAPI * pSnmpExtensionTrap) (
557 OUT AsnObjectIdentifier * enterprise,
558 OUT AsnInteger * genericTrap,
559 OUT AsnInteger * specificTrap,
560 OUT AsnTimeticks * timeStamp,
561 OUT RFC1157VarBindList * variableBindings);
563 typedef BOOL(WINAPI * pSnmpExtensionQuery) (
565 IN OUT RFC1157VarBindList * variableBindings,
566 OUT AsnInteger * errorStatus,
567 OUT AsnInteger * errorIndex);
569 typedef BOOL(WINAPI * pSnmpExtensionInitEx) (
570 OUT AsnObjectIdentifier * supportedView);
573 /// \brief gets current M.A.C adress (for internal use only)
574 int GetMacAddrSys ( unsigned char *addr );
575 int GetMacAddrSys ( unsigned char *addr )
579 if ( (WSAStartup(MAKEWORD(2, 0), &WinsockData)) != 0 )
581 std::cerr << "in Get MAC Adress (internal) : This program requires Winsock 2.x!"
586 HANDLE PollForTrapEvent;
587 AsnObjectIdentifier SupportedView;
588 UINT OID_ifEntryType[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 3 };
589 UINT OID_ifEntryNum[] = { 1, 3, 6, 1, 2, 1, 2, 1 };
590 UINT OID_ipMACEntAddr[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 6 };
591 AsnObjectIdentifier MIB_ifMACEntAddr = {
592 sizeof(OID_ipMACEntAddr) / sizeof(UINT), OID_ipMACEntAddr };
593 AsnObjectIdentifier MIB_ifEntryType = {
594 sizeof(OID_ifEntryType) / sizeof(UINT), OID_ifEntryType };
595 AsnObjectIdentifier MIB_ifEntryNum = {
596 sizeof(OID_ifEntryNum) / sizeof(UINT), OID_ifEntryNum };
597 RFC1157VarBindList varBindList;
598 RFC1157VarBind varBind[2];
599 AsnInteger errorStatus;
600 AsnInteger errorIndex;
601 AsnObjectIdentifier MIB_NULL = { 0, 0 };
606 // Load the SNMP dll and get the addresses of the functions necessary
607 HINSTANCE m_hInst = LoadLibrary("inetmib1.dll");
608 if (m_hInst < (HINSTANCE) HINSTANCE_ERROR)
612 pSnmpExtensionInit m_Init =
613 (pSnmpExtensionInit) GetProcAddress(m_hInst, "SnmpExtensionInit");
614 pSnmpExtensionQuery m_Query =
615 (pSnmpExtensionQuery) GetProcAddress(m_hInst, "SnmpExtensionQuery");
616 m_Init(GetTickCount(), &PollForTrapEvent, &SupportedView);
618 /* Initialize the variable list to be retrieved by m_Query */
619 varBindList.list = varBind;
620 varBind[0].name = MIB_NULL;
621 varBind[1].name = MIB_NULL;
623 // Copy in the OID to find the number of entries in the
625 varBindList.len = 1; // Only retrieving one item
626 SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryNum);
627 m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
629 // printf("# of adapters in this system : %i\n",
630 // varBind[0].value.asnValue.number);
633 // Copy in the OID of ifType, the type of interface
634 SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryType);
636 // Copy in the OID of ifPhysAddress, the address
637 SNMP_oidcpy(&varBind[1].name, &MIB_ifMACEntAddr);
641 // Submit the query. Responses will be loaded into varBindList.
642 // We can expect this call to succeed a # of times corresponding
643 // to the # of adapters reported to be in the system
644 ret = m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
652 // Confirm that the proper type has been returned
653 ret = SNMP_oidncmp(&varBind[0].name, &MIB_ifEntryType,
654 MIB_ifEntryType.idLength);
659 dtmp = varBind[0].value.asnValue.number;
661 // Type 6 describes ethernet interfaces
664 // Confirm that we have an address here
665 ret = SNMP_oidncmp(&varBind[1].name, &MIB_ifMACEntAddr,
666 MIB_ifMACEntAddr.idLength);
667 if ( !ret && varBind[1].value.asnValue.address.stream != NULL )
669 if ( (varBind[1].value.asnValue.address.stream[0] == 0x44)
670 && (varBind[1].value.asnValue.address.stream[1] == 0x45)
671 && (varBind[1].value.asnValue.address.stream[2] == 0x53)
672 && (varBind[1].value.asnValue.address.stream[3] == 0x54)
673 && (varBind[1].value.asnValue.address.stream[4] == 0x00) )
675 // Ignore all dial-up networking adapters
676 std::cerr << "in Get MAC Adress (internal) : Interface #"
677 << j << " is a DUN adapter\n";
680 if ( (varBind[1].value.asnValue.address.stream[0] == 0x00)
681 && (varBind[1].value.asnValue.address.stream[1] == 0x00)
682 && (varBind[1].value.asnValue.address.stream[2] == 0x00)
683 && (varBind[1].value.asnValue.address.stream[3] == 0x00)
684 && (varBind[1].value.asnValue.address.stream[4] == 0x00)
685 && (varBind[1].value.asnValue.address.stream[5] == 0x00) )
687 // Ignore NULL addresses returned by other network
689 std::cerr << "in Get MAC Adress (internal) : Interface #"
690 << j << " is a NULL address\n";
693 memcpy( addr, varBind[1].value.asnValue.address.stream, 6);
700 SNMP_FreeVarBind(&varBind[0]);
701 SNMP_FreeVarBind(&varBind[1]);
703 #endif //Win32 version
706 // implementation for POSIX system
707 #if defined(CMAKE_HAVE_NET_IF_ARP_H) && defined(__sun)
708 //The POSIX version is broken anyway on Solaris, plus would require full
710 struct arpreq parpreq;
711 struct sockaddr_in *psa;
712 struct hostent *phost;
713 char hostname[MAXHOSTNAMELEN];
717 if (gethostname(hostname, MAXHOSTNAMELEN) != 0 )
719 perror("in Get MAC Adress (internal) : gethostname");
722 phost = gethostbyname(hostname);
723 paddrs = phost->h_addr_list;
725 sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
728 perror("in Get MAC Adress (internal) : sock");
731 memset(&parpreq, 0, sizeof(struct arpreq));
732 psa = (struct sockaddr_in *) &parpreq.arp_pa;
734 memset(psa, 0, sizeof(struct sockaddr_in));
735 psa->sin_family = AF_INET;
736 memcpy(&psa->sin_addr, *paddrs, sizeof(struct in_addr));
738 status = ioctl(sock, SIOCGARP, &parpreq);
741 perror("in Get MAC Adress (internal) : SIOCGARP");
744 memcpy(addr, parpreq.arp_ha.sa_data, 6);
748 #ifdef CMAKE_HAVE_NET_IF_H
750 struct ifreq ifr, *ifrp;
755 #if defined(AF_LINK) && (!defined(SIOCGIFHWADDR) && !defined(SIOCGENADDR))
756 struct sockaddr_dl *sdlp;
760 // BSD 4.4 defines the size of an ifreq to be
761 // max(sizeof(ifreq), sizeof(ifreq.ifr_name)+ifreq.ifr_addr.sa_len
762 // However, under earlier systems, sa_len isn't present, so the size is
763 // just sizeof(struct ifreq)
764 // We should investigate the use of SIZEOF_ADDR_IFREQ
768 #define max(a,b) ((a) > (b) ? (a) : (b))
770 #define ifreq_size(i) max(sizeof(struct ifreq),\
771 sizeof((i).ifr_name)+(i).ifr_addr.sa_len)
773 #define ifreq_size(i) sizeof(struct ifreq)
774 #endif // HAVE_SA_LEN
776 if ( (sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) < 0 )
780 memset(buf, 0, sizeof(buf));
781 ifc.ifc_len = sizeof(buf);
783 if (ioctl (sd, SIOCGIFCONF, (char *)&ifc) < 0)
789 for (i = 0; i < n; i+= ifreq_size(*ifrp) )
791 ifrp = (struct ifreq *)((char *) ifc.ifc_buf+i);
792 strncpy(ifr.ifr_name, ifrp->ifr_name, IFNAMSIZ);
794 if (ioctl(sd, SIOCGIFHWADDR, &ifr) < 0)
796 a = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
799 // In theory this call should also work on Sun Solaris, but apparently
800 // SIOCGENADDR is not implemented properly thus the call
801 // ioctl(sd, SIOCGENADDR, &ifr) always returns errno=2
802 // (No such file or directory)
803 // Furthermore the DLAPI seems to require full root access
804 if (ioctl(sd, SIOCGENADDR, &ifr) < 0)
806 a = (unsigned char *) ifr.ifr_enaddr;
809 sdlp = (struct sockaddr_dl *) &ifrp->ifr_addr;
810 if ((sdlp->sdl_family != AF_LINK) || (sdlp->sdl_alen != 6))
812 a = (unsigned char *) &sdlp->sdl_data[sdlp->sdl_nlen];
814 perror("in Get MAC Adress (internal) : No way to access hardware");
818 #endif // SIOCGENADDR
819 #endif // SIOCGIFHWADDR
820 if (!a[0] && !a[1] && !a[2] && !a[3] && !a[4] && !a[5]) continue;
831 // Not implemented platforms (or no cable !)
832 perror("in Get MAC Adress (internal) : There was a configuration problem (or no cable !) on your plateform");
839 * \brief Mini function to return the last digit from a number express in base 256
840 * pre condition data contain an array of 6 unsigned char
841 * post condition carry contain the last digit
843 inline int getlastdigit(unsigned char *data)
845 int extended, carry = 0;
848 extended = (carry << 8) + data[i];
849 data[i] = extended / 10;
850 carry = extended % 10;
856 * \brief Encode the mac address on a fixed length string of 15 characters.
857 * we save space this way.
859 std::string Util::GetMACAddress()
861 // This code is the result of a long internet search to find something
862 // as compact as possible (not OS independant). We only have to separate
863 // 3 OS: Win32, SunOS and 'real' POSIX
864 // http://groups-beta.google.com/group/comp.unix.solaris/msg/ad36929d783d63be
865 // http://bdn.borland.com/article/0,1410,26040,00.html
866 unsigned char addr[6];
868 int stat = GetMacAddrSys(addr);
871 // We need to convert a 6 digit number from base 256 to base 10, using integer
872 // would requires a 48bits one. To avoid this we have to reimplement the div + modulo
879 res = getlastdigit(addr);
880 sres.insert(sres.begin(), '0' + res);
881 zero = (addr[0] == 0) && (addr[1] == 0) && (addr[2] == 0)
882 && (addr[3] == 0) && (addr[4] == 0) && (addr[5] == 0);
889 gdcmStaticWarningMacro("Problem in finding the MAC Address");
895 * \brief Creates a new UID. As stipulated in the DICOM ref
896 * each time a DICOM image is created it should have
897 * a unique identifier (URI)
898 * @param root is the DICOM prefix assigned by IOS group
900 std::string Util::CreateUniqueUID(const std::string &root)
906 // gdcm UID prefix, as supplied by http://www.medicalconnections.co.uk
914 // A root was specified use it to forge our new UID:
916 //append += Util::GetMACAddress(); // to save CPU time
917 append += Util::GDCM_MAC_ADRESS;
919 append += Util::GetCurrentDateTime();
921 //Also add a mini random number just in case:
923 int r = (int) (100.0*rand()/RAND_MAX);
924 // Don't use Util::Format to accelerate the execution
925 sprintf(tmp,"%02d", r);
928 // If append is too long we need to rehash it
929 if ( (prefix + append).size() > 64 )
931 gdcmStaticErrorMacro( "Size of UID is too long." );
932 // we need a hash function to truncate this number
933 // if only md5 was cross plateform
937 return prefix + append;
940 void Util::SetRootUID(const std::string &root)
948 const std::string &Util::GetRootUID()
953 //-------------------------------------------------------------------------
955 * \brief binary_write binary_write
956 * @param os ostream to write to
957 * @param val 16 bits value to write
959 std::ostream &binary_write(std::ostream &os, const uint16_t &val)
961 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
963 swap = ( val << 8 | val >> 8 );
965 return os.write(reinterpret_cast<const char*>(&swap), 2);
967 return os.write(reinterpret_cast<const char*>(&val), 2);
968 #endif //GDCM_WORDS_BIGENDIAN
972 * \brief binary_write binary_write
973 * @param os ostream to write to
974 * @param val 32 bits value to write
976 std::ostream &binary_write(std::ostream &os, const uint32_t &val)
978 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
980 swap = ( (val<<24) | ((val<<8) & 0x00ff0000) |
981 ((val>>8) & 0x0000ff00) | (val>>24) );
982 return os.write(reinterpret_cast<const char*>(&swap), 4);
984 return os.write(reinterpret_cast<const char*>(&val), 4);
985 #endif //GDCM_WORDS_BIGENDIAN
990 * \brief binary_write binary_write
991 * @param os ostream to write to
992 * @param val double (64 bits) value to write
994 std::ostream &binary_write(std::ostream &os, const double &val)
996 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
999 char *beg = (char *)&swap;
1000 char *end = beg + 7;
1002 for (unsigned int i = 0; i<7; i++)
1010 return os.write(reinterpret_cast<const char*>(&swap), 8);
1012 return os.write(reinterpret_cast<const char*>(&val), 8);
1013 #endif //GDCM_WORDS_BIGENDIAN
1018 * \brief binary_write binary_write
1019 * @param os ostream to write to
1020 * @param val 8 bits characters aray to write
1022 std::ostream &binary_write(std::ostream &os, const char *val)
1024 return os.write(val, strlen(val));
1028 * \brief binary_write binary_write
1029 * @param os ostream to write to
1030 * @param val std::string value to write
1032 std::ostream &binary_write(std::ostream &os, std::string const &val)
1034 return os.write(val.c_str(), val.size());
1038 * \brief binary_write binary_write
1039 * @param os ostream to write to
1040 * @param val 8 bits 'characters' aray to write
1041 * @param len length of the 'value' to be written
1043 std::ostream &binary_write(std::ostream &os, const uint8_t *val, size_t len)
1045 // We are writting sizeof(char) thus no need to swap bytes
1046 return os.write(reinterpret_cast<const char*>(val), len);
1050 * \brief binary_write binary_write
1051 * @param os ostream to write to
1052 * @param val 16 bits words aray to write
1053 * @param len length (in bytes) of the 'value' to be written
1055 std::ostream &binary_write(std::ostream &os, const uint16_t *val, size_t len)
1057 // This is tricky since we are writting two bytes buffer.
1058 // Be carefull with little endian vs big endian.
1059 // Also this other trick is to allocate a small (efficient) buffer that store
1060 // intermediate result before writting it.
1061 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
1062 const int BUFFER_SIZE = 4096;
1063 static char buffer[BUFFER_SIZE];
1064 uint16_t *binArea16 = (uint16_t*)val; //for the const
1066 // how many BUFFER_SIZE long pieces in binArea ?
1067 int nbPieces = len/BUFFER_SIZE; //(16 bits = 2 Bytes)
1068 int remainingSize = len%BUFFER_SIZE;
1070 for (int j=0;j<nbPieces;j++)
1072 uint16_t *pbuffer = (uint16_t*)buffer; //reinitialize pbuffer
1073 for (int i = 0; i < BUFFER_SIZE/2; i++)
1075 *pbuffer = *binArea16 >> 8 | *binArea16 << 8;
1079 os.write ( buffer, BUFFER_SIZE );
1081 if ( remainingSize > 0)
1083 uint16_t *pbuffer = (uint16_t*)buffer; //reinitialize pbuffer
1084 for (int i = 0; i < remainingSize/2; i++)
1086 *pbuffer = *binArea16 >> 8 | *binArea16 << 8;
1090 os.write ( buffer, remainingSize );
1094 return os.write(reinterpret_cast<const char*>(val), len);
1098 //-------------------------------------------------------------------------
1101 //-------------------------------------------------------------------------
1104 * \brief Return the IP adress of the machine writting the DICOM image
1106 std::string Util::GetIPAddress()
1108 // This is a rip from
1109 // http://www.codeguru.com/Cpp/I-N/internet/network/article.php/c3445/
1110 #ifndef HOST_NAME_MAX
1111 // SUSv2 guarantees that `Host names are limited to 255 bytes'.
1112 // POSIX 1003.1-2001 guarantees that `Host names (not including the
1113 // terminating NUL) are limited to HOST_NAME_MAX bytes'.
1114 #define HOST_NAME_MAX 255
1115 // In this case we should maybe check the string was not truncated.
1116 // But I don't known how to check that...
1117 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
1118 // with WinSock DLL we need to initialize the WinSock before using gethostname
1119 WORD wVersionRequested = MAKEWORD(1,0);
1121 int err = WSAStartup(wVersionRequested,&WSAData);
1124 // Tell the user that we could not find a usable
1131 #endif //HOST_NAME_MAX
1134 char szHostName[HOST_NAME_MAX+1];
1135 int r = gethostname(szHostName, HOST_NAME_MAX);
1139 // Get host adresses
1140 struct hostent *pHost = gethostbyname(szHostName);
1142 for( int i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
1144 for( int j = 0; j<pHost->h_length; j++ )
1146 if ( j > 0 ) str += ".";
1148 str += Util::Format("%u",
1149 (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);
1151 // str now contains one local IP address
1153 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
1159 // If an error occur r == -1
1160 // Most of the time it will return 127.0.0.1...
1164 void Util::hfpswap(double *a, double *b)
1172 //-------------------------------------------------------------------------
1173 } // end namespace gdcm