1 /*=========================================================================
4 Module: $RCSfile: gdcmUtil.cxx,v $
6 Date: $Date: 2005/08/31 15:54:50 $
7 Version: $Revision: 1.161 $
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;
98 const uint16_t Util::FMIV = 0x0001;
99 uint8_t *Util::FileMetaInformationVersion = (uint8_t *)&FMIV;
100 std::string Util::GDCM_MAC_ADRESS = GetMACAddress();
102 //-------------------------------------------------------------------------
105 * \brief Provide a better 'c++' approach for sprintf
106 * For example c code is:
107 * char result[200]; // hope 200 is enough
108 * sprintf(result, "%04x|%04x", group , elem);
111 * std::ostringstream buf;
112 * buf << std::right << std::setw(4) << std::setfill('0') << std::hex
113 * << group << "|" << std::right << std::setw(4) << std::setfill('0')
114 * << std::hex << elem;
119 * result = gdcm::Util::Format("%04x|%04x", group , elem);
121 std::string Util::Format(const char *format, ...)
125 va_start(args, format);
126 vsprintf(buffer, format, args); //might be a security flaw
127 va_end(args); // Each invocation of va_start should be matched
128 // by a corresponding invocation of va_end
129 // args is then 'undefined'
135 * \brief Because not available in C++ (?)
136 * @param str string to check
137 * @param tokens std::vector to receive the tokenized substrings
138 * @param delimiters string containing the character delimitors
141 void Util::Tokenize (const std::string &str,
142 std::vector<std::string> &tokens,
143 const std::string &delimiters)
145 std::string::size_type lastPos = str.find_first_not_of(delimiters,0);
146 std::string::size_type pos = str.find_first_of (delimiters,lastPos);
147 while (std::string::npos != pos || std::string::npos != lastPos)
149 tokens.push_back(str.substr(lastPos, pos - lastPos));
150 lastPos = str.find_first_not_of(delimiters, pos);
151 pos = str.find_first_of (delimiters, lastPos);
156 * \brief Because not available in C++ (?)
157 * Counts the number of occurences of a substring within a string
158 * @param str string to check
159 * @param subStr substring to count
162 int Util::CountSubstring (const std::string &str,
163 const std::string &subStr)
165 int count = 0; // counts how many times it appears
166 std::string::size_type x = 0; // The index position in the string
170 x = str.find(subStr,x); // Find the substring
171 if (x != std::string::npos) // If present
173 count++; // increase the count
174 x += subStr.length(); // Skip this word
177 while (x != std::string::npos);// Carry on until not present
183 * \brief Checks whether a 'string' is printable or not (in order
184 * to avoid corrupting the terminal of invocation when printing)
185 * @param s string to check
187 bool Util::IsCleanString(std::string const &s)
189 std::cout<< std::endl << s << std::endl;
190 for(unsigned int i=0; i<s.size(); i++)
192 std::cout<< std::endl << i << " : " << (unsigned char)s[i] << std::endl;
193 if (!isprint((unsigned char)s[i]) )
202 * \brief Checks whether an 'area' is printable or not (in order
203 * to avoid corrupting the terminal of invocation when printing)
204 * @param s area to check (uint8_t is just for prototyping. feel free to cast)
205 * @param l area length to check
207 bool Util::IsCleanArea(uint8_t *s, int l)
209 for( int i=0; i<l; i++)
211 if (!isprint((unsigned char)s[i]) )
219 * \brief Weed out a string from the non-printable characters (in order
220 * to avoid corrupting the terminal of invocation when printing)
221 * @param s area to check (uint8_t is just for prototyping. feel free to cast)
222 * @param l area length to check
224 std::string Util::CreateCleanString(std::string const &s)
228 for(unsigned int i=0; i<str.size(); i++)
230 if (!isprint((unsigned char)str[i]) )
238 if (!isprint((unsigned char)s[str.size()-1]) )
240 if (s[str.size()-1] == 0 )
242 str[str.size()-1] = ' ';
251 * \brief Weed out a string from the non-printable characters (in order
252 * to avoid corrupting the terminal of invocation when printing)
253 * @param s area to process (uint8_t is just for prototyping. feel free to cast)
254 * @param l area length to check
256 std::string Util::CreateCleanString(uint8_t *s, int l)
260 for( int i=0; i<l; i++)
262 if (!isprint((unsigned char)s[i]) )
268 str = str + (char )s[i];
276 * \brief Add a SEPARATOR to the end of the name is necessary
277 * @param pathname file/directory name to normalize
279 std::string Util::NormalizePath(std::string const &pathname)
281 const char SEPARATOR_X = '/';
282 const char SEPARATOR_WIN = '\\';
283 const std::string SEPARATOR = "/";
284 std::string name = pathname;
285 int size = name.size();
287 if ( name[size-1] != SEPARATOR_X && name[size-1] != SEPARATOR_WIN )
295 * \brief Get the (directory) path from a full path file name
296 * @param fullName file/directory name to extract Path from
298 std::string Util::GetPath(std::string const &fullName)
300 std::string res = fullName;
301 int pos1 = res.rfind("/");
302 int pos2 = res.rfind("\\");
316 * \brief Get the (last) name of a full path file name
317 * @param fullName file/directory name to extract end name from
319 std::string Util::GetName(std::string const &fullName)
321 std::string filename = fullName;
323 std::string::size_type slash_pos = filename.rfind("/");
324 std::string::size_type backslash_pos = filename.rfind("\\");
325 slash_pos = slash_pos > backslash_pos ? slash_pos : backslash_pos;
326 if (slash_pos != std::string::npos )
328 return filename.substr(slash_pos + 1);
337 * \brief Get the current date of the system in a dicom string
339 std::string Util::GetCurrentDate()
344 strftime(tmp,512,"%Y%m%d", localtime(&tloc) );
349 * \brief Get the current time of the system in a dicom string
351 std::string Util::GetCurrentTime()
356 strftime(tmp,512,"%H%M%S", localtime(&tloc) );
361 * \brief Get both the date and time at the same time to avoid problem
362 * around midnight where the two calls could be before and after midnight
364 std::string Util::GetCurrentDateTime()
370 // We need implementation specific functions to obtain millisecond precision
371 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
375 milliseconds = tb.millitm;
378 gettimeofday (&tv, NULL);
380 // Compute milliseconds from microseconds.
381 milliseconds = tv.tv_usec / 1000;
383 // Obtain the time of day, and convert it to a tm struct.
384 struct tm *ptm = localtime (&timep);
385 // Format the date and time, down to a single second.
386 strftime (tmp, sizeof (tmp), "%Y%m%d%H%M%S", ptm);
389 // Don't use Util::Format to accelerate execution of code
391 sprintf(tmpAll,"%s%03ld",tmp,milliseconds);
396 unsigned int Util::GetCurrentThreadID()
398 // FIXME the implementation is far from complete
399 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
400 return (unsigned int)GetCurrentThreadId();
404 // Doesn't work on fedora, but is in the man page...
405 //return (unsigned int)gettid();
408 return (unsigned int)thr_self();
410 //default implementation
417 unsigned int Util::GetCurrentProcessID()
419 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
420 // NOTE: There is also a _getpid()...
421 return (unsigned int)GetCurrentProcessId();
423 // get process identification, POSIX
424 return (unsigned int)getpid();
429 * \brief tells us whether the processor we are working with is BigEndian or not
431 bool Util::IsCurrentProcessorBigEndian()
433 #if defined(GDCM_WORDS_BIGENDIAN)
441 * \brief Create a /DICOM/ string:
442 * It should a of even length (no odd length ever)
443 * It can contain as many (if you are reading this from your
444 * editor the following character is backslash followed by zero
445 * that needed to be escaped with an extra backslash for doxygen) \\0
448 std::string Util::DicomString(const char *s, size_t l)
450 std::string r(s, s+l);
451 gdcmAssertMacro( !(r.size() % 2) ); // == basically 'l' is even
456 * \brief Create a /DICOM/ string:
457 * It should a of even length (no odd length ever)
458 * It can contain as many (if you are reading this from your
459 * editor the following character is backslash followed by zero
460 * that needed to be escaped with an extra backslash for doxygen) \\0
462 * This function is similar to DicomString(const char*),
463 * except it doesn't take a length.
464 * It only pad with a null character if length is odd
466 std::string Util::DicomString(const char *s)
468 size_t l = strlen(s);
473 std::string r(s, s+l);
474 gdcmAssertMacro( !(r.size() % 2) );
479 * \brief Safely check the equality of two Dicom String:
480 * - Both strings should be of even length
481 * - We allow padding of even length string by either a null
482 * character of a space
484 bool Util::DicomStringEqual(const std::string &s1, const char *s2)
486 // s2 is the string from the DICOM reference e.g. : 'MONOCHROME1'
487 std::string s1_even = s1; //Never change input parameter
488 std::string s2_even = DicomString( s2 );
489 if ( s1_even[s1_even.size()-1] == ' ' )
491 s1_even[s1_even.size()-1] = '\0'; //replace space character by null
493 return s1_even == s2_even;
497 * \brief Safely compare two Dicom String:
498 * - Both strings should be of even length
499 * - We allow padding of even length string by either a null
500 * character of a space
502 bool Util::CompareDicomString(const std::string &s1, const char *s2, int op)
504 // s2 is the string from the DICOM reference e.g. : 'MONOCHROME1'
505 std::string s1_even = s1; //Never change input parameter
506 std::string s2_even = DicomString( s2 );
507 if ( s1_even[s1_even.size()-1] == ' ' )
509 s1_even[s1_even.size()-1] = '\0'; //replace space character by null
514 return s1_even == s2_even;
515 case GDCM_DIFFERENT :
516 return s1_even != s2_even;
518 return s1_even > s2_even;
519 case GDCM_GREATEROREQUAL :
520 return s1_even >= s2_even;
522 return s1_even < s2_even;
523 case GDCM_LESSOREQUAL :
524 return s1_even <= s2_even;
526 gdcmDebugMacro(" Wrong operator : " << op);
532 typedef BOOL(WINAPI * pSnmpExtensionInit) (
533 IN DWORD dwTimeZeroReference,
534 OUT HANDLE * hPollForTrapEvent,
535 OUT AsnObjectIdentifier * supportedView);
537 typedef BOOL(WINAPI * pSnmpExtensionTrap) (
538 OUT AsnObjectIdentifier * enterprise,
539 OUT AsnInteger * genericTrap,
540 OUT AsnInteger * specificTrap,
541 OUT AsnTimeticks * timeStamp,
542 OUT RFC1157VarBindList * variableBindings);
544 typedef BOOL(WINAPI * pSnmpExtensionQuery) (
546 IN OUT RFC1157VarBindList * variableBindings,
547 OUT AsnInteger * errorStatus,
548 OUT AsnInteger * errorIndex);
550 typedef BOOL(WINAPI * pSnmpExtensionInitEx) (
551 OUT AsnObjectIdentifier * supportedView);
554 /// \brief gets current M.A.C adress (for internal use only)
555 int GetMacAddrSys ( unsigned char *addr );
556 int GetMacAddrSys ( unsigned char *addr )
560 if ( (WSAStartup(MAKEWORD(2, 0), &WinsockData)) != 0 )
562 std::cerr << "in Get MAC Adress (internal) : This program requires Winsock 2.x!"
567 HANDLE PollForTrapEvent;
568 AsnObjectIdentifier SupportedView;
569 UINT OID_ifEntryType[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 3 };
570 UINT OID_ifEntryNum[] = { 1, 3, 6, 1, 2, 1, 2, 1 };
571 UINT OID_ipMACEntAddr[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 6 };
572 AsnObjectIdentifier MIB_ifMACEntAddr = {
573 sizeof(OID_ipMACEntAddr) / sizeof(UINT), OID_ipMACEntAddr };
574 AsnObjectIdentifier MIB_ifEntryType = {
575 sizeof(OID_ifEntryType) / sizeof(UINT), OID_ifEntryType };
576 AsnObjectIdentifier MIB_ifEntryNum = {
577 sizeof(OID_ifEntryNum) / sizeof(UINT), OID_ifEntryNum };
578 RFC1157VarBindList varBindList;
579 RFC1157VarBind varBind[2];
580 AsnInteger errorStatus;
581 AsnInteger errorIndex;
582 AsnObjectIdentifier MIB_NULL = { 0, 0 };
587 // Load the SNMP dll and get the addresses of the functions necessary
588 HINSTANCE m_hInst = LoadLibrary("inetmib1.dll");
589 if (m_hInst < (HINSTANCE) HINSTANCE_ERROR)
593 pSnmpExtensionInit m_Init =
594 (pSnmpExtensionInit) GetProcAddress(m_hInst, "SnmpExtensionInit");
595 pSnmpExtensionQuery m_Query =
596 (pSnmpExtensionQuery) GetProcAddress(m_hInst, "SnmpExtensionQuery");
597 m_Init(GetTickCount(), &PollForTrapEvent, &SupportedView);
599 /* Initialize the variable list to be retrieved by m_Query */
600 varBindList.list = varBind;
601 varBind[0].name = MIB_NULL;
602 varBind[1].name = MIB_NULL;
604 // Copy in the OID to find the number of entries in the
606 varBindList.len = 1; // Only retrieving one item
607 SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryNum);
608 m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
610 // printf("# of adapters in this system : %i\n",
611 // varBind[0].value.asnValue.number);
614 // Copy in the OID of ifType, the type of interface
615 SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryType);
617 // Copy in the OID of ifPhysAddress, the address
618 SNMP_oidcpy(&varBind[1].name, &MIB_ifMACEntAddr);
622 // Submit the query. Responses will be loaded into varBindList.
623 // We can expect this call to succeed a # of times corresponding
624 // to the # of adapters reported to be in the system
625 ret = m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
633 // Confirm that the proper type has been returned
634 ret = SNMP_oidncmp(&varBind[0].name, &MIB_ifEntryType,
635 MIB_ifEntryType.idLength);
640 dtmp = varBind[0].value.asnValue.number;
642 // Type 6 describes ethernet interfaces
645 // Confirm that we have an address here
646 ret = SNMP_oidncmp(&varBind[1].name, &MIB_ifMACEntAddr,
647 MIB_ifMACEntAddr.idLength);
648 if ( !ret && varBind[1].value.asnValue.address.stream != NULL )
650 if ( (varBind[1].value.asnValue.address.stream[0] == 0x44)
651 && (varBind[1].value.asnValue.address.stream[1] == 0x45)
652 && (varBind[1].value.asnValue.address.stream[2] == 0x53)
653 && (varBind[1].value.asnValue.address.stream[3] == 0x54)
654 && (varBind[1].value.asnValue.address.stream[4] == 0x00) )
656 // Ignore all dial-up networking adapters
657 std::cerr << "in Get MAC Adress (internal) : Interface #"
658 << j << " is a DUN adapter\n";
661 if ( (varBind[1].value.asnValue.address.stream[0] == 0x00)
662 && (varBind[1].value.asnValue.address.stream[1] == 0x00)
663 && (varBind[1].value.asnValue.address.stream[2] == 0x00)
664 && (varBind[1].value.asnValue.address.stream[3] == 0x00)
665 && (varBind[1].value.asnValue.address.stream[4] == 0x00)
666 && (varBind[1].value.asnValue.address.stream[5] == 0x00) )
668 // Ignore NULL addresses returned by other network
670 std::cerr << "in Get MAC Adress (internal) : Interface #"
671 << j << " is a NULL address\n";
674 memcpy( addr, varBind[1].value.asnValue.address.stream, 6);
681 SNMP_FreeVarBind(&varBind[0]);
682 SNMP_FreeVarBind(&varBind[1]);
684 #endif //Win32 version
687 // implementation for POSIX system
688 #if defined(CMAKE_HAVE_NET_IF_ARP_H) && defined(__sun)
689 //The POSIX version is broken anyway on Solaris, plus would require full
691 struct arpreq parpreq;
692 struct sockaddr_in *psa;
693 struct hostent *phost;
694 char hostname[MAXHOSTNAMELEN];
698 if (gethostname(hostname, MAXHOSTNAMELEN) != 0 )
700 perror("in Get MAC Adress (internal) : gethostname");
703 phost = gethostbyname(hostname);
704 paddrs = phost->h_addr_list;
706 sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
709 perror("in Get MAC Adress (internal) : sock");
712 memset(&parpreq, 0, sizeof(struct arpreq));
713 psa = (struct sockaddr_in *) &parpreq.arp_pa;
715 memset(psa, 0, sizeof(struct sockaddr_in));
716 psa->sin_family = AF_INET;
717 memcpy(&psa->sin_addr, *paddrs, sizeof(struct in_addr));
719 status = ioctl(sock, SIOCGARP, &parpreq);
722 perror("in Get MAC Adress (internal) : SIOCGARP");
725 memcpy(addr, parpreq.arp_ha.sa_data, 6);
729 #ifdef CMAKE_HAVE_NET_IF_H
731 struct ifreq ifr, *ifrp;
736 #if defined(AF_LINK) && (!defined(SIOCGIFHWADDR) && !defined(SIOCGENADDR))
737 struct sockaddr_dl *sdlp;
741 // BSD 4.4 defines the size of an ifreq to be
742 // max(sizeof(ifreq), sizeof(ifreq.ifr_name)+ifreq.ifr_addr.sa_len
743 // However, under earlier systems, sa_len isn't present, so the size is
744 // just sizeof(struct ifreq)
745 // We should investigate the use of SIZEOF_ADDR_IFREQ
749 #define max(a,b) ((a) > (b) ? (a) : (b))
751 #define ifreq_size(i) max(sizeof(struct ifreq),\
752 sizeof((i).ifr_name)+(i).ifr_addr.sa_len)
754 #define ifreq_size(i) sizeof(struct ifreq)
755 #endif // HAVE_SA_LEN
757 if ( (sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) < 0 )
761 memset(buf, 0, sizeof(buf));
762 ifc.ifc_len = sizeof(buf);
764 if (ioctl (sd, SIOCGIFCONF, (char *)&ifc) < 0)
770 for (i = 0; i < n; i+= ifreq_size(*ifrp) )
772 ifrp = (struct ifreq *)((char *) ifc.ifc_buf+i);
773 strncpy(ifr.ifr_name, ifrp->ifr_name, IFNAMSIZ);
775 if (ioctl(sd, SIOCGIFHWADDR, &ifr) < 0)
777 a = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
780 // In theory this call should also work on Sun Solaris, but apparently
781 // SIOCGENADDR is not implemented properly thus the call
782 // ioctl(sd, SIOCGENADDR, &ifr) always returns errno=2
783 // (No such file or directory)
784 // Furthermore the DLAPI seems to require full root access
785 if (ioctl(sd, SIOCGENADDR, &ifr) < 0)
787 a = (unsigned char *) ifr.ifr_enaddr;
790 sdlp = (struct sockaddr_dl *) &ifrp->ifr_addr;
791 if ((sdlp->sdl_family != AF_LINK) || (sdlp->sdl_alen != 6))
793 a = (unsigned char *) &sdlp->sdl_data[sdlp->sdl_nlen];
795 perror("in Get MAC Adress (internal) : No way to access hardware");
799 #endif // SIOCGENADDR
800 #endif // SIOCGIFHWADDR
801 if (!a[0] && !a[1] && !a[2] && !a[3] && !a[4] && !a[5]) continue;
812 // Not implemented platforms
813 perror("in Get MAC Adress (internal) : There was a configuration problem on your plateform");
820 * \brief Mini function to return the last digit from a number express in base 256
821 * pre condition data contain an array of 6 unsigned char
822 * post condition carry contain the last digit
824 inline int getlastdigit(unsigned char *data)
826 int extended, carry = 0;
829 extended = (carry << 8) + data[i];
830 data[i] = extended / 10;
831 carry = extended % 10;
837 * \brief Encode the mac address on a fixed lenght string of 15 characters.
838 * we save space this way.
840 std::string Util::GetMACAddress()
842 // This code is the result of a long internet search to find something
843 // as compact as possible (not OS independant). We only have to separate
844 // 3 OS: Win32, SunOS and 'real' POSIX
845 // http://groups-beta.google.com/group/comp.unix.solaris/msg/ad36929d783d63be
846 // http://bdn.borland.com/article/0,1410,26040,00.html
847 unsigned char addr[6];
849 int stat = GetMacAddrSys(addr);
852 // We need to convert a 6 digit number from base 256 to base 10, using integer
853 // would requires a 48bits one. To avoid this we have to reimplement the div + modulo
860 res = getlastdigit(addr);
861 sres.insert(sres.begin(), '0' + res);
862 zero = (addr[0] == 0) && (addr[1] == 0) && (addr[2] == 0)
863 && (addr[3] == 0) && (addr[4] == 0) && (addr[5] == 0);
870 gdcmWarningMacro("Problem in finding the MAC Address");
876 * \brief Creates a new UID. As stipulate in the DICOM ref
877 * each time a DICOM image is create it should have
878 * a unique identifier (URI)
879 * @param root is the DICOM prefix assigned by IOS group
881 std::string Util::CreateUniqueUID(const std::string &root)
887 // gdcm UID prefix, as supplied by http://www.medicalconnections.co.uk
895 // A root was specified use it to forge our new UID:
897 //append += Util::GetMACAddress(); // to save CPU time
898 append += Util::GDCM_MAC_ADRESS;
900 append += Util::GetCurrentDateTime();
902 //Also add a mini random number just in case:
904 int r = (int) (100.0*rand()/RAND_MAX);
905 // Don't use Util::Format to accelerate the execution
906 sprintf(tmp,"%02d", r);
909 // If append is too long we need to rehash it
910 if ( (prefix + append).size() > 64 )
912 gdcmErrorMacro( "Size of UID is too long." );
913 // we need a hash function to truncate this number
914 // if only md5 was cross plateform
918 return prefix + append;
921 void Util::SetRootUID(const std::string &root)
929 const std::string &Util::GetRootUID()
934 //-------------------------------------------------------------------------
936 * \brief binary_write binary_write
937 * @param os ostream to write to
940 std::ostream &binary_write(std::ostream &os, const uint16_t &val)
942 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
944 //swap = ((( val << 8 ) & 0xff00 ) | (( val >> 8 ) & 0x00ff ) );
946 swap = ( val << 8 | val >> 8 );
948 return os.write(reinterpret_cast<const char*>(&swap), 2);
950 return os.write(reinterpret_cast<const char*>(&val), 2);
951 #endif //GDCM_WORDS_BIGENDIAN
955 * \brief binary_write binary_write
956 * @param os ostream to write to
959 std::ostream &binary_write(std::ostream &os, const uint32_t &val)
961 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
963 // swap = ( ((val<<24) & 0xff000000) | ((val<<8) & 0x00ff0000) |
964 // ((val>>8) & 0x0000ff00) | ((val>>24) & 0x000000ff) );
966 swap = ( (val<<24) | ((val<<8) & 0x00ff0000) |
967 ((val>>8) & 0x0000ff00) | (val>>24) );
968 return os.write(reinterpret_cast<const char*>(&swap), 4);
970 return os.write(reinterpret_cast<const char*>(&val), 4);
971 #endif //GDCM_WORDS_BIGENDIAN
975 * \brief binary_write binary_write
976 * @param os ostream to write to
979 std::ostream &binary_write(std::ostream &os, const char *val)
981 return os.write(val, strlen(val));
986 * @param os ostream to write to
989 std::ostream &binary_write(std::ostream &os, std::string const &val)
991 return os.write(val.c_str(), val.size());
995 * \brief binary_write binary_write
996 * @param os ostream to write to
998 * @param len length of the 'value' to be written
1000 std::ostream &binary_write(std::ostream &os, const uint8_t *val, size_t len)
1002 // We are writting sizeof(char) thus no need to swap bytes
1003 return os.write(reinterpret_cast<const char*>(val), len);
1007 * \brief binary_write binary_write
1008 * @param os ostream to write to
1010 * @param len length of the 'value' to be written
1012 std::ostream &binary_write(std::ostream &os, const uint16_t *val, size_t len)
1014 // This is tricky since we are writting two bytes buffer.
1015 // Be carefull with little endian vs big endian.
1016 // Also this other trick is to allocate a small (efficient) buffer that store
1017 // intermediate result before writting it.
1018 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
1019 const int BUFFER_SIZE = 4096;
1020 static char buffer[BUFFER_SIZE];
1021 uint16_t *binArea16 = (uint16_t*)val; //for the const
1023 // how many BUFFER_SIZE long pieces in binArea ?
1024 int nbPieces = len/BUFFER_SIZE; //(16 bits = 2 Bytes)
1025 int remainingSize = len%BUFFER_SIZE;
1027 for (int j=0;j<nbPieces;j++)
1029 uint16_t *pbuffer = (uint16_t*)buffer; //reinitialize pbuffer
1030 for (int i = 0; i < BUFFER_SIZE/2; i++)
1032 *pbuffer = *binArea16 >> 8 | *binArea16 << 8;
1036 os.write ( buffer, BUFFER_SIZE );
1038 if ( remainingSize > 0)
1040 uint16_t *pbuffer = (uint16_t*)buffer; //reinitialize pbuffer
1041 for (int i = 0; i < remainingSize/2; i++)
1043 *pbuffer = *binArea16 >> 8 | *binArea16 << 8;
1047 os.write ( buffer, remainingSize );
1051 return os.write(reinterpret_cast<const char*>(val), len);
1055 //-------------------------------------------------------------------------
1058 //-------------------------------------------------------------------------
1061 * \brief Return the IP adress of the machine writting the DICOM image
1063 std::string Util::GetIPAddress()
1065 // This is a rip from
1066 // http://www.codeguru.com/Cpp/I-N/internet/network/article.php/c3445/
1067 #ifndef HOST_NAME_MAX
1068 // SUSv2 guarantees that `Host names are limited to 255 bytes'.
1069 // POSIX 1003.1-2001 guarantees that `Host names (not including the
1070 // terminating NUL) are limited to HOST_NAME_MAX bytes'.
1071 #define HOST_NAME_MAX 255
1072 // In this case we should maybe check the string was not truncated.
1073 // But I don't known how to check that...
1074 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
1075 // with WinSock DLL we need to initialize the WinSock before using gethostname
1076 WORD wVersionRequested = MAKEWORD(1,0);
1078 int err = WSAStartup(wVersionRequested,&WSAData);
1081 // Tell the user that we could not find a usable
1088 #endif //HOST_NAME_MAX
1091 char szHostName[HOST_NAME_MAX+1];
1092 int r = gethostname(szHostName, HOST_NAME_MAX);
1096 // Get host adresses
1097 struct hostent *pHost = gethostbyname(szHostName);
1099 for( int i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
1101 for( int j = 0; j<pHost->h_length; j++ )
1103 if ( j > 0 ) str += ".";
1105 str += Util::Format("%u",
1106 (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);
1108 // str now contains one local IP address
1110 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
1116 // If an error occur r == -1
1117 // Most of the time it will return 127.0.0.1...
1121 //-------------------------------------------------------------------------
1122 } // end namespace gdcm