1 /*=========================================================================
4 Module: $RCSfile: gdcmUtil.cxx,v $
6 Date: $Date: 2005/11/03 14:04:43 $
7 Version: $Revision: 1.174 $
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 // For GetCurrentDate, GetCurrentTime
25 #include <sys/types.h>
28 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
29 #include <sys/timeb.h>
34 #include <stdarg.h> //only included in implementation file
35 #include <stdio.h> //only included in implementation file
37 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
38 #include <winsock.h> // for gethostname and gethostbyname and GetTickCount...
39 // I haven't find a way to determine wether we need to under GetCurrentTime or not...
40 // I think the best solution would simply to get rid of this problematic function
41 // and use a 'less' common name...
42 #if !defined(__BORLANDC__) || (__BORLANDC__ >= 0x0560)
46 #include <unistd.h> // for gethostname
47 #include <netdb.h> // for gethostbyname
58 #include <sys/types.h>
61 #ifdef CMAKE_HAVE_SYS_IOCTL_H
62 #include <sys/ioctl.h> // For SIOCGIFCONF on Linux
64 #ifdef CMAKE_HAVE_SYS_SOCKET_H
65 #include <sys/socket.h>
67 #ifdef CMAKE_HAVE_SYS_SOCKIO_H
68 #include <sys/sockio.h> // For SIOCGIFCONF on SunOS
70 #ifdef CMAKE_HAVE_NET_IF_H
73 #ifdef CMAKE_HAVE_NETINET_IN_H
74 #include <netinet/in.h> //For IPPROTO_IP
76 #ifdef CMAKE_HAVE_NET_IF_DL_H
77 #include <net/if_dl.h>
79 #if defined(CMAKE_HAVE_NET_IF_ARP_H) && defined(__sun)
80 // This is absolutely necessary on SunOS
81 #include <net/if_arp.h>
84 // For GetCurrentThreadID()
86 #include <sys/types.h>
87 #include <linux/unistd.h>
95 //-------------------------------------------------------------------------
96 const std::string Util::GDCM_UID = "1.2.826.0.1.3680043.2.1143";
97 std::string Util::RootUID = GDCM_UID;
99 * File Meta Information Version (0002,0001) shall contain a two byte OB
100 * value consisting of a 0x00 byte, followed by 0x01 byte, and not the
101 * value 0x0001 encoded as a little endian 16 bit short value,
102 * which would be the other way around...
104 const uint16_t Util::FMIV = 0x0100;
105 uint8_t *Util::FileMetaInformationVersion = (uint8_t *)&FMIV;
106 std::string Util::GDCM_MAC_ADRESS = GetMACAddress();
108 //-------------------------------------------------------------------------
111 * \brief Provide a better 'c++' approach for sprintf
112 * For example c code is:
113 * char result[2048]; // hope 2048 is enough
114 * sprintf(result, "%04x|%04x", group , elem);
117 * std::ostringstream buf;
118 * buf << std::right << std::setw(4) << std::setfill('0') << std::hex
119 * << group << "|" << std::right << std::setw(4) << std::setfill('0')
120 * << std::hex << elem;
125 * result = gdcm::Util::Format("%04x|%04x", group , elem);
127 std::string Util::Format(const char *format, ...)
129 char buffer[2048]; // hope 2048 is enough
131 va_start(args, format);
132 vsprintf(buffer, format, args); //might be a security flaw
133 va_end(args); // Each invocation of va_start should be matched
134 // by a corresponding invocation of va_end
135 // args is then 'undefined'
141 * \brief Because not available in C++ (?)
142 * @param str string to check
143 * @param tokens std::vector to receive the tokenized substrings
144 * @param delimiters string containing the character delimitors
147 void Util::Tokenize (const std::string &str,
148 std::vector<std::string> &tokens,
149 const std::string &delimiters)
151 std::string::size_type lastPos = str.find_first_not_of(delimiters,0);
152 std::string::size_type pos = str.find_first_of (delimiters,lastPos);
153 while (std::string::npos != pos || std::string::npos != lastPos)
155 tokens.push_back(str.substr(lastPos, pos - lastPos));
156 lastPos = str.find_first_not_of(delimiters, pos);
157 pos = str.find_first_of (delimiters, lastPos);
162 * \brief Because not available in C++ (?)
163 * Counts the number of occurences of a substring within a string
164 * @param str string to check
165 * @param subStr substring to count
168 int Util::CountSubstring (const std::string &str,
169 const std::string &subStr)
171 int count = 0; // counts how many times it appears
172 std::string::size_type x = 0; // The index position in the string
176 x = str.find(subStr,x); // Find the substring
177 if (x != std::string::npos) // If present
179 count++; // increase the count
180 x += subStr.length(); // Skip this word
183 while (x != std::string::npos);// Carry on until not present
189 * \brief Checks whether a 'string' is printable or not (in order
190 * to avoid corrupting the terminal of invocation when printing)
191 * @param s string to check
193 bool Util::IsCleanString(std::string const &s)
195 //std::cout<< std::endl << s << std::endl;
196 for(unsigned int i=0; i<s.size(); i++)
198 if (!isprint((unsigned char)s[i]) )
207 * \brief Checks whether an 'area' is printable or not (in order
208 * to avoid corrupting the terminal of invocation when printing)
209 * @param s area to check (uint8_t is just for prototyping. feel free to cast)
210 * @param l area length to check
212 bool Util::IsCleanArea(uint8_t *s, int l)
214 for( int i=0; i<l; i++)
216 if (!isprint((unsigned char)s[i]) )
224 * \brief Weed out a string from the non-printable characters (in order
225 * to avoid corrupting the terminal of invocation when printing)
226 * @param s string to check (uint8_t is just for prototyping. feel free to cast)
228 std::string Util::CreateCleanString(std::string const &s)
232 for(unsigned int i=0; i<str.size(); i++)
234 if (!isprint((unsigned char)str[i]) )
242 if (!isprint((unsigned char)s[str.size()-1]) )
244 if (s[str.size()-1] == 0 )
246 str[str.size()-1] = ' ';
255 * \brief Weed out a string from the non-printable characters (in order
256 * to avoid corrupting the terminal of invocation when printing)
257 * @param s area to process (uint8_t is just for prototyping. feel free to cast)
258 * @param l area length to check
260 std::string Util::CreateCleanString(uint8_t *s, int l)
264 for( int i=0; i<l; i++)
266 if (!isprint((unsigned char)s[i]) )
272 str = str + (char )s[i];
279 * \brief Add a SEPARATOR to the end of the name is necessary
280 * @param pathname file/directory name to normalize
282 std::string Util::NormalizePath(std::string const &pathname)
284 const char SEPARATOR_X = '/';
285 const char SEPARATOR_WIN = '\\';
286 const std::string SEPARATOR = "/";
287 std::string name = pathname;
288 int size = name.size();
290 if ( name[size-1] != SEPARATOR_X && name[size-1] != SEPARATOR_WIN )
298 * \brief Get the (directory) path from a full path file name
299 * @param fullName file/directory name to extract Path from
301 std::string Util::GetPath(std::string const &fullName)
303 std::string res = fullName;
304 int pos1 = res.rfind("/");
305 int pos2 = res.rfind("\\");
319 * \brief Get the (last) name of a full path file name
320 * @param fullName file/directory name to extract end name from
322 std::string Util::GetName(std::string const &fullName)
324 std::string filename = fullName;
326 std::string::size_type slash_pos = filename.rfind("/");
327 std::string::size_type backslash_pos = filename.rfind("\\");
328 slash_pos = slash_pos > backslash_pos ? slash_pos : backslash_pos;
329 if (slash_pos != std::string::npos )
331 return filename.substr(slash_pos + 1);
340 * \brief Get the current date of the system in a dicom string
342 std::string Util::GetCurrentDate()
347 strftime(tmp,512,"%Y%m%d", localtime(&tloc) );
352 * \brief Get the current time of the system in a dicom string
354 std::string Util::GetCurrentTime()
359 strftime(tmp,512,"%H%M%S", localtime(&tloc) );
364 * \brief Get both the date and time at the same time to avoid problem
365 * around midnight where the two calls could be before and after midnight
367 std::string Util::GetCurrentDateTime()
373 // We need implementation specific functions to obtain millisecond precision
374 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
378 milliseconds = tb.millitm;
381 gettimeofday (&tv, NULL);
383 // Compute milliseconds from microseconds.
384 milliseconds = tv.tv_usec / 1000;
386 // Obtain the time of day, and convert it to a tm struct.
387 struct tm *ptm = localtime (&timep);
388 // Format the date and time, down to a single second.
389 strftime (tmp, sizeof (tmp), "%Y%m%d%H%M%S", ptm);
392 // Don't use Util::Format to accelerate execution of code
394 sprintf(tmpAll,"%s%03ld",tmp,milliseconds);
399 unsigned int Util::GetCurrentThreadID()
401 // FIXME the implementation is far from complete
402 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
403 return (unsigned int)GetCurrentThreadId();
407 // Doesn't work on fedora, but is in the man page...
408 //return (unsigned int)gettid();
411 return (unsigned int)thr_self();
413 //default implementation
420 unsigned int Util::GetCurrentProcessID()
422 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
423 // NOTE: There is also a _getpid()...
424 return (unsigned int)GetCurrentProcessId();
426 // get process identification, POSIX
427 return (unsigned int)getpid();
432 * \brief tells us whether the processor we are working with is BigEndian or not
434 bool Util::IsCurrentProcessorBigEndian()
436 #if defined(GDCM_WORDS_BIGENDIAN)
444 * \brief Create a /DICOM/ string:
445 * It should a of even length (no odd length ever)
446 * It can contain as many (if you are reading this from your
447 * editor the following character is backslash followed by zero
448 * that needed to be escaped with an extra backslash for doxygen) \\0
451 std::string Util::DicomString(const char *s, size_t l)
453 std::string r(s, s+l);
454 gdcmAssertMacro( !(r.size() % 2) ); // == basically 'l' is even
459 * \brief Create a /DICOM/ string:
460 * It should a of even length (no odd length ever)
461 * It can contain as many (if you are reading this from your
462 * editor the following character is backslash followed by zero
463 * that needed to be escaped with an extra backslash for doxygen) \\0
465 * This function is similar to DicomString(const char*),
466 * except it doesn't take a length.
467 * It only pad with a null character if length is odd
469 std::string Util::DicomString(const char *s)
471 size_t l = strlen(s);
476 std::string r(s, s+l);
477 gdcmAssertMacro( !(r.size() % 2) );
482 * \brief Safely check the equality of two Dicom String:
483 * - Both strings should be of even length
484 * - We allow padding of even length string by either a null
485 * character of a space
487 bool Util::DicomStringEqual(const std::string &s1, const char *s2)
489 // s2 is the string from the DICOM reference e.g. : 'MONOCHROME1'
490 std::string s1_even = s1; //Never change input parameter
491 std::string s2_even = DicomString( s2 );
492 if ( s1_even[s1_even.size()-1] == ' ' )
494 s1_even[s1_even.size()-1] = '\0'; //replace space character by null
496 return s1_even == s2_even;
500 * \brief Safely compare two Dicom String:
501 * - Both strings should be of even length
502 * - We allow padding of even length string by either a null
503 * character of a space
505 bool Util::CompareDicomString(const std::string &s1, const char *s2, int op)
507 // s2 is the string from the DICOM reference e.g. : 'MONOCHROME1'
508 std::string s1_even = s1; //Never change input parameter
509 std::string s2_even = DicomString( s2 );
510 if ( s1_even[s1_even.size()-1] == ' ' )
512 s1_even[s1_even.size()-1] = '\0'; //replace space character by null
517 return s1_even == s2_even;
518 case GDCM_DIFFERENT :
519 return s1_even != s2_even;
521 return s1_even > s2_even;
522 case GDCM_GREATEROREQUAL :
523 return s1_even >= s2_even;
525 return s1_even < s2_even;
526 case GDCM_LESSOREQUAL :
527 return s1_even <= s2_even;
529 gdcmDebugMacro(" Wrong operator : " << op);
535 typedef BOOL(WINAPI * pSnmpExtensionInit) (
536 IN DWORD dwTimeZeroReference,
537 OUT HANDLE * hPollForTrapEvent,
538 OUT AsnObjectIdentifier * supportedView);
540 typedef BOOL(WINAPI * pSnmpExtensionTrap) (
541 OUT AsnObjectIdentifier * enterprise,
542 OUT AsnInteger * genericTrap,
543 OUT AsnInteger * specificTrap,
544 OUT AsnTimeticks * timeStamp,
545 OUT RFC1157VarBindList * variableBindings);
547 typedef BOOL(WINAPI * pSnmpExtensionQuery) (
549 IN OUT RFC1157VarBindList * variableBindings,
550 OUT AsnInteger * errorStatus,
551 OUT AsnInteger * errorIndex);
553 typedef BOOL(WINAPI * pSnmpExtensionInitEx) (
554 OUT AsnObjectIdentifier * supportedView);
557 /// \brief gets current M.A.C adress (for internal use only)
558 int GetMacAddrSys ( unsigned char *addr );
559 int GetMacAddrSys ( unsigned char *addr )
563 if ( (WSAStartup(MAKEWORD(2, 0), &WinsockData)) != 0 )
565 std::cerr << "in Get MAC Adress (internal) : This program requires Winsock 2.x!"
570 HANDLE PollForTrapEvent;
571 AsnObjectIdentifier SupportedView;
572 UINT OID_ifEntryType[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 3 };
573 UINT OID_ifEntryNum[] = { 1, 3, 6, 1, 2, 1, 2, 1 };
574 UINT OID_ipMACEntAddr[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 6 };
575 AsnObjectIdentifier MIB_ifMACEntAddr = {
576 sizeof(OID_ipMACEntAddr) / sizeof(UINT), OID_ipMACEntAddr };
577 AsnObjectIdentifier MIB_ifEntryType = {
578 sizeof(OID_ifEntryType) / sizeof(UINT), OID_ifEntryType };
579 AsnObjectIdentifier MIB_ifEntryNum = {
580 sizeof(OID_ifEntryNum) / sizeof(UINT), OID_ifEntryNum };
581 RFC1157VarBindList varBindList;
582 RFC1157VarBind varBind[2];
583 AsnInteger errorStatus;
584 AsnInteger errorIndex;
585 AsnObjectIdentifier MIB_NULL = { 0, 0 };
590 // Load the SNMP dll and get the addresses of the functions necessary
591 HINSTANCE m_hInst = LoadLibrary("inetmib1.dll");
592 if (m_hInst < (HINSTANCE) HINSTANCE_ERROR)
596 pSnmpExtensionInit m_Init =
597 (pSnmpExtensionInit) GetProcAddress(m_hInst, "SnmpExtensionInit");
598 pSnmpExtensionQuery m_Query =
599 (pSnmpExtensionQuery) GetProcAddress(m_hInst, "SnmpExtensionQuery");
600 m_Init(GetTickCount(), &PollForTrapEvent, &SupportedView);
602 /* Initialize the variable list to be retrieved by m_Query */
603 varBindList.list = varBind;
604 varBind[0].name = MIB_NULL;
605 varBind[1].name = MIB_NULL;
607 // Copy in the OID to find the number of entries in the
609 varBindList.len = 1; // Only retrieving one item
610 SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryNum);
611 m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
613 // printf("# of adapters in this system : %i\n",
614 // varBind[0].value.asnValue.number);
617 // Copy in the OID of ifType, the type of interface
618 SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryType);
620 // Copy in the OID of ifPhysAddress, the address
621 SNMP_oidcpy(&varBind[1].name, &MIB_ifMACEntAddr);
625 // Submit the query. Responses will be loaded into varBindList.
626 // We can expect this call to succeed a # of times corresponding
627 // to the # of adapters reported to be in the system
628 ret = m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
636 // Confirm that the proper type has been returned
637 ret = SNMP_oidncmp(&varBind[0].name, &MIB_ifEntryType,
638 MIB_ifEntryType.idLength);
643 dtmp = varBind[0].value.asnValue.number;
645 // Type 6 describes ethernet interfaces
648 // Confirm that we have an address here
649 ret = SNMP_oidncmp(&varBind[1].name, &MIB_ifMACEntAddr,
650 MIB_ifMACEntAddr.idLength);
651 if ( !ret && varBind[1].value.asnValue.address.stream != NULL )
653 if ( (varBind[1].value.asnValue.address.stream[0] == 0x44)
654 && (varBind[1].value.asnValue.address.stream[1] == 0x45)
655 && (varBind[1].value.asnValue.address.stream[2] == 0x53)
656 && (varBind[1].value.asnValue.address.stream[3] == 0x54)
657 && (varBind[1].value.asnValue.address.stream[4] == 0x00) )
659 // Ignore all dial-up networking adapters
660 std::cerr << "in Get MAC Adress (internal) : Interface #"
661 << j << " is a DUN adapter\n";
664 if ( (varBind[1].value.asnValue.address.stream[0] == 0x00)
665 && (varBind[1].value.asnValue.address.stream[1] == 0x00)
666 && (varBind[1].value.asnValue.address.stream[2] == 0x00)
667 && (varBind[1].value.asnValue.address.stream[3] == 0x00)
668 && (varBind[1].value.asnValue.address.stream[4] == 0x00)
669 && (varBind[1].value.asnValue.address.stream[5] == 0x00) )
671 // Ignore NULL addresses returned by other network
673 std::cerr << "in Get MAC Adress (internal) : Interface #"
674 << j << " is a NULL address\n";
677 memcpy( addr, varBind[1].value.asnValue.address.stream, 6);
684 SNMP_FreeVarBind(&varBind[0]);
685 SNMP_FreeVarBind(&varBind[1]);
687 #endif //Win32 version
690 // implementation for POSIX system
691 #if defined(CMAKE_HAVE_NET_IF_ARP_H) && defined(__sun)
692 //The POSIX version is broken anyway on Solaris, plus would require full
694 struct arpreq parpreq;
695 struct sockaddr_in *psa;
696 struct hostent *phost;
697 char hostname[MAXHOSTNAMELEN];
701 if (gethostname(hostname, MAXHOSTNAMELEN) != 0 )
703 perror("in Get MAC Adress (internal) : gethostname");
706 phost = gethostbyname(hostname);
707 paddrs = phost->h_addr_list;
709 sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
712 perror("in Get MAC Adress (internal) : sock");
715 memset(&parpreq, 0, sizeof(struct arpreq));
716 psa = (struct sockaddr_in *) &parpreq.arp_pa;
718 memset(psa, 0, sizeof(struct sockaddr_in));
719 psa->sin_family = AF_INET;
720 memcpy(&psa->sin_addr, *paddrs, sizeof(struct in_addr));
722 status = ioctl(sock, SIOCGARP, &parpreq);
725 perror("in Get MAC Adress (internal) : SIOCGARP");
728 memcpy(addr, parpreq.arp_ha.sa_data, 6);
732 #ifdef CMAKE_HAVE_NET_IF_H
734 struct ifreq ifr, *ifrp;
739 #if defined(AF_LINK) && (!defined(SIOCGIFHWADDR) && !defined(SIOCGENADDR))
740 struct sockaddr_dl *sdlp;
744 // BSD 4.4 defines the size of an ifreq to be
745 // max(sizeof(ifreq), sizeof(ifreq.ifr_name)+ifreq.ifr_addr.sa_len
746 // However, under earlier systems, sa_len isn't present, so the size is
747 // just sizeof(struct ifreq)
748 // We should investigate the use of SIZEOF_ADDR_IFREQ
752 #define max(a,b) ((a) > (b) ? (a) : (b))
754 #define ifreq_size(i) max(sizeof(struct ifreq),\
755 sizeof((i).ifr_name)+(i).ifr_addr.sa_len)
757 #define ifreq_size(i) sizeof(struct ifreq)
758 #endif // HAVE_SA_LEN
760 if ( (sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) < 0 )
764 memset(buf, 0, sizeof(buf));
765 ifc.ifc_len = sizeof(buf);
767 if (ioctl (sd, SIOCGIFCONF, (char *)&ifc) < 0)
773 for (i = 0; i < n; i+= ifreq_size(*ifrp) )
775 ifrp = (struct ifreq *)((char *) ifc.ifc_buf+i);
776 strncpy(ifr.ifr_name, ifrp->ifr_name, IFNAMSIZ);
778 if (ioctl(sd, SIOCGIFHWADDR, &ifr) < 0)
780 a = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
783 // In theory this call should also work on Sun Solaris, but apparently
784 // SIOCGENADDR is not implemented properly thus the call
785 // ioctl(sd, SIOCGENADDR, &ifr) always returns errno=2
786 // (No such file or directory)
787 // Furthermore the DLAPI seems to require full root access
788 if (ioctl(sd, SIOCGENADDR, &ifr) < 0)
790 a = (unsigned char *) ifr.ifr_enaddr;
793 sdlp = (struct sockaddr_dl *) &ifrp->ifr_addr;
794 if ((sdlp->sdl_family != AF_LINK) || (sdlp->sdl_alen != 6))
796 a = (unsigned char *) &sdlp->sdl_data[sdlp->sdl_nlen];
798 perror("in Get MAC Adress (internal) : No way to access hardware");
802 #endif // SIOCGENADDR
803 #endif // SIOCGIFHWADDR
804 if (!a[0] && !a[1] && !a[2] && !a[3] && !a[4] && !a[5]) continue;
815 // Not implemented platforms (or no cable !)
816 perror("in Get MAC Adress (internal) : There was a configuration problem on your plateform");
823 * \brief Mini function to return the last digit from a number express in base 256
824 * pre condition data contain an array of 6 unsigned char
825 * post condition carry contain the last digit
827 inline int getlastdigit(unsigned char *data)
829 int extended, carry = 0;
832 extended = (carry << 8) + data[i];
833 data[i] = extended / 10;
834 carry = extended % 10;
840 * \brief Encode the mac address on a fixed lenght string of 15 characters.
841 * we save space this way.
843 std::string Util::GetMACAddress()
845 // This code is the result of a long internet search to find something
846 // as compact as possible (not OS independant). We only have to separate
847 // 3 OS: Win32, SunOS and 'real' POSIX
848 // http://groups-beta.google.com/group/comp.unix.solaris/msg/ad36929d783d63be
849 // http://bdn.borland.com/article/0,1410,26040,00.html
850 unsigned char addr[6];
852 int stat = GetMacAddrSys(addr);
855 // We need to convert a 6 digit number from base 256 to base 10, using integer
856 // would requires a 48bits one. To avoid this we have to reimplement the div + modulo
863 res = getlastdigit(addr);
864 sres.insert(sres.begin(), '0' + res);
865 zero = (addr[0] == 0) && (addr[1] == 0) && (addr[2] == 0)
866 && (addr[3] == 0) && (addr[4] == 0) && (addr[5] == 0);
873 gdcmWarningMacro("Problem in finding the MAC Address");
879 * \brief Creates a new UID. As stipulate in the DICOM ref
880 * each time a DICOM image is create it should have
881 * a unique identifier (URI)
882 * @param root is the DICOM prefix assigned by IOS group
884 std::string Util::CreateUniqueUID(const std::string &root)
890 // gdcm UID prefix, as supplied by http://www.medicalconnections.co.uk
898 // A root was specified use it to forge our new UID:
900 //append += Util::GetMACAddress(); // to save CPU time
901 append += Util::GDCM_MAC_ADRESS;
903 append += Util::GetCurrentDateTime();
905 //Also add a mini random number just in case:
907 int r = (int) (100.0*rand()/RAND_MAX);
908 // Don't use Util::Format to accelerate the execution
909 sprintf(tmp,"%02d", r);
912 // If append is too long we need to rehash it
913 if ( (prefix + append).size() > 64 )
915 gdcmErrorMacro( "Size of UID is too long." );
916 // we need a hash function to truncate this number
917 // if only md5 was cross plateform
921 return prefix + append;
924 void Util::SetRootUID(const std::string &root)
932 const std::string &Util::GetRootUID()
937 //-------------------------------------------------------------------------
939 * \brief binary_write binary_write
940 * @param os ostream to write to
941 * @param val 16 bits value to write
943 std::ostream &binary_write(std::ostream &os, const uint16_t &val)
945 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
947 swap = ( val << 8 | val >> 8 );
949 return os.write(reinterpret_cast<const char*>(&swap), 2);
951 return os.write(reinterpret_cast<const char*>(&val), 2);
952 #endif //GDCM_WORDS_BIGENDIAN
956 * \brief binary_write binary_write
957 * @param os ostream to write to
958 * @param val 32 bits value to write
960 std::ostream &binary_write(std::ostream &os, const uint32_t &val)
962 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
964 swap = ( (val<<24) | ((val<<8) & 0x00ff0000) |
965 ((val>>8) & 0x0000ff00) | (val>>24) );
966 return os.write(reinterpret_cast<const char*>(&swap), 4);
968 return os.write(reinterpret_cast<const char*>(&val), 4);
969 #endif //GDCM_WORDS_BIGENDIAN
974 * \brief binary_write binary_write
975 * @param os ostream to write to
976 * @param val double (64 bits) value to write
978 std::ostream &binary_write(std::ostream &os, const double &val)
980 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
983 char *beg = (char *)&swap;
986 for (unsigned int i = 0; i<7; i++)
994 return os.write(reinterpret_cast<const char*>(&swap), 8);
996 return os.write(reinterpret_cast<const char*>(&val), 8);
997 #endif //GDCM_WORDS_BIGENDIAN
1002 * \brief binary_write binary_write
1003 * @param os ostream to write to
1004 * @param val 8 bits characters aray to write
1006 std::ostream &binary_write(std::ostream &os, const char *val)
1008 return os.write(val, strlen(val));
1012 * \brief binary_write binary_write
1013 * @param os ostream to write to
1014 * @param val std::string value to write
1016 std::ostream &binary_write(std::ostream &os, std::string const &val)
1018 return os.write(val.c_str(), val.size());
1022 * \brief binary_write binary_write
1023 * @param os ostream to write to
1024 * @param val 8 bits 'characters' aray to write
1025 * @param len length of the 'value' to be written
1027 std::ostream &binary_write(std::ostream &os, const uint8_t *val, size_t len)
1029 // We are writting sizeof(char) thus no need to swap bytes
1030 return os.write(reinterpret_cast<const char*>(val), len);
1034 * \brief binary_write binary_write
1035 * @param os ostream to write to
1036 * @param val 16 bits words aray to write
1037 * @param len length (in bytes) of the 'value' to be written
1039 std::ostream &binary_write(std::ostream &os, const uint16_t *val, size_t len)
1041 // This is tricky since we are writting two bytes buffer.
1042 // Be carefull with little endian vs big endian.
1043 // Also this other trick is to allocate a small (efficient) buffer that store
1044 // intermediate result before writting it.
1045 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
1046 const int BUFFER_SIZE = 4096;
1047 static char buffer[BUFFER_SIZE];
1048 uint16_t *binArea16 = (uint16_t*)val; //for the const
1050 // how many BUFFER_SIZE long pieces in binArea ?
1051 int nbPieces = len/BUFFER_SIZE; //(16 bits = 2 Bytes)
1052 int remainingSize = len%BUFFER_SIZE;
1054 for (int j=0;j<nbPieces;j++)
1056 uint16_t *pbuffer = (uint16_t*)buffer; //reinitialize pbuffer
1057 for (int i = 0; i < BUFFER_SIZE/2; i++)
1059 *pbuffer = *binArea16 >> 8 | *binArea16 << 8;
1063 os.write ( buffer, BUFFER_SIZE );
1065 if ( remainingSize > 0)
1067 uint16_t *pbuffer = (uint16_t*)buffer; //reinitialize pbuffer
1068 for (int i = 0; i < remainingSize/2; i++)
1070 *pbuffer = *binArea16 >> 8 | *binArea16 << 8;
1074 os.write ( buffer, remainingSize );
1078 return os.write(reinterpret_cast<const char*>(val), len);
1082 //-------------------------------------------------------------------------
1085 //-------------------------------------------------------------------------
1088 * \brief Return the IP adress of the machine writting the DICOM image
1090 std::string Util::GetIPAddress()
1092 // This is a rip from
1093 // http://www.codeguru.com/Cpp/I-N/internet/network/article.php/c3445/
1094 #ifndef HOST_NAME_MAX
1095 // SUSv2 guarantees that `Host names are limited to 255 bytes'.
1096 // POSIX 1003.1-2001 guarantees that `Host names (not including the
1097 // terminating NUL) are limited to HOST_NAME_MAX bytes'.
1098 #define HOST_NAME_MAX 255
1099 // In this case we should maybe check the string was not truncated.
1100 // But I don't known how to check that...
1101 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
1102 // with WinSock DLL we need to initialize the WinSock before using gethostname
1103 WORD wVersionRequested = MAKEWORD(1,0);
1105 int err = WSAStartup(wVersionRequested,&WSAData);
1108 // Tell the user that we could not find a usable
1115 #endif //HOST_NAME_MAX
1118 char szHostName[HOST_NAME_MAX+1];
1119 int r = gethostname(szHostName, HOST_NAME_MAX);
1123 // Get host adresses
1124 struct hostent *pHost = gethostbyname(szHostName);
1126 for( int i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
1128 for( int j = 0; j<pHost->h_length; j++ )
1130 if ( j > 0 ) str += ".";
1132 str += Util::Format("%u",
1133 (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);
1135 // str now contains one local IP address
1137 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
1143 // If an error occur r == -1
1144 // Most of the time it will return 127.0.0.1...
1148 //-------------------------------------------------------------------------
1149 } // end namespace gdcm