1 /*=========================================================================
4 Module: $RCSfile: gdcmUtil.cxx,v $
6 Date: $Date: 2005/01/15 03:49:49 $
7 Version: $Revision: 1.91 $
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
53 #if defined(__linux__) || defined(__CYGWIN__)
54 #include <sys/ioctl.h>
55 #include <sys/types.h>
56 #include <sys/socket.h>
57 #include <netinet/in.h>
64 #include <sys/types.h>
65 #include <sys/socket.h>
67 #include <net/if_dl.h>
75 #include <sys/ndd_var.h>
76 #include <sys/kinfo.h>
80 #include <CoreFoundation/CoreFoundation.h>
81 #include <IOKit/IOKitLib.h>
82 #include <IOKit/network/IOEthernetInterface.h>
83 #include <IOKit/network/IONetworkInterface.h>
84 #include <IOKit/network/IOEthernetController.h>
86 // End For GetMACAddress
92 * \brief Provide a better 'c++' approach for sprintf
93 * For example c code is:
94 * sprintf(trash, "%04x|%04x", group , elem);
97 * std::ostringstream buf;
98 * buf << std::right << std::setw(4) << std::setfill('0') << std::hex
99 * << group << "|" << std::right << std::setw(4) << std::setfill('0')
100 * << std::hex << elem;
104 * Format("%04x|%04x", group , elem);
107 std::string Util::Format(const char *format, ...)
111 va_start(args, format);
112 vsprintf(buffer, format, args); //might be a security flaw
113 va_end(args); // Each invocation of va_start should be matched
114 // by a corresponding invocation of va_end
115 // args is then 'undefined'
122 * \brief Because not available in C++ (?)
124 void Util::Tokenize (const std::string &str,
125 std::vector<std::string> &tokens,
126 const std::string& delimiters)
128 std::string::size_type lastPos = str.find_first_not_of(delimiters,0);
129 std::string::size_type pos = str.find_first_of (delimiters,lastPos);
130 while (std::string::npos != pos || std::string::npos != lastPos)
132 tokens.push_back(str.substr(lastPos, pos - lastPos));
133 lastPos = str.find_first_not_of(delimiters, pos);
134 pos = str.find_first_of (delimiters, lastPos);
140 * \brief Because not available in C++ (?)
141 * Counts the number of occurences of a substring within a string
144 int Util::CountSubstring (const std::string &str,
145 const std::string &subStr)
147 int count = 0; // counts how many times it appears
148 std::string::size_type x = 0; // The index position in the string
152 x = str.find(subStr,x); // Find the substring
153 if (x != std::string::npos) // If present
155 count++; // increase the count
156 x += subStr.length(); // Skip this word
159 while (x != std::string::npos); // Carry on until not present
166 * \brief Weed out a string from the non-printable characters (in order
167 * to avoid corrupting the terminal of invocation when printing)
168 * @param s string to remove non printable characters from
170 std::string Util::CreateCleanString(std::string const &s)
174 for(unsigned int i=0; i<str.size(); i++)
176 if(!isprint((unsigned char)str[i]))
184 if(!isprint((unsigned char)s[str.size()-1]))
186 if(s[str.size()-1] == 0)
188 str[str.size()-1] = ' ';
198 * \brief Add a SEPARATOR to the end of the name is necessary
199 * @param pathname file/directory name to normalize
201 std::string Util::NormalizePath(std::string const &pathname)
203 const char SEPARATOR_X = '/';
204 const char SEPARATOR_WIN = '\\';
205 const std::string SEPARATOR = "/";
206 std::string name = pathname;
207 int size = name.size();
209 if( name[size-1] != SEPARATOR_X && name[size-1] != SEPARATOR_WIN )
218 * \brief Get the (directory) path from a full path file name
219 * @param fullName file/directory name to extract Path from
221 std::string Util::GetPath(std::string const &fullName)
223 std::string res = fullName;
224 int pos1 = res.rfind("/");
225 int pos2 = res.rfind("\\");
240 * \brief Get the (last) name of a full path file name
241 * @param fullName file/directory name to extract end name from
243 std::string Util::GetName(std::string const &fullName)
245 std::string filename = fullName;
247 std::string::size_type slash_pos = filename.rfind("/");
248 std::string::size_type backslash_pos = filename.rfind("\\");
249 slash_pos = slash_pos > backslash_pos ? slash_pos : backslash_pos;
250 if(slash_pos != std::string::npos)
252 return filename.substr(slash_pos + 1);
262 * \brief Get the current date of the system in a dicom string
264 std::string Util::GetCurrentDate()
269 strftime(tmp,512,"%Y%m%d", localtime(&tloc) );
275 * \brief Get the current time of the system in a dicom string
277 std::string Util::GetCurrentTime()
282 strftime(tmp,512,"%H%M%S", localtime(&tloc) );
287 * \brief Create a /DICOM/ string:
288 * It should a of even length (no odd length ever)
289 * It can contain as many (if you are reading this from your
290 * editor the following character is is backslash followed by zero
291 * that needed to be escaped with an extra backslash for doxygen) \\0
294 std::string Util::DicomString(const char *s, size_t l)
296 std::string r(s, s+l);
297 gdcmAssertMacro( !(r.size() % 2) ); // == basically 'l' is even
303 * \brief Create a /DICOM/ string:
304 * It should a of even lenght (no odd length ever)
305 * It can contain as many (if you are reading this from your
306 * editor the following character is is backslash followed by zero
307 * that needed to be escaped with an extra backslash for doxygen) \\0
309 * This function is similar to DicomString(const char*),
310 * except it doesn't take a lenght.
311 * It only pad with a null character if length is odd
313 std::string Util::DicomString(const char *s)
315 size_t l = strlen(s);
320 std::string r(s, s+l);
321 gdcmAssertMacro( !(r.size() % 2) );
327 * \brief Safely compare two Dicom String:
328 * - Both string should be of even lenght
329 * - We allow padding of even lenght string by either a null
330 * character of a space
332 bool Util::DicomStringEqual(const std::string &s1, const char *s2)
334 // s2 is the string from the DICOM reference: 'MONOCHROME1'
335 std::string s1_even = s1; //Never change input parameter
336 std::string s2_even = DicomString( s2 );
337 if( s1_even[s1_even.size()-1] == ' ')
339 s1_even[s1_even.size()-1] = '\0'; //replace space character by null
341 return s1_even == s2_even;
348 * \brief tells us if the processor we are working with is BigEndian or not
350 bool Util::IsCurrentProcessorBigEndian()
352 #ifdef GDCM_WORDS_BIGENDIAN
362 typedef BOOL(WINAPI * pSnmpExtensionInit) (
363 IN DWORD dwTimeZeroReference,
364 OUT HANDLE * hPollForTrapEvent,
365 OUT AsnObjectIdentifier * supportedView);
367 typedef BOOL(WINAPI * pSnmpExtensionTrap) (
368 OUT AsnObjectIdentifier * enterprise,
369 OUT AsnInteger * genericTrap,
370 OUT AsnInteger * specificTrap,
371 OUT AsnTimeticks * timeStamp,
372 OUT RFC1157VarBindList * variableBindings);
374 typedef BOOL(WINAPI * pSnmpExtensionQuery) (
376 IN OUT RFC1157VarBindList * variableBindings,
377 OUT AsnInteger * errorStatus,
378 OUT AsnInteger * errorIndex);
380 typedef BOOL(WINAPI * pSnmpExtensionInitEx) (
381 OUT AsnObjectIdentifier * supportedView);
386 // Returns an iterator containing the primary (built-in) Ethernet interface.
387 // The caller is responsible for releasing the iterator after the caller is
389 static kern_return_t FindEthernetInterfaces(io_iterator_t *matchingServices)
391 kern_return_t kernResult;
392 mach_port_t masterPort;
393 CFMutableDictionaryRef matchingDict;
394 CFMutableDictionaryRef propertyMatchDict;
396 // Retrieve the Mach port used to initiate communication with I/O Kit
397 kernResult = IOMasterPort(MACH_PORT_NULL, &masterPort);
398 if (KERN_SUCCESS != kernResult)
400 printf("IOMasterPort returned %d\n", kernResult);
404 // Ethernet interfaces are instances of class kIOEthernetInterfaceClass.
405 // IOServiceMatching is a convenience function to create a dictionary
406 // with the key kIOProviderClassKey and
407 // the specified value.
408 matchingDict = IOServiceMatching(kIOEthernetInterfaceClass);
410 // Note that another option here would be:
411 // matchingDict = IOBSDMatching("en0");
413 if (NULL == matchingDict)
415 printf("IOServiceMatching returned a NULL dictionary.\n");
419 // Each IONetworkInterface object has a Boolean property with the
420 // key kIOPrimaryInterface. Only the
421 // primary (built-in) interface has this property set to TRUE.
423 // IOServiceGetMatchingServices uses the default matching criteria
424 // defined by IOService. This considers
425 // only the following properties plus any family-specific matching
426 // in this order of precedence
427 // (see IOService::passiveMatch):
429 // kIOProviderClassKey (IOServiceMatching)
430 // kIONameMatchKey (IOServiceNameMatching)
431 // kIOPropertyMatchKey
433 // kIOMatchedServiceCountKey
434 // family-specific matching
435 // kIOBSDNameKey (IOBSDNameMatching)
436 // kIOLocationMatchKey
438 // The IONetworkingFamily does not define any family-specific
439 // matching. This means that in order to have
440 // IOServiceGetMatchingServices consider the kIOPrimaryInterface
441 // property, we must add that property to a separate dictionary and
442 // then add that to our matching dictionary specifying
443 // kIOPropertyMatchKey.
446 CFDictionaryCreateMutable( kCFAllocatorDefault, 0,
447 &kCFTypeDictionaryKeyCallBacks,
448 &kCFTypeDictionaryValueCallBacks);
450 if (NULL == propertyMatchDict)
452 printf("CFDictionaryCreateMutable returned a NULL dictionary.\n");
456 // Set the value in the dictionary of the property with the given
457 // key, or add the key to the dictionary if it doesn't exist.
458 // This call retains the value object passed in.
459 CFDictionarySetValue(propertyMatchDict, CFSTR(kIOPrimaryInterface),
462 // Now add the dictionary containing the matching value for
463 // kIOPrimaryInterface to our main matching dictionary. This call
464 // will retain propertyMatchDict, so we can release our reference
465 // on propertyMatchDict after adding it to matchingDict.
466 CFDictionarySetValue(matchingDict, CFSTR(kIOPropertyMatchKey),
468 CFRelease(propertyMatchDict);
472 // IOServiceGetMatchingServices retains the returned iterator, so release
473 // the iterator when we're done with it.
474 // IOServiceGetMatchingServices also consumes a reference on the matching
475 // dictionary so we don't need to release the dictionary explicitly.
477 IOServiceGetMatchingServices(masterPort, matchingDict, matchingServices);
478 if (KERN_SUCCESS != kernResult)
480 printf("IOServiceGetMatchingServices returned %d\n", kernResult);
486 // Given an iterator across a set of Ethernet interfaces, return the MAC
487 // address of the last one.
488 // If no interfaces are found the MAC address is set to an empty string.
489 // In this sample the iterator should contain just the primary interface.
490 static kern_return_t GetMACAddress_MAC(io_iterator_t intfIterator,
493 io_object_t intfService;
494 io_object_t controllerService;
495 kern_return_t kernResult = KERN_FAILURE;
497 // Initialize the returned address
498 bzero(MACAddress, kIOEthernetAddressSize);
500 // IOIteratorNext retains the returned object, so release it when we're
502 while ( (intfService = IOIteratorNext(intfIterator)))
504 CFTypeRef MACAddressAsCFData;
506 // IONetworkControllers can't be found directly by the
507 // IOServiceGetMatchingServices call, since they are hardware nubs
508 // and do not participate in driver matching. In other words,
509 // registerService() is never called on them. So we've found the
510 // IONetworkInterface and will
511 // get its parent controller by asking for it specifically.
513 // IORegistryEntryGetParentEntry retains the returned object, so
514 // release it when we're done with it.
515 kernResult = IORegistryEntryGetParentEntry( intfService,
517 &controllerService );
519 if (KERN_SUCCESS != kernResult)
521 printf("IORegistryEntryGetParentEntry returned 0x%08x\n", kernResult);
525 // Retrieve the MAC address property from the I/O Registry in the
528 IORegistryEntryCreateCFProperty( controllerService,
529 CFSTR(kIOMACAddress),
532 if (MACAddressAsCFData)
534 // for display purposes only; output goes to stderr
535 //CFShow(MACAddressAsCFData);
537 // Get the raw bytes of the MAC address from the CFData
538 CFDataGetBytes(MACAddressAsCFData,
539 CFRangeMake(0, kIOEthernetAddressSize),
541 CFRelease(MACAddressAsCFData);
544 // Done with the parent Ethernet controller object so we release it.
545 (void) IOObjectRelease(controllerService);
548 // Done with the Ethernet interface object so we release it.
549 (void) IOObjectRelease(intfService);
556 long GetMacAddrSys ( u_char *addr)
560 if (WSAStartup(MAKEWORD(2, 0), &WinsockData) != 0)
562 std::cerr << "This program requires Winsock 2.x!" << std::endl;
566 HANDLE PollForTrapEvent;
567 AsnObjectIdentifier SupportedView;
568 UINT OID_ifEntryType[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 3 };
569 UINT OID_ifEntryNum[] = { 1, 3, 6, 1, 2, 1, 2, 1 };
570 UINT OID_ipMACEntAddr[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 6 };
571 AsnObjectIdentifier MIB_ifMACEntAddr = {
572 sizeof(OID_ipMACEntAddr) / sizeof(UINT), OID_ipMACEntAddr };
573 AsnObjectIdentifier MIB_ifEntryType = {
574 sizeof(OID_ifEntryType) / sizeof(UINT), OID_ifEntryType };
575 AsnObjectIdentifier MIB_ifEntryNum = {
576 sizeof(OID_ifEntryNum) / sizeof(UINT), OID_ifEntryNum };
577 RFC1157VarBindList varBindList;
578 RFC1157VarBind varBind[2];
579 AsnInteger errorStatus;
580 AsnInteger errorIndex;
581 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)
594 pSnmpExtensionInit m_Init =
595 (pSnmpExtensionInit) GetProcAddress(m_hInst, "SnmpExtensionInit");
596 pSnmpExtensionInitEx m_InitEx =
597 (pSnmpExtensionInitEx) GetProcAddress(m_hInst, "SnmpExtensionInitEx");
598 pSnmpExtensionQuery m_Query =
599 (pSnmpExtensionQuery) GetProcAddress(m_hInst, "SnmpExtensionQuery");
600 pSnmpExtensionTrap m_Trap =
601 (pSnmpExtensionTrap) GetProcAddress(m_hInst, "SnmpExtensionTrap");
602 m_Init(GetTickCount(), &PollForTrapEvent, &SupportedView);
604 /* Initialize the variable list to be retrieved by m_Query */
605 varBindList.list = varBind;
606 varBind[0].name = MIB_NULL;
607 varBind[1].name = MIB_NULL;
609 // Copy in the OID to find the number of entries in the
611 varBindList.len = 1; // Only retrieving one item
612 SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryNum);
613 ret = m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
615 // printf("# of adapters in this system : %i\n",
616 // varBind[0].value.asnValue.number); varBindList.len = 2;
618 // Copy in the OID of ifType, the type of interface
619 SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryType);
621 // Copy in the OID of ifPhysAddress, the address
622 SNMP_oidcpy(&varBind[1].name, &MIB_ifMACEntAddr);
626 // Submit the query. Responses will be loaded into varBindList.
627 // We can expect this call to succeed a # of times corresponding
628 // to the # of adapters reported to be in the system
629 ret = m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
637 // Confirm that the proper type has been returned
638 ret = SNMP_oidncmp(&varBind[0].name, &MIB_ifEntryType,
639 MIB_ifEntryType.idLength);
644 dtmp = varBind[0].value.asnValue.number;
645 printf("Interface #%i type : %i\n", j, dtmp);
647 // Type 6 describes ethernet interfaces
650 // Confirm that we have an address here
651 ret = SNMP_oidncmp(&varBind[1].name, &MIB_ifMACEntAddr,
652 MIB_ifMACEntAddr.idLength);
653 if ( !ret && varBind[1].value.asnValue.address.stream != NULL )
655 if ( (varBind[1].value.asnValue.address.stream[0] == 0x44)
656 && (varBind[1].value.asnValue.address.stream[1] == 0x45)
657 && (varBind[1].value.asnValue.address.stream[2] == 0x53)
658 && (varBind[1].value.asnValue.address.stream[3] == 0x54)
659 && (varBind[1].value.asnValue.address.stream[4] == 0x00) )
661 // Ignore all dial-up networking adapters
662 printf("Interface #%i is a DUN adapter\n", j);
665 if ( (varBind[1].value.asnValue.address.stream[0] == 0x00)
666 && (varBind[1].value.asnValue.address.stream[1] == 0x00)
667 && (varBind[1].value.asnValue.address.stream[2] == 0x00)
668 && (varBind[1].value.asnValue.address.stream[3] == 0x00)
669 && (varBind[1].value.asnValue.address.stream[4] == 0x00)
670 && (varBind[1].value.asnValue.address.stream[5] == 0x00) )
672 // Ignore NULL addresses returned by other network
674 printf("Interface #%i is a NULL address\n", j);
677 memcpy( addr, varBind[1].value.asnValue.address.stream, 6);
684 SNMP_FreeVarBind(&varBind[0]);
685 SNMP_FreeVarBind(&varBind[1]);
689 // implementation for GNU/Linux and cygwin
690 #if defined(__linux__) || defined(__CYGWIN__)
698 s = socket(AF_INET, SOCK_DGRAM, 0);
704 ifc.ifc_len = sizeof(buf);
706 ioctl(s, SIOCGIFCONF, &ifc);
709 for (i = ifc.ifc_len / sizeof(struct ifreq); --i >= 0; IFR++)
711 strcpy(ifr.ifr_name, IFR->ifr_name);
712 if (ioctl(s, SIOCGIFFLAGS, &ifr) == 0)
714 if (! (ifr.ifr_flags & IFF_LOOPBACK))
716 if (ioctl(s, SIOCGIFHWADDR, &ifr) == 0)
728 bcopy( ifr.ifr_hwaddr.sa_data, addr, 6);
737 // implementation for FreeBSD
739 struct ifaddrs *ifap, *ifaphead;
741 const struct sockaddr_dl *sdl;
745 rtnerr = getifaddrs(&ifaphead);
752 for (ifap = ifaphead; ifap; ifap = ifap->ifa_next)
754 if (ifap->ifa_addr->sa_family == AF_LINK)
756 sdl = (const struct sockaddr_dl *) ifap->ifa_addr;
757 ap = ((caddr_t)((sdl)->sdl_data + (sdl)->sdl_nlen));
758 alen = sdl->sdl_alen;
763 //printf ("%s:", ifap->ifa_name);
764 //for (i = 0; i < alen; i++, ap++)
766 //printf("%c%02x", i > 0 ? ':' : ' ', 0xff&*ap);
775 freeifaddrs(ifaphead);
779 // implementation for HP-UX
781 const char LAN_DEV0[] = "/dev/lan0";
784 struct fis iocnt_block;
785 char net_buf[sizeof(LAN_DEV0)+1];
787 (void)sprintf(net_buf, "%s", LAN_DEV0);
788 char *p = net_buf + strlen(net_buf) - 1;
791 // Get 802.3 address from card by opening the driver and interrogating it.
793 for (int i = 0; i < 10; i++, (*p)++)
795 if ((fd = open (net_buf, O_RDONLY)) != -1)
797 iocnt_block.reqtype = LOCAL_ADDRESS;
798 ioctl (fd, NETSTAT, &iocnt_block);
801 if (iocnt_block.vtype == 6) break;
805 if (fd == -1 || iocnt_block.vtype != 6)
810 bcopy( &iocnt_block.value.s[0], addr, 6);
814 /* implementation for AIX */
816 int size = getkerninfo(KINFO_NDD, 0, 0, 0);
821 struct kinfo_ndd *nddp = (struct kinfo_ndd *)malloc(size);
827 if (getkerninfo(KINFO_NDD, nddp, &size, 0) < 0)
832 bcopy(nddp->ndd_addr, addr, 6);
839 io_iterator_t intfIterator;
840 UInt8 MACAddress[ kIOEthernetAddressSize ];
842 kern_return_t kernResult = FindEthernetInterfaces(&intfIterator);
844 if (KERN_SUCCESS != kernResult)
846 printf("FindEthernetInterfaces returned 0x%08x\n", kernResult);
850 kernResult = GetMACAddress_MAC(intfIterator, MACAddress);
852 if (KERN_SUCCESS != kernResult)
854 printf("GetMACAddress returned 0x%08x\n", kernResult);
858 (void) IOObjectRelease(intfIterator); // Release the iterator.
860 memcpy(addr, MACAddress, kIOEthernetAddressSize);
864 /* Not implemented platforms */
869 std::string Util::GetMACAddress()
871 // This is a rip from: http://cplus.kompf.de/macaddr.html for Linux/CYGWIN, HPUX and AIX
872 // and http://tangentsoft.net/wskfaq/examples/src/snmpmac.cpp for windows version
873 // and http://groups-beta.google.com/group/sol.lists.freebsd.hackers/msg/0d0f862e05fce6c0 for the FreeBSD version
874 // and http://developer.apple.com/samplecode/GetPrimaryMACAddress/GetPrimaryMACAddress.html for MacOSX version
878 long stat = GetMacAddrSys(addr);
881 //printf( "MAC address = ");
882 for (int i=0; i<6; ++i)
884 //printf("%2.2x", addr[i]);
885 macaddr += Format("%2.2x", addr[i]);
892 //printf( "No MAC address !\n" );
899 * \brief Return the IP adress of the machine writting the DICOM image
901 std::string Util::GetIPAddress()
903 // This is a rip from
904 // http://www.codeguru.com/Cpp/I-N/internet/network/article.php/c3445/
905 #ifndef HOST_NAME_MAX
906 // SUSv2 guarantees that `Host names are limited to 255 bytes'.
907 // POSIX 1003.1-2001 guarantees that `Host names (not including the
908 // terminating NUL) are limited to HOST_NAME_MAX bytes'.
909 # define HOST_NAME_MAX 255
910 // In this case we should maybe check the string was not truncated.
911 // But I don't known how to check that...
912 #if defined(_MSC_VER) || defined(__BORLANDC__)
913 // with WinSock DLL we need to initialise the WinSock before using gethostname
914 WORD wVersionRequested = MAKEWORD(1,0);
916 int err = WSAStartup(wVersionRequested,&WSAData);
919 // Tell the user that we could not find a usable
926 #endif //HOST_NAME_MAX
929 char szHostName[HOST_NAME_MAX+1];
930 int r = gethostname(szHostName, HOST_NAME_MAX);
935 struct hostent *pHost = gethostbyname(szHostName);
937 for( int i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
939 for( int j = 0; j<pHost->h_length; j++ )
941 if( j > 0 ) str += ".";
943 str += Util::Format("%u",
944 (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);
946 // str now contains one local IP address
948 #if defined(_MSC_VER) || defined(__BORLANDC__)
954 // If an error occur r == -1
955 // Most of the time it will return 127.0.0.1...
961 * \brief Creates a new UID. As stipulate in the DICOM ref
962 * each time a DICOM image is create it should have
963 * a unique identifier (URI)
965 std::string Util::CreateUniqueUID(const std::string &root)
967 // The code works as follow:
968 // echo "gdcm" | od -b
969 // 0000000 147 144 143 155 012
970 // Therefore we return
971 // radical + 147.144.143.155 + IP + time()
972 std::string radical = root;
973 if( !root.size() ) //anything better ?
975 radical = "0.0."; // Is this really usefull ?
978 // A root was specified use it to forge our new UID:
979 radical += "147.144.143.155"; // gdcm
981 radical += Util::GetIPAddress();
983 radical += Util::GetCurrentDate();
985 radical += Util::GetCurrentTime();
991 std::ostream &binary_write(std::ostream &os, const T &val)
993 return os.write(reinterpret_cast<const char*>(&val), sizeof val);
996 std::ostream &binary_write(std::ostream &os, const uint16_t &val)
998 #ifdef GDCM_WORDS_BIGENDIAN
1000 swap = ((( val << 8 ) & 0x0ff00 ) | (( val >> 8 ) & 0x00ff ) );
1001 return os.write(reinterpret_cast<const char*>(&swap), 2);
1003 return os.write(reinterpret_cast<const char*>(&val), 2);
1004 #endif //GDCM_WORDS_BIGENDIAN
1007 std::ostream &binary_write(std::ostream &os, const uint32_t &val)
1009 #ifdef GDCM_WORDS_BIGENDIAN
1011 swap = ( ((val<<24) & 0xff000000) | ((val<<8) & 0x00ff0000) |
1012 ((val>>8) & 0x0000ff00) | ((val>>24) & 0x000000ff) );
1013 return os.write(reinterpret_cast<const char*>(&swap), 4);
1015 return os.write(reinterpret_cast<const char*>(&val), 4);
1016 #endif //GDCM_WORDS_BIGENDIAN
1019 std::ostream &binary_write(std::ostream &os, const char *val)
1021 return os.write(val, strlen(val));
1024 std::ostream &binary_write(std::ostream &os, std::string const &val)
1026 return os.write(val.c_str(), val.size());
1029 } // end namespace gdcm