1 /*=========================================================================
4 Module: $RCSfile: gdcmUtil.cxx,v $
6 Date: $Date: 2005/01/15 00:52:36 $
7 Version: $Revision: 1.90 $
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 #include <stdarg.h> //only included in implementation file
29 #include <stdio.h> //only included in implementation file
32 #include <winsock.h> // for gethostname & gethostbyname
36 #include <unistd.h> // for gethostname
37 #include <netdb.h> // for gethostbyname
50 #include <strings.h> //for bzero on unix
54 #include <sys/ioctl.h>
55 #include <sys/types.h>
56 #include <sys/socket.h>
57 #include <netinet/in.h>
62 #include <sys/types.h>
63 #include <sys/socket.h>
65 #include <net/if_dl.h>
73 #include <sys/ndd_var.h>
74 #include <sys/kinfo.h>
78 #include <CoreFoundation/CoreFoundation.h>
79 #include <IOKit/IOKitLib.h>
80 #include <IOKit/network/IOEthernetInterface.h>
81 #include <IOKit/network/IONetworkInterface.h>
82 #include <IOKit/network/IOEthernetController.h>
84 // End For GetMACAddress
90 * \brief Provide a better 'c++' approach for sprintf
91 * For example c code is:
92 * sprintf(trash, "%04x|%04x", group , elem);
95 * std::ostringstream buf;
96 * buf << std::right << std::setw(4) << std::setfill('0') << std::hex
97 * << group << "|" << std::right << std::setw(4) << std::setfill('0')
98 * << std::hex << elem;
102 * Format("%04x|%04x", group , elem);
105 std::string Util::Format(const char *format, ...)
109 va_start(args, format);
110 vsprintf(buffer, format, args); //might be a security flaw
111 va_end(args); // Each invocation of va_start should be matched
112 // by a corresponding invocation of va_end
113 // args is then 'undefined'
120 * \brief Because not available in C++ (?)
122 void Util::Tokenize (const std::string &str,
123 std::vector<std::string> &tokens,
124 const std::string& delimiters)
126 std::string::size_type lastPos = str.find_first_not_of(delimiters,0);
127 std::string::size_type pos = str.find_first_of (delimiters,lastPos);
128 while (std::string::npos != pos || std::string::npos != lastPos)
130 tokens.push_back(str.substr(lastPos, pos - lastPos));
131 lastPos = str.find_first_not_of(delimiters, pos);
132 pos = str.find_first_of (delimiters, lastPos);
138 * \brief Because not available in C++ (?)
139 * Counts the number of occurences of a substring within a string
142 int Util::CountSubstring (const std::string &str,
143 const std::string &subStr)
145 int count = 0; // counts how many times it appears
146 std::string::size_type x = 0; // The index position in the string
150 x = str.find(subStr,x); // Find the substring
151 if (x != std::string::npos) // If present
153 count++; // increase the count
154 x += subStr.length(); // Skip this word
157 while (x != std::string::npos); // Carry on until not present
164 * \brief Weed out a string from the non-printable characters (in order
165 * to avoid corrupting the terminal of invocation when printing)
166 * @param s string to remove non printable characters from
168 std::string Util::CreateCleanString(std::string const &s)
172 for(unsigned int i=0; i<str.size(); i++)
174 if(!isprint((unsigned char)str[i]))
182 if(!isprint((unsigned char)s[str.size()-1]))
184 if(s[str.size()-1] == 0)
186 str[str.size()-1] = ' ';
196 * \brief Add a SEPARATOR to the end of the name is necessary
197 * @param pathname file/directory name to normalize
199 std::string Util::NormalizePath(std::string const &pathname)
201 const char SEPARATOR_X = '/';
202 const char SEPARATOR_WIN = '\\';
203 const std::string SEPARATOR = "/";
204 std::string name = pathname;
205 int size = name.size();
207 if( name[size-1] != SEPARATOR_X && name[size-1] != SEPARATOR_WIN )
216 * \brief Get the (directory) path from a full path file name
217 * @param fullName file/directory name to extract Path from
219 std::string Util::GetPath(std::string const &fullName)
221 std::string res = fullName;
222 int pos1 = res.rfind("/");
223 int pos2 = res.rfind("\\");
238 * \brief Get the (last) name of a full path file name
239 * @param fullName file/directory name to extract end name from
241 std::string Util::GetName(std::string const &fullName)
243 std::string filename = fullName;
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)
250 return filename.substr(slash_pos + 1);
260 * \brief Get the current date of the system in a dicom string
262 std::string Util::GetCurrentDate()
267 strftime(tmp,512,"%Y%m%d", localtime(&tloc) );
273 * \brief Get the current time of the system in a dicom string
275 std::string Util::GetCurrentTime()
280 strftime(tmp,512,"%H%M%S", localtime(&tloc) );
285 * \brief Create a /DICOM/ string:
286 * It should a of even length (no odd length ever)
287 * It can contain as many (if you are reading this from your
288 * editor the following character is is backslash followed by zero
289 * that needed to be escaped with an extra backslash for doxygen) \\0
292 std::string Util::DicomString(const char *s, size_t l)
294 std::string r(s, s+l);
295 gdcmAssertMacro( !(r.size() % 2) ); // == basically 'l' is even
301 * \brief Create a /DICOM/ string:
302 * It should a of even lenght (no odd length ever)
303 * It can contain as many (if you are reading this from your
304 * editor the following character is is backslash followed by zero
305 * that needed to be escaped with an extra backslash for doxygen) \\0
307 * This function is similar to DicomString(const char*),
308 * except it doesn't take a lenght.
309 * It only pad with a null character if length is odd
311 std::string Util::DicomString(const char *s)
313 size_t l = strlen(s);
318 std::string r(s, s+l);
319 gdcmAssertMacro( !(r.size() % 2) );
325 * \brief Safely compare two Dicom String:
326 * - Both string should be of even lenght
327 * - We allow padding of even lenght string by either a null
328 * character of a space
330 bool Util::DicomStringEqual(const std::string &s1, const char *s2)
332 // s2 is the string from the DICOM reference: 'MONOCHROME1'
333 std::string s1_even = s1; //Never change input parameter
334 std::string s2_even = DicomString( s2 );
335 if( s1_even[s1_even.size()-1] == ' ')
337 s1_even[s1_even.size()-1] = '\0'; //replace space character by null
339 return s1_even == s2_even;
346 * \brief tells us if the processor we are working with is BigEndian or not
348 bool Util::IsCurrentProcessorBigEndian()
350 #ifdef GDCM_WORDS_BIGENDIAN
360 typedef BOOL(WINAPI * pSnmpExtensionInit) (
361 IN DWORD dwTimeZeroReference,
362 OUT HANDLE * hPollForTrapEvent,
363 OUT AsnObjectIdentifier * supportedView);
365 typedef BOOL(WINAPI * pSnmpExtensionTrap) (
366 OUT AsnObjectIdentifier * enterprise,
367 OUT AsnInteger * genericTrap,
368 OUT AsnInteger * specificTrap,
369 OUT AsnTimeticks * timeStamp,
370 OUT RFC1157VarBindList * variableBindings);
372 typedef BOOL(WINAPI * pSnmpExtensionQuery) (
374 IN OUT RFC1157VarBindList * variableBindings,
375 OUT AsnInteger * errorStatus,
376 OUT AsnInteger * errorIndex);
378 typedef BOOL(WINAPI * pSnmpExtensionInitEx) (
379 OUT AsnObjectIdentifier * supportedView);
384 // Returns an iterator containing the primary (built-in) Ethernet interface.
385 // The caller is responsible for releasing the iterator after the caller is
387 static kern_return_t FindEthernetInterfaces(io_iterator_t *matchingServices)
389 kern_return_t kernResult;
390 mach_port_t masterPort;
391 CFMutableDictionaryRef matchingDict;
392 CFMutableDictionaryRef propertyMatchDict;
394 // Retrieve the Mach port used to initiate communication with I/O Kit
395 kernResult = IOMasterPort(MACH_PORT_NULL, &masterPort);
396 if (KERN_SUCCESS != kernResult)
398 printf("IOMasterPort returned %d\n", kernResult);
402 // Ethernet interfaces are instances of class kIOEthernetInterfaceClass.
403 // IOServiceMatching is a convenience function to create a dictionary
404 // with the key kIOProviderClassKey and
405 // the specified value.
406 matchingDict = IOServiceMatching(kIOEthernetInterfaceClass);
408 // Note that another option here would be:
409 // matchingDict = IOBSDMatching("en0");
411 if (NULL == matchingDict)
413 printf("IOServiceMatching returned a NULL dictionary.\n");
417 // Each IONetworkInterface object has a Boolean property with the
418 // key kIOPrimaryInterface. Only the
419 // primary (built-in) interface has this property set to TRUE.
421 // IOServiceGetMatchingServices uses the default matching criteria
422 // defined by IOService. This considers
423 // only the following properties plus any family-specific matching
424 // in this order of precedence
425 // (see IOService::passiveMatch):
427 // kIOProviderClassKey (IOServiceMatching)
428 // kIONameMatchKey (IOServiceNameMatching)
429 // kIOPropertyMatchKey
431 // kIOMatchedServiceCountKey
432 // family-specific matching
433 // kIOBSDNameKey (IOBSDNameMatching)
434 // kIOLocationMatchKey
436 // The IONetworkingFamily does not define any family-specific
437 // matching. This means that in order to have
438 // IOServiceGetMatchingServices consider the kIOPrimaryInterface
439 // property, we must add that property to a separate dictionary and
440 // then add that to our matching dictionary specifying
441 // kIOPropertyMatchKey.
444 CFDictionaryCreateMutable( kCFAllocatorDefault, 0,
445 &kCFTypeDictionaryKeyCallBacks,
446 &kCFTypeDictionaryValueCallBacks);
448 if (NULL == propertyMatchDict)
450 printf("CFDictionaryCreateMutable returned a NULL dictionary.\n");
454 // Set the value in the dictionary of the property with the given
455 // key, or add the key to the dictionary if it doesn't exist.
456 // This call retains the value object passed in.
457 CFDictionarySetValue(propertyMatchDict, CFSTR(kIOPrimaryInterface),
460 // Now add the dictionary containing the matching value for
461 // kIOPrimaryInterface to our main matching dictionary. This call
462 // will retain propertyMatchDict, so we can release our reference
463 // on propertyMatchDict after adding it to matchingDict.
464 CFDictionarySetValue(matchingDict, CFSTR(kIOPropertyMatchKey),
466 CFRelease(propertyMatchDict);
470 // IOServiceGetMatchingServices retains the returned iterator, so release
471 // the iterator when we're done with it.
472 // IOServiceGetMatchingServices also consumes a reference on the matching
473 // dictionary so we don't need to release the dictionary explicitly.
475 IOServiceGetMatchingServices(masterPort, matchingDict, matchingServices);
476 if (KERN_SUCCESS != kernResult)
478 printf("IOServiceGetMatchingServices returned %d\n", kernResult);
484 // Given an iterator across a set of Ethernet interfaces, return the MAC
485 // address of the last one.
486 // If no interfaces are found the MAC address is set to an empty string.
487 // In this sample the iterator should contain just the primary interface.
488 static kern_return_t GetMACAddress_MAC(io_iterator_t intfIterator,
491 io_object_t intfService;
492 io_object_t controllerService;
493 kern_return_t kernResult = KERN_FAILURE;
495 // Initialize the returned address
496 bzero(MACAddress, kIOEthernetAddressSize);
498 // IOIteratorNext retains the returned object, so release it when we're
500 while ( (intfService = IOIteratorNext(intfIterator)))
502 CFTypeRef MACAddressAsCFData;
504 // IONetworkControllers can't be found directly by the
505 // IOServiceGetMatchingServices call, since they are hardware nubs
506 // and do not participate in driver matching. In other words,
507 // registerService() is never called on them. So we've found the
508 // IONetworkInterface and will
509 // get its parent controller by asking for it specifically.
511 // IORegistryEntryGetParentEntry retains the returned object, so
512 // release it when we're done with it.
513 kernResult = IORegistryEntryGetParentEntry( intfService,
515 &controllerService );
517 if (KERN_SUCCESS != kernResult)
519 printf("IORegistryEntryGetParentEntry returned 0x%08x\n", kernResult);
523 // Retrieve the MAC address property from the I/O Registry in the
526 IORegistryEntryCreateCFProperty( controllerService,
527 CFSTR(kIOMACAddress),
530 if (MACAddressAsCFData)
532 // for display purposes only; output goes to stderr
533 //CFShow(MACAddressAsCFData);
535 // Get the raw bytes of the MAC address from the CFData
536 CFDataGetBytes(MACAddressAsCFData,
537 CFRangeMake(0, kIOEthernetAddressSize),
539 CFRelease(MACAddressAsCFData);
542 // Done with the parent Ethernet controller object so we release it.
543 (void) IOObjectRelease(controllerService);
546 // Done with the Ethernet interface object so we release it.
547 (void) IOObjectRelease(intfService);
554 long GetMacAddrSys ( u_char *addr)
558 if (WSAStartup(MAKEWORD(2, 0), &WinsockData) != 0)
560 std::cerr << "This program requires Winsock 2.x!" << std::endl;
564 HANDLE PollForTrapEvent;
565 AsnObjectIdentifier SupportedView;
566 UINT OID_ifEntryType[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 3 };
567 UINT OID_ifEntryNum[] = { 1, 3, 6, 1, 2, 1, 2, 1 };
568 UINT OID_ipMACEntAddr[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 6 };
569 AsnObjectIdentifier MIB_ifMACEntAddr = {
570 sizeof(OID_ipMACEntAddr) / sizeof(UINT), OID_ipMACEntAddr };
571 AsnObjectIdentifier MIB_ifEntryType = {
572 sizeof(OID_ifEntryType) / sizeof(UINT), OID_ifEntryType };
573 AsnObjectIdentifier MIB_ifEntryNum = {
574 sizeof(OID_ifEntryNum) / sizeof(UINT), OID_ifEntryNum };
575 RFC1157VarBindList varBindList;
576 RFC1157VarBind varBind[2];
577 AsnInteger errorStatus;
578 AsnInteger errorIndex;
579 AsnObjectIdentifier MIB_NULL = { 0, 0 };
585 // Load the SNMP dll and get the addresses of the functions necessary
586 HINSTANCE m_hInst = LoadLibrary("inetmib1.dll");
587 if (m_hInst < (HINSTANCE) HINSTANCE_ERROR)
592 pSnmpExtensionInit m_Init =
593 (pSnmpExtensionInit) GetProcAddress(m_hInst, "SnmpExtensionInit");
594 pSnmpExtensionInitEx m_InitEx =
595 (pSnmpExtensionInitEx) GetProcAddress(m_hInst, "SnmpExtensionInitEx");
596 pSnmpExtensionQuery m_Query =
597 (pSnmpExtensionQuery) GetProcAddress(m_hInst, "SnmpExtensionQuery");
598 pSnmpExtensionTrap m_Trap =
599 (pSnmpExtensionTrap) GetProcAddress(m_hInst, "SnmpExtensionTrap");
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 ret = m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
613 // printf("# of adapters in this system : %i\n",
614 // varBind[0].value.asnValue.number); varBindList.len = 2;
616 // Copy in the OID of ifType, the type of interface
617 SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryType);
619 // Copy in the OID of ifPhysAddress, the address
620 SNMP_oidcpy(&varBind[1].name, &MIB_ifMACEntAddr);
624 // Submit the query. Responses will be loaded into varBindList.
625 // We can expect this call to succeed a # of times corresponding
626 // to the # of adapters reported to be in the system
627 ret = m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
635 // Confirm that the proper type has been returned
636 ret = SNMP_oidncmp(&varBind[0].name, &MIB_ifEntryType,
637 MIB_ifEntryType.idLength);
642 dtmp = varBind[0].value.asnValue.number;
643 printf("Interface #%i type : %i\n", j, dtmp);
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 printf("Interface #%i is a DUN adapter\n", j);
663 if ( (varBind[1].value.asnValue.address.stream[0] == 0x00)
664 && (varBind[1].value.asnValue.address.stream[1] == 0x00)
665 && (varBind[1].value.asnValue.address.stream[2] == 0x00)
666 && (varBind[1].value.asnValue.address.stream[3] == 0x00)
667 && (varBind[1].value.asnValue.address.stream[4] == 0x00)
668 && (varBind[1].value.asnValue.address.stream[5] == 0x00) )
670 // Ignore NULL addresses returned by other network
672 printf("Interface #%i is a NULL address\n", j);
675 memcpy( addr, varBind[1].value.asnValue.address.stream, 6);
682 SNMP_FreeVarBind(&varBind[0]);
683 SNMP_FreeVarBind(&varBind[1]);
687 // implementation for Linux
696 s = socket(AF_INET, SOCK_DGRAM, 0);
702 ifc.ifc_len = sizeof(buf);
704 ioctl(s, SIOCGIFCONF, &ifc);
707 for (i = ifc.ifc_len / sizeof(struct ifreq); --i >= 0; IFR++)
709 strcpy(ifr.ifr_name, IFR->ifr_name);
710 if (ioctl(s, SIOCGIFFLAGS, &ifr) == 0)
712 if (! (ifr.ifr_flags & IFF_LOOPBACK))
714 if (ioctl(s, SIOCGIFHWADDR, &ifr) == 0)
726 bcopy( ifr.ifr_hwaddr.sa_data, addr, 6);
735 // implementation for FreeBSD
737 struct ifaddrs *ifap, *ifaphead;
739 const struct sockaddr_dl *sdl;
743 rtnerr = getifaddrs(&ifaphead);
750 for (ifap = ifaphead; ifap; ifap = ifap->ifa_next)
752 if (ifap->ifa_addr->sa_family == AF_LINK)
754 sdl = (const struct sockaddr_dl *) ifap->ifa_addr;
755 ap = ((caddr_t)((sdl)->sdl_data + (sdl)->sdl_nlen));
756 alen = sdl->sdl_alen;
761 //printf ("%s:", ifap->ifa_name);
762 //for (i = 0; i < alen; i++, ap++)
764 //printf("%c%02x", i > 0 ? ':' : ' ', 0xff&*ap);
773 freeifaddrs(ifaphead);
777 // implementation for HP-UX
779 const char LAN_DEV0[] = "/dev/lan0";
782 struct fis iocnt_block;
783 char net_buf[sizeof(LAN_DEV0)+1];
785 (void)sprintf(net_buf, "%s", LAN_DEV0);
786 char *p = net_buf + strlen(net_buf) - 1;
789 // Get 802.3 address from card by opening the driver and interrogating it.
791 for (int i = 0; i < 10; i++, (*p)++)
793 if ((fd = open (net_buf, O_RDONLY)) != -1)
795 iocnt_block.reqtype = LOCAL_ADDRESS;
796 ioctl (fd, NETSTAT, &iocnt_block);
799 if (iocnt_block.vtype == 6) break;
803 if (fd == -1 || iocnt_block.vtype != 6)
808 bcopy( &iocnt_block.value.s[0], addr, 6);
812 /* implementation for AIX */
814 int size = getkerninfo(KINFO_NDD, 0, 0, 0);
819 struct kinfo_ndd *nddp = (struct kinfo_ndd *)malloc(size);
825 if (getkerninfo(KINFO_NDD, nddp, &size, 0) < 0)
830 bcopy(nddp->ndd_addr, addr, 6);
837 io_iterator_t intfIterator;
838 UInt8 MACAddress[ kIOEthernetAddressSize ];
840 kern_return_t kernResult = FindEthernetInterfaces(&intfIterator);
842 if (KERN_SUCCESS != kernResult)
844 printf("FindEthernetInterfaces returned 0x%08x\n", kernResult);
848 kernResult = GetMACAddress_MAC(intfIterator, MACAddress);
850 if (KERN_SUCCESS != kernResult)
852 printf("GetMACAddress returned 0x%08x\n", kernResult);
856 (void) IOObjectRelease(intfIterator); // Release the iterator.
858 memcpy(addr, MACAddress, kIOEthernetAddressSize);
862 /* Not implemented platforms */
867 std::string Util::GetMACAddress()
869 // This is a rip from: http://cplus.kompf.de/macaddr.html for Linux, HPUX and AIX
870 // and http://tangentsoft.net/wskfaq/examples/src/snmpmac.cpp for windows version
871 // and http://groups-beta.google.com/group/sol.lists.freebsd.hackers/msg/0d0f862e05fce6c0 for the FreeBSD version
872 // and http://developer.apple.com/samplecode/GetPrimaryMACAddress/GetPrimaryMACAddress.html for MacOSX version
876 long stat = GetMacAddrSys(addr);
879 //printf( "MAC address = ");
880 for (int i=0; i<6; ++i)
882 //printf("%2.2x", addr[i]);
883 macaddr += Format("%2.2x", addr[i]);
890 //printf( "No MAC address !\n" );
897 * \brief Return the IP adress of the machine writting the DICOM image
899 std::string Util::GetIPAddress()
901 // This is a rip from
902 // http://www.codeguru.com/Cpp/I-N/internet/network/article.php/c3445/
903 #ifndef HOST_NAME_MAX
904 // SUSv2 guarantees that `Host names are limited to 255 bytes'.
905 // POSIX 1003.1-2001 guarantees that `Host names (not including the
906 // terminating NUL) are limited to HOST_NAME_MAX bytes'.
907 # define HOST_NAME_MAX 255
908 // In this case we should maybe check the string was not truncated.
909 // But I don't known how to check that...
910 #if defined(_MSC_VER) || defined(__BORLANDC__)
911 // with WinSock DLL we need to initialise the WinSock before using gethostname
912 WORD wVersionRequested = MAKEWORD(1,0);
914 int err = WSAStartup(wVersionRequested,&WSAData);
917 // Tell the user that we could not find a usable
924 #endif //HOST_NAME_MAX
927 char szHostName[HOST_NAME_MAX+1];
928 int r = gethostname(szHostName, HOST_NAME_MAX);
933 struct hostent *pHost = gethostbyname(szHostName);
935 for( int i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
937 for( int j = 0; j<pHost->h_length; j++ )
939 if( j > 0 ) str += ".";
941 str += Util::Format("%u",
942 (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);
944 // str now contains one local IP address
946 #if defined(_MSC_VER) || defined(__BORLANDC__)
952 // If an error occur r == -1
953 // Most of the time it will return 127.0.0.1...
959 * \brief Creates a new UID. As stipulate in the DICOM ref
960 * each time a DICOM image is create it should have
961 * a unique identifier (URI)
963 std::string Util::CreateUniqueUID(const std::string &root)
965 // The code works as follow:
966 // echo "gdcm" | od -b
967 // 0000000 147 144 143 155 012
968 // Therefore we return
969 // radical + 147.144.143.155 + IP + time()
970 std::string radical = root;
971 if( !root.size() ) //anything better ?
973 radical = "0.0."; // Is this really usefull ?
976 // A root was specified use it to forge our new UID:
977 radical += "147.144.143.155"; // gdcm
979 radical += Util::GetIPAddress();
981 radical += Util::GetCurrentDate();
983 radical += Util::GetCurrentTime();
989 std::ostream &binary_write(std::ostream &os, const T &val)
991 return os.write(reinterpret_cast<const char*>(&val), sizeof val);
994 std::ostream &binary_write(std::ostream &os, const uint16_t &val)
996 #ifdef GDCM_WORDS_BIGENDIAN
998 swap = ((( val << 8 ) & 0x0ff00 ) | (( val >> 8 ) & 0x00ff ) );
999 return os.write(reinterpret_cast<const char*>(&swap), 2);
1001 return os.write(reinterpret_cast<const char*>(&val), 2);
1002 #endif //GDCM_WORDS_BIGENDIAN
1005 std::ostream &binary_write(std::ostream &os, const uint32_t &val)
1007 #ifdef GDCM_WORDS_BIGENDIAN
1009 swap = ( ((val<<24) & 0xff000000) | ((val<<8) & 0x00ff0000) |
1010 ((val>>8) & 0x0000ff00) | ((val>>24) & 0x000000ff) );
1011 return os.write(reinterpret_cast<const char*>(&swap), 4);
1013 return os.write(reinterpret_cast<const char*>(&val), 4);
1014 #endif //GDCM_WORDS_BIGENDIAN
1017 std::ostream &binary_write(std::ostream &os, const char *val)
1019 return os.write(val, strlen(val));
1022 std::ostream &binary_write(std::ostream &os, std::string const &val)
1024 return os.write(val.c_str(), val.size());
1027 } // end namespace gdcm