1 /*=========================================================================
4 Module: $RCSfile: gdcmUtil.cxx,v $
6 Date: $Date: 2005/01/10 17:09:49 $
7 Version: $Revision: 1.87 $
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
45 * \brief Provide a better 'c++' approach for sprintf
46 * For example c code is:
47 * sprintf(trash, "%04x|%04x", group , elem);
50 * std::ostringstream buf;
51 * buf << std::right << std::setw(4) << std::setfill('0') << std::hex
52 * << group << "|" << std::right << std::setw(4) << std::setfill('0')
53 * << std::hex << elem;
57 * Format("%04x|%04x", group , elem);
60 std::string Util::Format(const char *format, ...)
64 va_start(args, format);
65 vsprintf(buffer, format, args); //might be a security flaw
66 va_end(args); // Each invocation of va_start should be matched
67 // by a corresponding invocation of va_end
68 // args is then 'undefined'
75 * \brief Because not available in C++ (?)
77 void Util::Tokenize (const std::string &str,
78 std::vector<std::string> &tokens,
79 const std::string& delimiters)
81 std::string::size_type lastPos = str.find_first_not_of(delimiters,0);
82 std::string::size_type pos = str.find_first_of (delimiters,lastPos);
83 while (std::string::npos != pos || std::string::npos != lastPos)
85 tokens.push_back(str.substr(lastPos, pos - lastPos));
86 lastPos = str.find_first_not_of(delimiters, pos);
87 pos = str.find_first_of (delimiters, lastPos);
93 * \brief Because not available in C++ (?)
94 * Counts the number of occurences of a substring within a string
97 int Util::CountSubstring (const std::string &str,
98 const std::string &subStr)
100 int count = 0; // counts how many times it appears
101 std::string::size_type x = 0; // The index position in the string
105 x = str.find(subStr,x); // Find the substring
106 if (x != std::string::npos) // If present
108 count++; // increase the count
109 x += subStr.length(); // Skip this word
112 while (x != std::string::npos); // Carry on until not present
119 * \brief Weed out a string from the non-printable characters (in order
120 * to avoid corrupting the terminal of invocation when printing)
121 * @param s string to remove non printable characters from
123 std::string Util::CreateCleanString(std::string const &s)
127 for(unsigned int i=0; i<str.size(); i++)
129 if(!isprint((unsigned char)str[i]))
137 if(!isprint((unsigned char)s[str.size()-1]))
139 if(s[str.size()-1] == 0)
141 str[str.size()-1] = ' ';
151 * \brief Add a SEPARATOR to the end of the name is necessary
152 * @param pathname file/directory name to normalize
154 std::string Util::NormalizePath(std::string const &pathname)
156 const char SEPARATOR_X = '/';
157 const char SEPARATOR_WIN = '\\';
158 const std::string SEPARATOR = "/";
159 std::string name = pathname;
160 int size = name.size();
162 if( name[size-1] != SEPARATOR_X && name[size-1] != SEPARATOR_WIN )
171 * \brief Get the (directory) path from a full path file name
172 * @param fullName file/directory name to extract Path from
174 std::string Util::GetPath(std::string const &fullName)
176 std::string res = fullName;
177 int pos1 = res.rfind("/");
178 int pos2 = res.rfind("\\");
193 * \brief Get the (last) name of a full path file name
194 * @param fullName file/directory name to extract end name from
196 std::string Util::GetName(std::string const &fullName)
198 std::string filename = fullName;
200 std::string::size_type slash_pos = filename.rfind("/");
201 std::string::size_type backslash_pos = filename.rfind("\\");
202 slash_pos = slash_pos > backslash_pos ? slash_pos : backslash_pos;
203 if(slash_pos != std::string::npos)
205 return filename.substr(slash_pos + 1);
215 * \brief Get the current date of the system in a dicom string
217 std::string Util::GetCurrentDate()
222 strftime(tmp,512,"%Y%m%d", localtime(&tloc) );
228 * \brief Get the current time of the system in a dicom string
230 std::string Util::GetCurrentTime()
235 strftime(tmp,512,"%H%M%S", localtime(&tloc) );
240 * \brief Create a /DICOM/ string:
241 * It should a of even length (no odd length ever)
242 * It can contain as many (if you are reading this from your
243 * editor the following character is is backslash followed by zero
244 * that needed to be escaped with an extra backslash for doxygen) \\0
247 std::string Util::DicomString(const char *s, size_t l)
249 std::string r(s, s+l);
250 gdcmAssertMacro( !(r.size() % 2) ); // == basically 'l' is even
256 * \brief Create a /DICOM/ string:
257 * It should a of even lenght (no odd length ever)
258 * It can contain as many (if you are reading this from your
259 * editor the following character is is backslash followed by zero
260 * that needed to be escaped with an extra backslash for doxygen) \\0
262 * This function is similar to DicomString(const char*),
263 * except it doesn't take a lenght.
264 * It only pad with a null character if length is odd
266 std::string Util::DicomString(const char *s)
268 size_t l = strlen(s);
273 std::string r(s, s+l);
274 gdcmAssertMacro( !(r.size() % 2) );
280 * \brief Safely compare two Dicom String:
281 * - Both string should be of even lenght
282 * - We allow padding of even lenght string by either a null
283 * character of a space
285 bool Util::DicomStringEqual(const std::string &s1, const char *s2)
287 // s2 is the string from the DICOM reference: 'MONOCHROME1'
288 std::string s1_even = s1; //Never change input parameter
289 std::string s2_even = DicomString( s2 );
290 if( s1_even[s1_even.size()-1] == ' ')
292 s1_even[s1_even.size()-1] = '\0'; //replace space character by null
294 return s1_even == s2_even;
301 * \brief tells us if the processor we are working with is BigEndian or not
303 bool Util::IsCurrentProcessorBigEndian()
306 uint8_t bigEndianRepr[4] = { 0x00, 0x00, 0x00, 0x01 };
307 int res = memcmp(reinterpret_cast<const void*>(&intVal),
308 reinterpret_cast<const void*>(bigEndianRepr), 4);
323 typedef BOOL(WINAPI * pSnmpExtensionInit) (
324 IN DWORD dwTimeZeroReference,
325 OUT HANDLE * hPollForTrapEvent,
326 OUT AsnObjectIdentifier * supportedView);
328 typedef BOOL(WINAPI * pSnmpExtensionTrap) (
329 OUT AsnObjectIdentifier * enterprise,
330 OUT AsnInteger * genericTrap,
331 OUT AsnInteger * specificTrap,
332 OUT AsnTimeticks * timeStamp,
333 OUT RFC1157VarBindList * variableBindings);
335 typedef BOOL(WINAPI * pSnmpExtensionQuery) (
337 IN OUT RFC1157VarBindList * variableBindings,
338 OUT AsnInteger * errorStatus,
339 OUT AsnInteger * errorIndex);
341 typedef BOOL(WINAPI * pSnmpExtensionInitEx) (
342 OUT AsnObjectIdentifier * supportedView);
344 #include <strings.h> //for bzero on unix
348 #include <sys/ioctl.h>
349 #include <sys/types.h>
350 #include <sys/socket.h>
351 #include <netinet/in.h>
352 #include <linux/if.h>
356 #include <sys/types.h>
357 #include <sys/socket.h>
359 #include <net/if_dl.h>
367 #include <sys/ndd_var.h>
368 #include <sys/kinfo.h>
372 #include <CoreFoundation/CoreFoundation.h>
373 #include <IOKit/IOKitLib.h>
374 #include <IOKit/network/IOEthernetInterface.h>
375 #include <IOKit/network/IONetworkInterface.h>
376 #include <IOKit/network/IOEthernetController.h>
378 //static kern_return_t FindEthernetInterfaces(io_iterator_t *matchingServices);
379 //static kern_return_t GetMACAddress(io_iterator_t intfIterator, UInt8 *MACAddress);
381 // Returns an iterator containing the primary (built-in) Ethernet interface. The caller is responsible for
382 // releasing the iterator after the caller is done with it.
383 static kern_return_t FindEthernetInterfaces(io_iterator_t *matchingServices)
385 kern_return_t kernResult;
386 mach_port_t masterPort;
387 CFMutableDictionaryRef matchingDict;
388 CFMutableDictionaryRef propertyMatchDict;
390 // Retrieve the Mach port used to initiate communication with I/O Kit
391 kernResult = IOMasterPort(MACH_PORT_NULL, &masterPort);
392 if (KERN_SUCCESS != kernResult)
394 printf("IOMasterPort returned %d\n", kernResult);
398 // Ethernet interfaces are instances of class kIOEthernetInterfaceClass.
399 // IOServiceMatching is a convenience function to create a dictionary with the key kIOProviderClassKey and
400 // the specified value.
401 matchingDict = IOServiceMatching(kIOEthernetInterfaceClass);
403 // Note that another option here would be:
404 // matchingDict = IOBSDMatching("en0");
406 if (NULL == matchingDict)
408 printf("IOServiceMatching returned a NULL dictionary.\n");
411 // Each IONetworkInterface object has a Boolean property with the key kIOPrimaryInterface. Only the
412 // primary (built-in) interface has this property set to TRUE.
414 // IOServiceGetMatchingServices uses the default matching criteria defined by IOService. This considers
415 // only the following properties plus any family-specific matching in this order of precedence
416 // (see IOService::passiveMatch):
418 // kIOProviderClassKey (IOServiceMatching)
419 // kIONameMatchKey (IOServiceNameMatching)
420 // kIOPropertyMatchKey
422 // kIOMatchedServiceCountKey
423 // family-specific matching
424 // kIOBSDNameKey (IOBSDNameMatching)
425 // kIOLocationMatchKey
427 // The IONetworkingFamily does not define any family-specific matching. This means that in
428 // order to have IOServiceGetMatchingServices consider the kIOPrimaryInterface property, we must
429 // add that property to a separate dictionary and then add that to our matching dictionary
430 // specifying kIOPropertyMatchKey.
432 propertyMatchDict = CFDictionaryCreateMutable( kCFAllocatorDefault, 0,
433 &kCFTypeDictionaryKeyCallBacks,
434 &kCFTypeDictionaryValueCallBacks);
436 if (NULL == propertyMatchDict)
438 printf("CFDictionaryCreateMutable returned a NULL dictionary.\n");
441 // Set the value in the dictionary of the property with the given key, or add the key
442 // to the dictionary if it doesn't exist. This call retains the value object passed in.
443 CFDictionarySetValue(propertyMatchDict, CFSTR(kIOPrimaryInterface), kCFBooleanTrue);
445 // Now add the dictionary containing the matching value for kIOPrimaryInterface to our main
446 // matching dictionary. This call will retain propertyMatchDict, so we can release our reference
447 // on propertyMatchDict after adding it to matchingDict.
448 CFDictionarySetValue(matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
449 CFRelease(propertyMatchDict);
453 // IOServiceGetMatchingServices retains the returned iterator, so release the iterator when we're done with it.
454 // IOServiceGetMatchingServices also consumes a reference on the matching dictionary so we don't need to release
455 // the dictionary explicitly.
456 kernResult = IOServiceGetMatchingServices(masterPort, matchingDict, matchingServices);
457 if (KERN_SUCCESS != kernResult)
459 printf("IOServiceGetMatchingServices returned %d\n", kernResult);
465 // Given an iterator across a set of Ethernet interfaces, return the MAC address of the last one.
466 // If no interfaces are found the MAC address is set to an empty string.
467 // In this sample the iterator should contain just the primary interface.
468 static kern_return_t GetMACAddress_MAC(io_iterator_t intfIterator, UInt8 *MACAddress)
470 io_object_t intfService;
471 io_object_t controllerService;
472 kern_return_t kernResult = KERN_FAILURE;
474 // Initialize the returned address
475 bzero(MACAddress, kIOEthernetAddressSize);
477 // IOIteratorNext retains the returned object, so release it when we're done with it.
478 while ( (intfService = IOIteratorNext(intfIterator)))
480 CFTypeRef MACAddressAsCFData;
482 // IONetworkControllers can't be found directly by the IOServiceGetMatchingServices call,
483 // since they are hardware nubs and do not participate in driver matching. In other words,
484 // registerService() is never called on them. So we've found the IONetworkInterface and will
485 // get its parent controller by asking for it specifically.
487 // IORegistryEntryGetParentEntry retains the returned object, so release it when we're done with it.
488 kernResult = IORegistryEntryGetParentEntry( intfService,
490 &controllerService );
492 if (KERN_SUCCESS != kernResult)
494 printf("IORegistryEntryGetParentEntry returned 0x%08x\n", kernResult);
497 // Retrieve the MAC address property from the I/O Registry in the form of a CFData
498 MACAddressAsCFData = IORegistryEntryCreateCFProperty( controllerService,
499 CFSTR(kIOMACAddress),
502 if (MACAddressAsCFData)
504 CFShow(MACAddressAsCFData); // for display purposes only; output goes to stderr
506 // Get the raw bytes of the MAC address from the CFData
507 CFDataGetBytes(MACAddressAsCFData, CFRangeMake(0, kIOEthernetAddressSize), MACAddress);
508 CFRelease(MACAddressAsCFData);
511 // Done with the parent Ethernet controller object so we release it.
512 (void) IOObjectRelease(controllerService);
515 // Done with the Ethernet interface object so we release it.
516 (void) IOObjectRelease(intfService);
523 long GetMacAddrSys ( u_char *addr)
527 if (WSAStartup(MAKEWORD(2, 0), &WinsockData) != 0) {
528 fprintf(stderr, "This program requires Winsock 2.x!\n");
533 pSnmpExtensionInit m_Init;
534 pSnmpExtensionInitEx m_InitEx;
535 pSnmpExtensionQuery m_Query;
536 pSnmpExtensionTrap m_Trap;
537 HANDLE PollForTrapEvent;
538 AsnObjectIdentifier SupportedView;
539 UINT OID_ifEntryType[] = {
540 1, 3, 6, 1, 2, 1, 2, 2, 1, 3
542 UINT OID_ifEntryNum[] = {
543 1, 3, 6, 1, 2, 1, 2, 1
545 UINT OID_ipMACEntAddr[] = {
546 1, 3, 6, 1, 2, 1, 2, 2, 1, 6
548 AsnObjectIdentifier MIB_ifMACEntAddr =
549 { sizeof(OID_ipMACEntAddr) / sizeof(UINT), OID_ipMACEntAddr };
550 AsnObjectIdentifier MIB_ifEntryType = {
551 sizeof(OID_ifEntryType) / sizeof(UINT), OID_ifEntryType
553 AsnObjectIdentifier MIB_ifEntryNum = {
554 sizeof(OID_ifEntryNum) / sizeof(UINT), OID_ifEntryNum
556 RFC1157VarBindList varBindList;
557 RFC1157VarBind varBind[2];
558 AsnInteger errorStatus;
559 AsnInteger errorIndex;
560 AsnObjectIdentifier MIB_NULL = {
572 /* Load the SNMP dll and get the addresses of the functions
574 m_hInst = LoadLibrary("inetmib1.dll");
575 if (m_hInst < (HINSTANCE) HINSTANCE_ERROR) {
580 (pSnmpExtensionInit) GetProcAddress(m_hInst, "SnmpExtensionInit");
582 (pSnmpExtensionInitEx) GetProcAddress(m_hInst,
583 "SnmpExtensionInitEx");
585 (pSnmpExtensionQuery) GetProcAddress(m_hInst,
586 "SnmpExtensionQuery");
588 (pSnmpExtensionTrap) GetProcAddress(m_hInst, "SnmpExtensionTrap");
589 m_Init(GetTickCount(), &PollForTrapEvent, &SupportedView);
591 /* Initialize the variable list to be retrieved by m_Query */
592 varBindList.list = varBind;
593 varBind[0].name = MIB_NULL;
594 varBind[1].name = MIB_NULL;
596 /* Copy in the OID to find the number of entries in the
598 varBindList.len = 1; /* Only retrieving one item */
599 SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryNum);
601 m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
603 printf("# of adapters in this system : %i\n",
604 varBind[0].value.asnValue.number); varBindList.len = 2;
606 /* Copy in the OID of ifType, the type of interface */
607 SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryType);
609 /* Copy in the OID of ifPhysAddress, the address */
610 SNMP_oidcpy(&varBind[1].name, &MIB_ifMACEntAddr);
614 /* Submit the query. Responses will be loaded into varBindList.
615 We can expect this call to succeed a # of times corresponding
616 to the # of adapters reported to be in the system */
618 m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
619 &errorIndex); if (!ret) ret = 1;
622 /* Confirm that the proper type has been returned */
624 SNMP_oidncmp(&varBind[0].name, &MIB_ifEntryType,
625 MIB_ifEntryType.idLength); if (!ret) {
627 dtmp = varBind[0].value.asnValue.number;
628 printf("Interface #%i type : %i\n", j, dtmp);
630 /* Type 6 describes ethernet interfaces */
633 /* Confirm that we have an address here */
635 SNMP_oidncmp(&varBind[1].name, &MIB_ifMACEntAddr,
636 MIB_ifMACEntAddr.idLength);
638 && (varBind[1].value.asnValue.address.stream != NULL)) {
640 (varBind[1].value.asnValue.address.stream[0] ==
642 && (varBind[1].value.asnValue.address.stream[1] ==
644 && (varBind[1].value.asnValue.address.stream[2] ==
646 && (varBind[1].value.asnValue.address.stream[3] ==
648 && (varBind[1].value.asnValue.address.stream[4] ==
651 /* Ignore all dial-up networking adapters */
652 printf("Interface #%i is a DUN adapter\n", j);
656 (varBind[1].value.asnValue.address.stream[0] ==
658 && (varBind[1].value.asnValue.address.stream[1] ==
660 && (varBind[1].value.asnValue.address.stream[2] ==
662 && (varBind[1].value.asnValue.address.stream[3] ==
664 && (varBind[1].value.asnValue.address.stream[4] ==
666 && (varBind[1].value.asnValue.address.stream[5] ==
669 /* Ignore NULL addresses returned by other network
671 printf("Interface #%i is a NULL address\n", j);
674 //sprintf((char*)addr, "%02x%02x%02x%02x%02x%02x",
675 // varBind[1].value.asnValue.address.stream[0],
676 // varBind[1].value.asnValue.address.stream[1],
677 // varBind[1].value.asnValue.address.stream[2],
678 // varBind[1].value.asnValue.address.stream[3],
679 // varBind[1].value.asnValue.address.stream[4],
680 // varBind[1].value.asnValue.address.stream[5]);
681 memcpy( addr, varBind[1].value.asnValue.address.stream, 6);
682 //printf("MAC Address of interface #%i: %s\n", j, addr);
686 } while (!ret); /* Stop only on an error. An error will occur
687 when we go exhaust the list of interfaces to
691 /* Free the bindings */
692 SNMP_FreeVarBind(&varBind[0]);
693 SNMP_FreeVarBind(&varBind[1]);
697 /* implementation for Linux */
706 s = socket(AF_INET, SOCK_DGRAM, 0);
711 ifc.ifc_len = sizeof(buf);
713 ioctl(s, SIOCGIFCONF, &ifc);
716 for (i = ifc.ifc_len / sizeof(struct ifreq); --i >= 0; IFR++) {
718 strcpy(ifr.ifr_name, IFR->ifr_name);
719 if (ioctl(s, SIOCGIFFLAGS, &ifr) == 0) {
720 if (! (ifr.ifr_flags & IFF_LOOPBACK)) {
721 if (ioctl(s, SIOCGIFHWADDR, &ifr) == 0) {
731 bcopy( ifr.ifr_hwaddr.sa_data, addr, 6);
739 /* implementation for FreeBSD */
741 struct ifaddrs *ifap, *ifaphead;
743 const struct sockaddr_dl *sdl;
747 rtnerr = getifaddrs(&ifaphead);
753 for (ifap = ifaphead; ifap; ifap = ifap->ifa_next) {
755 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;
759 if (ap && alen > 0) {
762 //printf ("%s:", ifap->ifa_name);
763 //for (i = 0; i < alen; i++, ap++)
765 //printf("%c%02x", i > 0 ? ':' : ' ', 0xff&*ap);
774 freeifaddrs(ifaphead);
778 /* implementation for HP-UX */
781 #define LAN_DEV0 "/dev/lan0"
784 struct fis iocnt_block;
786 char net_buf[sizeof(LAN_DEV0)+1];
789 (void)sprintf(net_buf, "%s", LAN_DEV0);
790 p = net_buf + strlen(net_buf) - 1;
793 * Get 802.3 address from card by opening the driver and interrogating it.
795 for (i = 0; i < 10; i++, (*p)++) {
796 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)
806 if (fd == -1 || iocnt_block.vtype != 6) {
810 bcopy( &iocnt_block.value.s[0], addr, 6);
815 /* implementation for AIX */
819 struct kinfo_ndd *nddp;
821 size = getkerninfo(KINFO_NDD, 0, 0, 0);
825 nddp = (struct kinfo_ndd *)malloc(size);
830 if (getkerninfo(KINFO_NDD, nddp, &size, 0) < 0) {
834 bcopy(nddp->ndd_addr, addr, 6);
840 kern_return_t kernResult = KERN_SUCCESS; // on PowerPC this is an int (4 bytes)
842 * error number layout as follows (see mach/error.h and IOKit/IOReturn.h):
845 * | system(6) | subsystem(12) | code(14) |
848 io_iterator_t intfIterator;
849 UInt8 MACAddress[ kIOEthernetAddressSize ];
851 kernResult = FindEthernetInterfaces(&intfIterator);
853 if (KERN_SUCCESS != kernResult)
855 printf("FindEthernetInterfaces returned 0x%08x\n", kernResult);
858 kernResult = GetMACAddress_MAC(intfIterator, MACAddress);
860 if (KERN_SUCCESS != kernResult)
862 printf("GetMACAddress returned 0x%08x\n", kernResult);
866 (void) IOObjectRelease(intfIterator); // Release the iterator.
868 memcpy(addr, MACAddress, kIOEthernetAddressSize);
872 /* Not implemented platforms */
877 std::string Util::GetMACAddress()
879 // This is a rip from: http://cplus.kompf.de/macaddr.html for Linux, HPUX and AIX
880 // and http://tangentsoft.net/wskfaq/examples/src/snmpmac.cpp for windows version
881 // and http://groups-beta.google.com/group/sol.lists.freebsd.hackers/msg/0d0f862e05fce6c0 for the FreeBSD version
882 // and http://developer.apple.com/samplecode/GetPrimaryMACAddress/GetPrimaryMACAddress.html for MacOSX version
887 stat = GetMacAddrSys( addr);
890 //printf( "MAC address = ");
891 for (int i=0; i<6; ++i)
893 //printf("%2.2x", addr[i]);
894 macaddr += Format("%2.2x", addr[i]);
901 //printf( "No MAC address !\n" );
908 * \brief Return the IP adress of the machine writting the DICOM image
910 std::string Util::GetIPAddress()
912 // This is a rip from http://www.codeguru.com/Cpp/I-N/internet/network/article.php/c3445/
913 #ifndef HOST_NAME_MAX
914 // SUSv2 guarantees that `Host names are limited to 255 bytes'.
915 // POSIX 1003.1-2001 guarantees that `Host names (not including the
916 // terminating NUL) are limited to HOST_NAME_MAX bytes'.
917 # define HOST_NAME_MAX 255
918 // In this case we should maybe check the string was not truncated.
919 // But I don't known how to check that...
920 #if defined(_MSC_VER) || defined(__BORLANDC__)
921 // with WinSock DLL we need to initialise the WinSock before using gethostname
922 WORD wVersionRequested = MAKEWORD(1,0);
924 int err = WSAStartup(wVersionRequested,&WSAData);
926 /* Tell the user that we could not find a usable */
933 #endif //HOST_NAME_MAX
936 char szHostName[HOST_NAME_MAX+1];
937 int r = gethostname(szHostName, HOST_NAME_MAX);
942 struct hostent *pHost = gethostbyname(szHostName);
944 for( int i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
946 for( int j = 0; j<pHost->h_length; j++ )
948 if( j > 0 ) str += ".";
950 str += Util::Format("%u",
951 (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);
953 // str now contains one local IP address
955 #if defined(_MSC_VER) || defined(__BORLANDC__)
961 // If an error occur r == -1
962 // Most of the time it will return 127.0.0.1...
968 * \brief Creates a new UID. As stipulate in the DICOM ref
969 * each time a DICOM image is create it should have
970 * a unique identifier (URI)
972 std::string Util::CreateUniqueUID(const std::string &root)
974 // The code works as follow:
975 // echo "gdcm" | od -b
976 // 0000000 147 144 143 155 012
977 // Therefore we return
978 // radical + 147.144.143.155 + IP + time()
979 std::string radical = root;
980 if( !root.size() ) //anything better ?
982 radical = "0.0."; // Is this really usefull ?
985 // A root was specified use it to forge our new UID:
986 radical += "147.144.143.155"; // gdcm
988 radical += Util::GetIPAddress();
990 radical += Util::GetCurrentDate();
992 radical += Util::GetCurrentTime();
998 std::ostream &binary_write(std::ostream &os, const T &val)
1000 return os.write(reinterpret_cast<const char*>(&val), sizeof val);
1003 std::ostream &binary_write(std::ostream &os, const uint16_t &val)
1005 #ifdef GDCM_WORDS_BIGENDIAN
1007 swap = ((( val << 8 ) & 0x0ff00 ) | (( val >> 8 ) & 0x00ff ) );
1008 return os.write(reinterpret_cast<const char*>(&swap), 2);
1010 return os.write(reinterpret_cast<const char*>(&val), 2);
1011 #endif //GDCM_WORDS_BIGENDIAN
1014 std::ostream &binary_write(std::ostream &os, const uint32_t &val)
1016 #ifdef GDCM_WORDS_BIGENDIAN
1018 swap = ( ((val<<24) & 0xff000000) | ((val<<8) & 0x00ff0000) |
1019 ((val>>8) & 0x0000ff00) | ((val>>24) & 0x000000ff) );
1020 return os.write(reinterpret_cast<const char*>(&swap), 4);
1022 return os.write(reinterpret_cast<const char*>(&val), 4);
1023 #endif //GDCM_WORDS_BIGENDIAN
1026 std::ostream &binary_write(std::ostream &os, const char *val)
1028 return os.write(val, strlen(val));
1031 std::ostream &binary_write(std::ostream &os, std::string const &val)
1033 return os.write(val.c_str(), val.size());
1036 } // end namespace gdcm