1 /*=========================================================================
4 Module: $RCSfile: gdcmUtil.cxx,v $
6 Date: $Date: 2005/07/05 23:50:19 $
7 Version: $Revision: 1.156 $
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 Weed out a string from the non-printable characters (in order
184 * to avoid corrupting the terminal of invocation when printing)
185 * @param s string to remove non printable characters from
187 std::string Util::CreateCleanString(std::string const &s)
191 for(unsigned int i=0; i<str.size(); i++)
193 if (!isprint((unsigned char)str[i]) )
201 if (!isprint((unsigned char)s[str.size()-1]) )
203 if (s[str.size()-1] == 0 )
205 str[str.size()-1] = ' ';
214 * \brief Add a SEPARATOR to the end of the name is necessary
215 * @param pathname file/directory name to normalize
217 std::string Util::NormalizePath(std::string const &pathname)
219 const char SEPARATOR_X = '/';
220 const char SEPARATOR_WIN = '\\';
221 const std::string SEPARATOR = "/";
222 std::string name = pathname;
223 int size = name.size();
225 if ( name[size-1] != SEPARATOR_X && name[size-1] != SEPARATOR_WIN )
233 * \brief Get the (directory) path from a full path file name
234 * @param fullName file/directory name to extract Path from
236 std::string Util::GetPath(std::string const &fullName)
238 std::string res = fullName;
239 int pos1 = res.rfind("/");
240 int pos2 = res.rfind("\\");
254 * \brief Get the (last) name of a full path file name
255 * @param fullName file/directory name to extract end name from
257 std::string Util::GetName(std::string const &fullName)
259 std::string filename = fullName;
261 std::string::size_type slash_pos = filename.rfind("/");
262 std::string::size_type backslash_pos = filename.rfind("\\");
263 slash_pos = slash_pos > backslash_pos ? slash_pos : backslash_pos;
264 if (slash_pos != std::string::npos )
266 return filename.substr(slash_pos + 1);
275 * \brief Get the current date of the system in a dicom string
277 std::string Util::GetCurrentDate()
282 strftime(tmp,512,"%Y%m%d", localtime(&tloc) );
287 * \brief Get the current time of the system in a dicom string
289 std::string Util::GetCurrentTime()
294 strftime(tmp,512,"%H%M%S", localtime(&tloc) );
299 * \brief Get both the date and time at the same time to avoid problem
300 * around midnight where two call could be before and after midnight
302 std::string Util::GetCurrentDateTime()
308 // We need implementation specific functions to obtain millisecond precision
309 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
313 milliseconds = tb.millitm;
316 gettimeofday (&tv, NULL);
318 // Compute milliseconds from microseconds.
319 milliseconds = tv.tv_usec / 1000;
321 // Obtain the time of day, and convert it to a tm struct.
322 struct tm *ptm = localtime (&timep);
323 // Format the date and time, down to a single second.
324 strftime (tmp, sizeof (tmp), "%Y%m%d%H%M%S", ptm);
327 // Don't use Util::Format to accelerate execution of code
329 sprintf(tmpAll,"%s%03ld",tmp,milliseconds);
334 unsigned int Util::GetCurrentThreadID()
336 // FIXME the implementation is far from complete
337 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
338 return (unsigned int)GetCurrentThreadId();
342 // Doesn't work on fedora, but is in the man page...
343 //return (unsigned int)gettid();
346 return (unsigned int)thr_self();
348 //default implementation
355 unsigned int Util::GetCurrentProcessID()
357 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
358 // NOTE: There is also a _getpid()...
359 return (unsigned int)GetCurrentProcessId();
361 // get process identification, POSIX
362 return (unsigned int)getpid();
367 * \brief tells us if the processor we are working with is BigEndian or not
369 bool Util::IsCurrentProcessorBigEndian()
371 #if defined(GDCM_WORDS_BIGENDIAN)
379 * \brief Create a /DICOM/ string:
380 * It should a of even length (no odd length ever)
381 * It can contain as many (if you are reading this from your
382 * editor the following character is is backslash followed by zero
383 * that needed to be escaped with an extra backslash for doxygen) \\0
386 std::string Util::DicomString(const char *s, size_t l)
388 std::string r(s, s+l);
389 gdcmAssertMacro( !(r.size() % 2) ); // == basically 'l' is even
394 * \brief Create a /DICOM/ string:
395 * It should a of even length (no odd length ever)
396 * It can contain as many (if you are reading this from your
397 * editor the following character is backslash followed by zero
398 * that needed to be escaped with an extra backslash for doxygen) \\0
400 * This function is similar to DicomString(const char*),
401 * except it doesn't take a length.
402 * It only pad with a null character if length is odd
404 std::string Util::DicomString(const char *s)
406 size_t l = strlen(s);
411 std::string r(s, s+l);
412 gdcmAssertMacro( !(r.size() % 2) );
417 * \brief Safely compare two Dicom String:
418 * - Both string should be of even length
419 * - We allow padding of even length string by either a null
420 * character of a space
422 bool Util::DicomStringEqual(const std::string &s1, const char *s2)
424 // s2 is the string from the DICOM reference: 'MONOCHROME1'
425 std::string s1_even = s1; //Never change input parameter
426 std::string s2_even = DicomString( s2 );
427 if ( s1_even[s1_even.size()-1] == ' ' )
429 s1_even[s1_even.size()-1] = '\0'; //replace space character by null
431 return s1_even == s2_even;
435 typedef BOOL(WINAPI * pSnmpExtensionInit) (
436 IN DWORD dwTimeZeroReference,
437 OUT HANDLE * hPollForTrapEvent,
438 OUT AsnObjectIdentifier * supportedView);
440 typedef BOOL(WINAPI * pSnmpExtensionTrap) (
441 OUT AsnObjectIdentifier * enterprise,
442 OUT AsnInteger * genericTrap,
443 OUT AsnInteger * specificTrap,
444 OUT AsnTimeticks * timeStamp,
445 OUT RFC1157VarBindList * variableBindings);
447 typedef BOOL(WINAPI * pSnmpExtensionQuery) (
449 IN OUT RFC1157VarBindList * variableBindings,
450 OUT AsnInteger * errorStatus,
451 OUT AsnInteger * errorIndex);
453 typedef BOOL(WINAPI * pSnmpExtensionInitEx) (
454 OUT AsnObjectIdentifier * supportedView);
457 /// \brief gets current M.A.C adress (for internal use only)
458 int GetMacAddrSys ( unsigned char *addr );
459 int GetMacAddrSys ( unsigned char *addr )
463 if ( (WSAStartup(MAKEWORD(2, 0), &WinsockData)) != 0)
465 std::cerr << "This program requires Winsock 2.x!" << std::endl;
469 HANDLE PollForTrapEvent;
470 AsnObjectIdentifier SupportedView;
471 UINT OID_ifEntryType[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 3 };
472 UINT OID_ifEntryNum[] = { 1, 3, 6, 1, 2, 1, 2, 1 };
473 UINT OID_ipMACEntAddr[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 6 };
474 AsnObjectIdentifier MIB_ifMACEntAddr = {
475 sizeof(OID_ipMACEntAddr) / sizeof(UINT), OID_ipMACEntAddr };
476 AsnObjectIdentifier MIB_ifEntryType = {
477 sizeof(OID_ifEntryType) / sizeof(UINT), OID_ifEntryType };
478 AsnObjectIdentifier MIB_ifEntryNum = {
479 sizeof(OID_ifEntryNum) / sizeof(UINT), OID_ifEntryNum };
480 RFC1157VarBindList varBindList;
481 RFC1157VarBind varBind[2];
482 AsnInteger errorStatus;
483 AsnInteger errorIndex;
484 AsnObjectIdentifier MIB_NULL = { 0, 0 };
489 // Load the SNMP dll and get the addresses of the functions necessary
490 HINSTANCE m_hInst = LoadLibrary("inetmib1.dll");
491 if (m_hInst < (HINSTANCE) HINSTANCE_ERROR)
495 pSnmpExtensionInit m_Init =
496 (pSnmpExtensionInit) GetProcAddress(m_hInst, "SnmpExtensionInit");
497 pSnmpExtensionQuery m_Query =
498 (pSnmpExtensionQuery) GetProcAddress(m_hInst, "SnmpExtensionQuery");
499 m_Init(GetTickCount(), &PollForTrapEvent, &SupportedView);
501 /* Initialize the variable list to be retrieved by m_Query */
502 varBindList.list = varBind;
503 varBind[0].name = MIB_NULL;
504 varBind[1].name = MIB_NULL;
506 // Copy in the OID to find the number of entries in the
508 varBindList.len = 1; // Only retrieving one item
509 SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryNum);
510 m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
512 // printf("# of adapters in this system : %i\n",
513 // varBind[0].value.asnValue.number);
516 // Copy in the OID of ifType, the type of interface
517 SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryType);
519 // Copy in the OID of ifPhysAddress, the address
520 SNMP_oidcpy(&varBind[1].name, &MIB_ifMACEntAddr);
524 // Submit the query. Responses will be loaded into varBindList.
525 // We can expect this call to succeed a # of times corresponding
526 // to the # of adapters reported to be in the system
527 ret = m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
535 // Confirm that the proper type has been returned
536 ret = SNMP_oidncmp(&varBind[0].name, &MIB_ifEntryType,
537 MIB_ifEntryType.idLength);
542 dtmp = varBind[0].value.asnValue.number;
544 // Type 6 describes ethernet interfaces
547 // Confirm that we have an address here
548 ret = SNMP_oidncmp(&varBind[1].name, &MIB_ifMACEntAddr,
549 MIB_ifMACEntAddr.idLength);
550 if ( !ret && varBind[1].value.asnValue.address.stream != NULL )
552 if ( (varBind[1].value.asnValue.address.stream[0] == 0x44)
553 && (varBind[1].value.asnValue.address.stream[1] == 0x45)
554 && (varBind[1].value.asnValue.address.stream[2] == 0x53)
555 && (varBind[1].value.asnValue.address.stream[3] == 0x54)
556 && (varBind[1].value.asnValue.address.stream[4] == 0x00) )
558 // Ignore all dial-up networking adapters
559 std::cerr << "Interface #" << j << " is a DUN adapter\n";
562 if ( (varBind[1].value.asnValue.address.stream[0] == 0x00)
563 && (varBind[1].value.asnValue.address.stream[1] == 0x00)
564 && (varBind[1].value.asnValue.address.stream[2] == 0x00)
565 && (varBind[1].value.asnValue.address.stream[3] == 0x00)
566 && (varBind[1].value.asnValue.address.stream[4] == 0x00)
567 && (varBind[1].value.asnValue.address.stream[5] == 0x00) )
569 // Ignore NULL addresses returned by other network
571 std::cerr << "Interface #" << j << " is a NULL address\n";
574 memcpy( addr, varBind[1].value.asnValue.address.stream, 6);
581 SNMP_FreeVarBind(&varBind[0]);
582 SNMP_FreeVarBind(&varBind[1]);
584 #endif //Win32 version
587 // implementation for POSIX system
588 #if defined(CMAKE_HAVE_NET_IF_ARP_H) && defined(__sun)
589 //The POSIX version is broken anyway on Solaris, plus would require full
591 struct arpreq parpreq;
592 struct sockaddr_in *psa;
593 struct hostent *phost;
594 char hostname[MAXHOSTNAMELEN];
598 if (gethostname(hostname, MAXHOSTNAMELEN) != 0 )
600 perror("gethostname");
603 phost = gethostbyname(hostname);
604 paddrs = phost->h_addr_list;
606 sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
612 memset(&parpreq, 0, sizeof(struct arpreq));
613 psa = (struct sockaddr_in *) &parpreq.arp_pa;
615 memset(psa, 0, sizeof(struct sockaddr_in));
616 psa->sin_family = AF_INET;
617 memcpy(&psa->sin_addr, *paddrs, sizeof(struct in_addr));
619 status = ioctl(sock, SIOCGARP, &parpreq);
625 memcpy(addr, parpreq.arp_ha.sa_data, 6);
629 #ifdef CMAKE_HAVE_NET_IF_H
631 struct ifreq ifr, *ifrp;
636 #if defined(AF_LINK) && (!defined(SIOCGIFHWADDR) && !defined(SIOCGENADDR))
637 struct sockaddr_dl *sdlp;
641 // BSD 4.4 defines the size of an ifreq to be
642 // max(sizeof(ifreq), sizeof(ifreq.ifr_name)+ifreq.ifr_addr.sa_len
643 // However, under earlier systems, sa_len isn't present, so the size is
644 // just sizeof(struct ifreq)
645 // We should investiage the use of SIZEOF_ADDR_IFREQ
649 #define max(a,b) ((a) > (b) ? (a) : (b))
651 #define ifreq_size(i) max(sizeof(struct ifreq),\
652 sizeof((i).ifr_name)+(i).ifr_addr.sa_len)
654 #define ifreq_size(i) sizeof(struct ifreq)
655 #endif // HAVE_SA_LEN
657 if ( (sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) < 0 )
661 memset(buf, 0, sizeof(buf));
662 ifc.ifc_len = sizeof(buf);
664 if (ioctl (sd, SIOCGIFCONF, (char *)&ifc) < 0)
670 for (i = 0; i < n; i+= ifreq_size(*ifrp) )
672 ifrp = (struct ifreq *)((char *) ifc.ifc_buf+i);
673 strncpy(ifr.ifr_name, ifrp->ifr_name, IFNAMSIZ);
675 if (ioctl(sd, SIOCGIFHWADDR, &ifr) < 0)
677 a = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
680 // In theory this call should also work on Sun Solaris, but apparently
681 // SIOCGENADDR is not implemented properly thus the call
682 // ioctl(sd, SIOCGENADDR, &ifr) always returns errno=2
683 // (No such file or directory)
684 // Furthermore the DLAPI seems to require full root access
685 if (ioctl(sd, SIOCGENADDR, &ifr) < 0)
687 a = (unsigned char *) ifr.ifr_enaddr;
690 sdlp = (struct sockaddr_dl *) &ifrp->ifr_addr;
691 if ((sdlp->sdl_family != AF_LINK) || (sdlp->sdl_alen != 6))
693 a = (unsigned char *) &sdlp->sdl_data[sdlp->sdl_nlen];
695 perror("No way to access hardware");
699 #endif // SIOCGENADDR
700 #endif // SIOCGIFHWADDR
701 if (!a[0] && !a[1] && !a[2] && !a[3] && !a[4] && !a[5]) continue;
712 // Not implemented platforms
713 perror("There was a configuration problem on your plateform");
720 * \brief Mini function to return the last digit from a number express in base 256
721 * pre condition data contain an array of 6 unsigned char
722 * post condition carry contain the last digit
724 inline int getlastdigit(unsigned char *data)
726 int extended, carry = 0;
729 extended = (carry << 8) + data[i];
730 data[i] = extended / 10;
731 carry = extended % 10;
737 * \brief Encode the mac address on a fixed lenght string of 15 characters.
738 * we save space this way.
740 std::string Util::GetMACAddress()
742 // This code is the result of a long internet search to find something
743 // as compact as possible (not OS independant). We only have to separate
744 // 3 OS: Win32, SunOS and 'real' POSIX
745 // http://groups-beta.google.com/group/comp.unix.solaris/msg/ad36929d783d63be
746 // http://bdn.borland.com/article/0,1410,26040,00.html
747 unsigned char addr[6];
749 int stat = GetMacAddrSys(addr);
752 // We need to convert a 6 digit number from base 256 to base 10, using integer
753 // would requires a 48bits one. To avoid this we have to reimplement the div + modulo
760 res = getlastdigit(addr);
761 sres.insert(sres.begin(), '0' + res);
762 zero = (addr[0] == 0) && (addr[1] == 0) && (addr[2] == 0)
763 && (addr[3] == 0) && (addr[4] == 0) && (addr[5] == 0);
770 gdcmWarningMacro("Problem in finding the MAC Address");
776 * \brief Creates a new UID. As stipulate in the DICOM ref
777 * each time a DICOM image is create it should have
778 * a unique identifier (URI)
779 * @param root is the DICOM prefix assigned by IOS group
781 std::string Util::CreateUniqueUID(const std::string &root)
787 // gdcm UID prefix, as supplied by http://www.medicalconnections.co.uk
795 // A root was specified use it to forge our new UID:
797 //append += Util::GetMACAddress(); // to save CPU time
798 append += Util::GDCM_MAC_ADRESS;
800 append += Util::GetCurrentDateTime();
802 //Also add a mini random number just in case:
804 int r = (int) (100.0*rand()/RAND_MAX);
805 // Don't use Util::Format to accelerate the execution
806 sprintf(tmp,"%02d", r);
809 // If append is too long we need to rehash it
810 if ( (prefix + append).size() > 64 )
812 gdcmErrorMacro( "Size of UID is too long." );
813 // we need a hash function to truncate this number
814 // if only md5 was cross plateform
818 return prefix + append;
821 void Util::SetRootUID(const std::string &root)
829 const std::string &Util::GetRootUID()
834 //-------------------------------------------------------------------------
836 * \brief binary_write binary_write
837 * @param os ostream to write to
840 std::ostream &binary_write(std::ostream &os, const uint16_t &val)
842 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
844 //swap = ((( val << 8 ) & 0xff00 ) | (( val >> 8 ) & 0x00ff ) );
846 swap = ( val << 8 | val >> 8 );
848 return os.write(reinterpret_cast<const char*>(&swap), 2);
850 return os.write(reinterpret_cast<const char*>(&val), 2);
851 #endif //GDCM_WORDS_BIGENDIAN
855 * \brief binary_write binary_write
856 * @param os ostream to write to
859 std::ostream &binary_write(std::ostream &os, const uint32_t &val)
861 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
863 // swap = ( ((val<<24) & 0xff000000) | ((val<<8) & 0x00ff0000) |
864 // ((val>>8) & 0x0000ff00) | ((val>>24) & 0x000000ff) );
866 swap = ( (val<<24) | ((val<<8) & 0x00ff0000) |
867 ((val>>8) & 0x0000ff00) | (val>>24) );
868 return os.write(reinterpret_cast<const char*>(&swap), 4);
870 return os.write(reinterpret_cast<const char*>(&val), 4);
871 #endif //GDCM_WORDS_BIGENDIAN
875 * \brief binary_write binary_write
876 * @param os ostream to write to
879 std::ostream &binary_write(std::ostream &os, const char *val)
881 return os.write(val, strlen(val));
886 * @param os ostream to write to
889 std::ostream &binary_write(std::ostream &os, std::string const &val)
891 return os.write(val.c_str(), val.size());
895 * \brief binary_write binary_write
896 * @param os ostream to write to
898 * @param len length of the 'value' to be written
900 std::ostream &binary_write(std::ostream &os, const uint8_t *val, size_t len)
902 // We are writting sizeof(char) thus no need to swap bytes
903 return os.write(reinterpret_cast<const char*>(val), len);
907 * \brief binary_write binary_write
908 * @param os ostream to write to
910 * @param len length of the 'value' to be written
912 std::ostream &binary_write(std::ostream &os, const uint16_t *val, size_t len)
914 // This is tricky since we are writting two bytes buffer.
915 // Be carefull with little endian vs big endian.
916 // Also this other trick is to allocate a small (efficient) buffer that store
917 // intermediate result before writting it.
918 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
919 const int BUFFER_SIZE = 4096;
920 static char buffer[BUFFER_SIZE];
921 uint16_t *binArea16 = (uint16_t*)val; //for the const
923 // how many BUFFER_SIZE long pieces in binArea ?
924 int nbPieces = len/BUFFER_SIZE; //(16 bits = 2 Bytes)
925 int remainingSize = len%BUFFER_SIZE;
927 for (int j=0;j<nbPieces;j++)
929 uint16_t *pbuffer = (uint16_t*)buffer; //reinitialize pbuffer
930 for (int i = 0; i < BUFFER_SIZE/2; i++)
932 *pbuffer = *binArea16 >> 8 | *binArea16 << 8;
936 os.write ( buffer, BUFFER_SIZE );
938 if ( remainingSize > 0)
940 uint16_t *pbuffer = (uint16_t*)buffer; //reinitialize pbuffer
941 for (int i = 0; i < remainingSize/2; i++)
943 *pbuffer = *binArea16 >> 8 | *binArea16 << 8;
947 os.write ( buffer, remainingSize );
951 return os.write(reinterpret_cast<const char*>(val), len);
955 //-------------------------------------------------------------------------
958 //-------------------------------------------------------------------------
961 * \brief Return the IP adress of the machine writting the DICOM image
963 std::string Util::GetIPAddress()
965 // This is a rip from
966 // http://www.codeguru.com/Cpp/I-N/internet/network/article.php/c3445/
967 #ifndef HOST_NAME_MAX
968 // SUSv2 guarantees that `Host names are limited to 255 bytes'.
969 // POSIX 1003.1-2001 guarantees that `Host names (not including the
970 // terminating NUL) are limited to HOST_NAME_MAX bytes'.
971 #define HOST_NAME_MAX 255
972 // In this case we should maybe check the string was not truncated.
973 // But I don't known how to check that...
974 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
975 // with WinSock DLL we need to initialize the WinSock before using gethostname
976 WORD wVersionRequested = MAKEWORD(1,0);
978 int err = WSAStartup(wVersionRequested,&WSAData);
981 // Tell the user that we could not find a usable
988 #endif //HOST_NAME_MAX
991 char szHostName[HOST_NAME_MAX+1];
992 int r = gethostname(szHostName, HOST_NAME_MAX);
997 struct hostent *pHost = gethostbyname(szHostName);
999 for( int i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
1001 for( int j = 0; j<pHost->h_length; j++ )
1003 if ( j > 0 ) str += ".";
1005 str += Util::Format("%u",
1006 (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);
1008 // str now contains one local IP address
1010 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
1016 // If an error occur r == -1
1017 // Most of the time it will return 127.0.0.1...
1021 //-------------------------------------------------------------------------
1022 } // end namespace gdcm