1 /*=========================================================================
4 Module: $RCSfile: gdcmUtil.cxx,v $
6 Date: $Date: 2005/02/28 18:56:29 $
7 Version: $Revision: 1.147 $
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(__MINGW32__)
38 #include <winsock.h> // for gethostname and gethostbyname
42 #include <unistd.h> // for gethostname
43 #include <netdb.h> // for gethostbyname
55 #include <sys/types.h>
58 #ifdef CMAKE_HAVE_SYS_IOCTL_H
59 #include <sys/ioctl.h> // For SIOCGIFCONF on Linux
61 #ifdef CMAKE_HAVE_SYS_SOCKET_H
62 #include <sys/socket.h>
64 #ifdef CMAKE_HAVE_SYS_SOCKIO_H
65 #include <sys/sockio.h> // For SIOCGIFCONF on SunOS
67 #ifdef CMAKE_HAVE_NET_IF_H
70 #ifdef CMAKE_HAVE_NETINET_IN_H
71 #include <netinet/in.h> //For IPPROTO_IP
73 #ifdef CMAKE_HAVE_NET_IF_DL_H
74 #include <net/if_dl.h>
76 #if defined(CMAKE_HAVE_NET_IF_ARP_H) && defined(__sun)
77 // This is absolutely necessary on SunOS
78 #include <net/if_arp.h>
81 // For GetCurrentThreadID()
83 #include <sys/types.h>
84 #include <linux/unistd.h>
92 //-------------------------------------------------------------------------
93 const std::string Util::GDCM_UID = "1.2.826.0.1.3680043.2.1143";
94 std::string Util::RootUID = GDCM_UID;
95 const uint16_t Util::FMIV = 0x0001;
96 uint8_t *Util::FileMetaInformationVersion = (uint8_t *)&FMIV;
98 //-------------------------------------------------------------------------
101 * \brief Provide a better 'c++' approach for sprintf
102 * For example c code is:
103 * char result[200]; // hope 200 is enough
104 * sprintf(result, "%04x|%04x", group , elem);
107 * std::ostringstream buf;
108 * buf << std::right << std::setw(4) << std::setfill('0') << std::hex
109 * << group << "|" << std::right << std::setw(4) << std::setfill('0')
110 * << std::hex << elem;
115 * result = gdcm::Util::Format("%04x|%04x", group , elem);
117 std::string Util::Format(const char *format, ...)
121 va_start(args, format);
122 vsprintf(buffer, format, args); //might be a security flaw
123 va_end(args); // Each invocation of va_start should be matched
124 // by a corresponding invocation of va_end
125 // args is then 'undefined'
131 * \brief Because not available in C++ (?)
132 * @param str string to check
133 * @param tokens std::vector to receive the tokenized substrings
134 * @param delimiters string containing the character delimitors
137 void Util::Tokenize (const std::string &str,
138 std::vector<std::string> &tokens,
139 const std::string &delimiters)
141 std::string::size_type lastPos = str.find_first_not_of(delimiters,0);
142 std::string::size_type pos = str.find_first_of (delimiters,lastPos);
143 while (std::string::npos != pos || std::string::npos != lastPos)
145 tokens.push_back(str.substr(lastPos, pos - lastPos));
146 lastPos = str.find_first_not_of(delimiters, pos);
147 pos = str.find_first_of (delimiters, lastPos);
152 * \brief Because not available in C++ (?)
153 * Counts the number of occurences of a substring within a string
154 * @param str string to check
155 * @param subStr substring to count
158 int Util::CountSubstring (const std::string &str,
159 const std::string &subStr)
161 int count = 0; // counts how many times it appears
162 std::string::size_type x = 0; // The index position in the string
166 x = str.find(subStr,x); // Find the substring
167 if (x != std::string::npos) // If present
169 count++; // increase the count
170 x += subStr.length(); // Skip this word
173 while (x != std::string::npos);// Carry on until not present
179 * \brief Weed out a string from the non-printable characters (in order
180 * to avoid corrupting the terminal of invocation when printing)
181 * @param s string to remove non printable characters from
183 std::string Util::CreateCleanString(std::string const &s)
187 for(unsigned int i=0; i<str.size(); i++)
189 if(!isprint((unsigned char)str[i]))
197 if(!isprint((unsigned char)s[str.size()-1]))
199 if(s[str.size()-1] == 0)
201 str[str.size()-1] = ' ';
210 * \brief Add a SEPARATOR to the end of the name is necessary
211 * @param pathname file/directory name to normalize
213 std::string Util::NormalizePath(std::string const &pathname)
215 const char SEPARATOR_X = '/';
216 const char SEPARATOR_WIN = '\\';
217 const std::string SEPARATOR = "/";
218 std::string name = pathname;
219 int size = name.size();
221 if( name[size-1] != SEPARATOR_X && name[size-1] != SEPARATOR_WIN )
229 * \brief Get the (directory) path from a full path file name
230 * @param fullName file/directory name to extract Path from
232 std::string Util::GetPath(std::string const &fullName)
234 std::string res = fullName;
235 int pos1 = res.rfind("/");
236 int pos2 = res.rfind("\\");
250 * \brief Get the (last) name of a full path file name
251 * @param fullName file/directory name to extract end name from
253 std::string Util::GetName(std::string const &fullName)
255 std::string filename = fullName;
257 std::string::size_type slash_pos = filename.rfind("/");
258 std::string::size_type backslash_pos = filename.rfind("\\");
259 slash_pos = slash_pos > backslash_pos ? slash_pos : backslash_pos;
260 if(slash_pos != std::string::npos)
262 return filename.substr(slash_pos + 1);
271 * \brief Get the current date of the system in a dicom string
273 std::string Util::GetCurrentDate()
278 strftime(tmp,512,"%Y%m%d", localtime(&tloc) );
283 * \brief Get the current time of the system in a dicom string
285 std::string Util::GetCurrentTime()
290 strftime(tmp,512,"%H%M%S", localtime(&tloc) );
295 * \brief Get both the date and time at the same time to avoid problem
296 * around midnight where two call could be before and after midnight
298 std::string Util::GetCurrentDateTime()
304 // We need implementation specific functions to obtain millisecond precision
305 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
309 milliseconds = tb.millitm;
312 gettimeofday (&tv, NULL);
314 // Compute milliseconds from microseconds.
315 milliseconds = tv.tv_usec / 1000;
317 // Obtain the time of day, and convert it to a tm struct.
318 struct tm *ptm = localtime (&timep);
319 // Format the date and time, down to a single second.
320 strftime (tmp, sizeof (tmp), "%Y%m%d%H%M%S", ptm);
324 r += Format("%03ld", milliseconds);
329 unsigned int Util::GetCurrentThreadID()
331 // FIXME the implementation is far from complete
332 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
333 return (unsigned int)GetCurrentThreadId();
337 // Doesn't work on fedora, but is in the man page...
338 //return (unsigned int)gettid();
341 return (unsigned int)thr_self();
343 //default implementation
348 unsigned int Util::GetCurrentProcessID()
350 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
351 // NOTE: There is also a _getpid()...
352 return (unsigned int)GetCurrentProcessId();
354 // get process identification, POSIX
355 return (unsigned int)getpid();
360 * \brief tells us if the processor we are working with is BigEndian or not
362 bool Util::IsCurrentProcessorBigEndian()
364 #if defined(GDCM_WORDS_BIGENDIAN)
372 * \brief Create a /DICOM/ string:
373 * It should a of even length (no odd length ever)
374 * It can contain as many (if you are reading this from your
375 * editor the following character is is backslash followed by zero
376 * that needed to be escaped with an extra backslash for doxygen) \\0
379 std::string Util::DicomString(const char *s, size_t l)
381 std::string r(s, s+l);
382 gdcmAssertMacro( !(r.size() % 2) ); // == basically 'l' is even
387 * \brief Create a /DICOM/ string:
388 * It should a of even length (no odd length ever)
389 * It can contain as many (if you are reading this from your
390 * editor the following character is is backslash followed by zero
391 * that needed to be escaped with an extra backslash for doxygen) \\0
393 * This function is similar to DicomString(const char*),
394 * except it doesn't take a length.
395 * It only pad with a null character if length is odd
397 std::string Util::DicomString(const char *s)
399 size_t l = strlen(s);
404 std::string r(s, s+l);
405 gdcmAssertMacro( !(r.size() % 2) );
410 * \brief Safely compare two Dicom String:
411 * - Both string should be of even length
412 * - We allow padding of even length string by either a null
413 * character of a space
415 bool Util::DicomStringEqual(const std::string &s1, const char *s2)
417 // s2 is the string from the DICOM reference: 'MONOCHROME1'
418 std::string s1_even = s1; //Never change input parameter
419 std::string s2_even = DicomString( s2 );
420 if( s1_even[s1_even.size()-1] == ' ')
422 s1_even[s1_even.size()-1] = '\0'; //replace space character by null
424 return s1_even == s2_even;
428 typedef BOOL(WINAPI * pSnmpExtensionInit) (
429 IN DWORD dwTimeZeroReference,
430 OUT HANDLE * hPollForTrapEvent,
431 OUT AsnObjectIdentifier * supportedView);
433 typedef BOOL(WINAPI * pSnmpExtensionTrap) (
434 OUT AsnObjectIdentifier * enterprise,
435 OUT AsnInteger * genericTrap,
436 OUT AsnInteger * specificTrap,
437 OUT AsnTimeticks * timeStamp,
438 OUT RFC1157VarBindList * variableBindings);
440 typedef BOOL(WINAPI * pSnmpExtensionQuery) (
442 IN OUT RFC1157VarBindList * variableBindings,
443 OUT AsnInteger * errorStatus,
444 OUT AsnInteger * errorIndex);
446 typedef BOOL(WINAPI * pSnmpExtensionInitEx) (
447 OUT AsnObjectIdentifier * supportedView);
450 /// \brief gets current M.A.C adress (for internal use only)
451 int GetMacAddrSys ( unsigned char *addr )
455 if (WSAStartup(MAKEWORD(2, 0), &WinsockData) != 0)
457 std::cerr << "This program requires Winsock 2.x!" << std::endl;
461 HANDLE PollForTrapEvent;
462 AsnObjectIdentifier SupportedView;
463 UINT OID_ifEntryType[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 3 };
464 UINT OID_ifEntryNum[] = { 1, 3, 6, 1, 2, 1, 2, 1 };
465 UINT OID_ipMACEntAddr[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 6 };
466 AsnObjectIdentifier MIB_ifMACEntAddr = {
467 sizeof(OID_ipMACEntAddr) / sizeof(UINT), OID_ipMACEntAddr };
468 AsnObjectIdentifier MIB_ifEntryType = {
469 sizeof(OID_ifEntryType) / sizeof(UINT), OID_ifEntryType };
470 AsnObjectIdentifier MIB_ifEntryNum = {
471 sizeof(OID_ifEntryNum) / sizeof(UINT), OID_ifEntryNum };
472 RFC1157VarBindList varBindList;
473 RFC1157VarBind varBind[2];
474 AsnInteger errorStatus;
475 AsnInteger errorIndex;
476 AsnObjectIdentifier MIB_NULL = { 0, 0 };
481 // Load the SNMP dll and get the addresses of the functions necessary
482 HINSTANCE m_hInst = LoadLibrary("inetmib1.dll");
483 if (m_hInst < (HINSTANCE) HINSTANCE_ERROR)
487 pSnmpExtensionInit m_Init =
488 (pSnmpExtensionInit) GetProcAddress(m_hInst, "SnmpExtensionInit");
489 pSnmpExtensionQuery m_Query =
490 (pSnmpExtensionQuery) GetProcAddress(m_hInst, "SnmpExtensionQuery");
491 m_Init(GetTickCount(), &PollForTrapEvent, &SupportedView);
493 /* Initialize the variable list to be retrieved by m_Query */
494 varBindList.list = varBind;
495 varBind[0].name = MIB_NULL;
496 varBind[1].name = MIB_NULL;
498 // Copy in the OID to find the number of entries in the
500 varBindList.len = 1; // Only retrieving one item
501 SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryNum);
502 m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
504 // printf("# of adapters in this system : %i\n",
505 // varBind[0].value.asnValue.number);
508 // Copy in the OID of ifType, the type of interface
509 SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryType);
511 // Copy in the OID of ifPhysAddress, the address
512 SNMP_oidcpy(&varBind[1].name, &MIB_ifMACEntAddr);
516 // Submit the query. Responses will be loaded into varBindList.
517 // We can expect this call to succeed a # of times corresponding
518 // to the # of adapters reported to be in the system
519 ret = m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
527 // Confirm that the proper type has been returned
528 ret = SNMP_oidncmp(&varBind[0].name, &MIB_ifEntryType,
529 MIB_ifEntryType.idLength);
534 dtmp = varBind[0].value.asnValue.number;
536 // Type 6 describes ethernet interfaces
539 // Confirm that we have an address here
540 ret = SNMP_oidncmp(&varBind[1].name, &MIB_ifMACEntAddr,
541 MIB_ifMACEntAddr.idLength);
542 if ( !ret && varBind[1].value.asnValue.address.stream != NULL )
544 if ( (varBind[1].value.asnValue.address.stream[0] == 0x44)
545 && (varBind[1].value.asnValue.address.stream[1] == 0x45)
546 && (varBind[1].value.asnValue.address.stream[2] == 0x53)
547 && (varBind[1].value.asnValue.address.stream[3] == 0x54)
548 && (varBind[1].value.asnValue.address.stream[4] == 0x00) )
550 // Ignore all dial-up networking adapters
551 std::cerr << "Interface #" << j << " is a DUN adapter\n";
554 if ( (varBind[1].value.asnValue.address.stream[0] == 0x00)
555 && (varBind[1].value.asnValue.address.stream[1] == 0x00)
556 && (varBind[1].value.asnValue.address.stream[2] == 0x00)
557 && (varBind[1].value.asnValue.address.stream[3] == 0x00)
558 && (varBind[1].value.asnValue.address.stream[4] == 0x00)
559 && (varBind[1].value.asnValue.address.stream[5] == 0x00) )
561 // Ignore NULL addresses returned by other network
563 std::cerr << "Interface #" << j << " is a NULL address\n";
566 memcpy( addr, varBind[1].value.asnValue.address.stream, 6);
573 SNMP_FreeVarBind(&varBind[0]);
574 SNMP_FreeVarBind(&varBind[1]);
576 #endif //Win32 version
579 // implementation for POSIX system
580 #if defined(CMAKE_HAVE_NET_IF_ARP_H) && defined(__sun)
581 //The POSIX version is broken anyway on Solaris, plus would require full
583 struct arpreq parpreq;
584 struct sockaddr_in *psa;
585 struct hostent *phost;
586 char hostname[MAXHOSTNAMELEN];
590 if(gethostname(hostname, MAXHOSTNAMELEN) != 0)
592 perror("gethostname");
595 phost = gethostbyname(hostname);
596 paddrs = phost->h_addr_list;
598 sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
604 memset(&parpreq, 0, sizeof(struct arpreq));
605 psa = (struct sockaddr_in *) &parpreq.arp_pa;
607 memset(psa, 0, sizeof(struct sockaddr_in));
608 psa->sin_family = AF_INET;
609 memcpy(&psa->sin_addr, *paddrs, sizeof(struct in_addr));
611 status = ioctl(sock, SIOCGARP, &parpreq);
617 memcpy(addr, parpreq.arp_ha.sa_data, 6);
621 #ifdef CMAKE_HAVE_NET_IF_H
623 struct ifreq ifr, *ifrp;
628 #if defined(AF_LINK) && (!defined(SIOCGIFHWADDR) && !defined(SIOCGENADDR))
629 struct sockaddr_dl *sdlp;
633 // BSD 4.4 defines the size of an ifreq to be
634 // max(sizeof(ifreq), sizeof(ifreq.ifr_name)+ifreq.ifr_addr.sa_len
635 // However, under earlier systems, sa_len isn't present, so the size is
636 // just sizeof(struct ifreq)
637 // We should investiage the use of SIZEOF_ADDR_IFREQ
641 #define max(a,b) ((a) > (b) ? (a) : (b))
643 #define ifreq_size(i) max(sizeof(struct ifreq),\
644 sizeof((i).ifr_name)+(i).ifr_addr.sa_len)
646 #define ifreq_size(i) sizeof(struct ifreq)
647 #endif // HAVE_SA_LEN
649 if( (sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) < 0 )
653 memset(buf, 0, sizeof(buf));
654 ifc.ifc_len = sizeof(buf);
656 if (ioctl (sd, SIOCGIFCONF, (char *)&ifc) < 0)
662 for (i = 0; i < n; i+= ifreq_size(*ifrp) )
664 ifrp = (struct ifreq *)((char *) ifc.ifc_buf+i);
665 strncpy(ifr.ifr_name, ifrp->ifr_name, IFNAMSIZ);
667 if (ioctl(sd, SIOCGIFHWADDR, &ifr) < 0)
669 a = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
672 // In theory this call should also work on Sun Solaris, but apparently
673 // SIOCGENADDR is not implemented properly thus the call
674 // ioctl(sd, SIOCGENADDR, &ifr) always returns errno=2
675 // (No such file or directory)
676 // Furthermore the DLAPI seems to require full root access
677 if (ioctl(sd, SIOCGENADDR, &ifr) < 0)
679 a = (unsigned char *) ifr.ifr_enaddr;
682 sdlp = (struct sockaddr_dl *) &ifrp->ifr_addr;
683 if ((sdlp->sdl_family != AF_LINK) || (sdlp->sdl_alen != 6))
685 a = (unsigned char *) &sdlp->sdl_data[sdlp->sdl_nlen];
687 perror("No way to access hardware");
691 #endif // SIOCGENADDR
692 #endif // SIOCGIFHWADDR
693 if (!a[0] && !a[1] && !a[2] && !a[3] && !a[4] && !a[5]) continue;
704 // Not implemented platforms
705 perror("There was a configuration problem on your plateform");
712 * \brief Mini function to return the last digit from a number express in base 256
713 * pre condition data contain an array of 6 unsigned char
714 * post condition carry contain the last digit
716 inline int getlastdigit(unsigned char *data)
718 int extended, carry = 0;
721 extended = (carry << 8) + data[i];
722 data[i] = extended / 10;
723 carry = extended % 10;
729 * \brief Encode the mac address on a fixed lenght string of 15 characters.
730 * we save space this way.
732 std::string Util::GetMACAddress()
734 // This code is the result of a long internet search to find something
735 // as compact as possible (not OS independant). We only have to separate
736 // 3 OS: Win32, SunOS and 'real' POSIX
737 // http://groups-beta.google.com/group/comp.unix.solaris/msg/ad36929d783d63be
738 // http://bdn.borland.com/article/0,1410,26040,00.html
739 unsigned char addr[6];
741 int stat = GetMacAddrSys(addr);
744 // We need to convert a 6 digit number from base 256 to base 10, using integer
745 // would requires a 48bits one. To avoid this we have to reimplement the div + modulo
752 res = getlastdigit(addr);
753 sres.insert(sres.begin(), '0' + res);
754 zero = (addr[0] == 0) && (addr[1] == 0) && (addr[2] == 0)
755 && (addr[3] == 0) && (addr[4] == 0) && (addr[5] == 0);
762 gdcmWarningMacro("Problem in finding the MAC Address");
768 * \brief Creates a new UID. As stipulate in the DICOM ref
769 * each time a DICOM image is create it should have
770 * a unique identifier (URI)
771 * @param root is the DICOM prefix assigned by IOS group
773 std::string Util::CreateUniqueUID(const std::string &root)
779 // gdcm UID prefix, as supplied by http://www.medicalconnections.co.uk
787 // A root was specified use it to forge our new UID:
789 append += Util::GetMACAddress();
791 append += Util::GetCurrentDateTime();
793 //Also add a mini random number just in case:
794 int r = (int) (100.0*rand()/RAND_MAX);
795 append += Format("%02d", r);
797 // If append is too long we need to rehash it
798 if( (prefix + append).size() > 64 )
800 gdcmErrorMacro( "Size of UID is too long." );
801 // we need a hash function to truncate this number
802 // if only md5 was cross plateform
806 return prefix + append;
809 void Util::SetRootUID(const std::string &root)
817 const std::string &Util::GetRootUID()
822 //-------------------------------------------------------------------------
824 * \brief binary_write binary_write
825 * @param os ostream to write to
828 std::ostream &binary_write(std::ostream &os, const uint16_t &val)
830 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
832 //swap = ((( val << 8 ) & 0xff00 ) | (( val >> 8 ) & 0x00ff ) );
834 swap = ( val << 8 | val >> 8 );
836 return os.write(reinterpret_cast<const char*>(&swap), 2);
838 return os.write(reinterpret_cast<const char*>(&val), 2);
839 #endif //GDCM_WORDS_BIGENDIAN
843 * \brief binary_write binary_write
844 * @param os ostream to write to
847 std::ostream &binary_write(std::ostream &os, const uint32_t &val)
849 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
851 // swap = ( ((val<<24) & 0xff000000) | ((val<<8) & 0x00ff0000) |
852 // ((val>>8) & 0x0000ff00) | ((val>>24) & 0x000000ff) );
854 swap = ( (val<<24) | ((val<<8) & 0x00ff0000) |
855 ((val>>8) & 0x0000ff00) | (val>>24) );
856 return os.write(reinterpret_cast<const char*>(&swap), 4);
858 return os.write(reinterpret_cast<const char*>(&val), 4);
859 #endif //GDCM_WORDS_BIGENDIAN
863 * \brief binary_write binary_write
864 * @param os ostream to write to
867 std::ostream &binary_write(std::ostream &os, const char *val)
869 return os.write(val, strlen(val));
874 * @param os ostream to write to
877 std::ostream &binary_write(std::ostream &os, std::string const &val)
879 return os.write(val.c_str(), val.size());
883 * \brief binary_write binary_write
884 * @param os ostream to write to
886 * @param len length of the 'value' to be written
888 std::ostream &binary_write(std::ostream &os, const uint8_t *val, size_t len)
890 // We are writting sizeof(char) thus no need to swap bytes
891 return os.write(reinterpret_cast<const char*>(val), len);
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 uint16_t *val, size_t len)
902 // This is tricky since we are writting two bytes buffer.
903 // Be carefull with little endian vs big endian.
904 // Also this other trick is to allocate a small (efficient) buffer that store
905 // intermediate result before writting it.
906 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
907 const int BUFFER_SIZE = 4096;
908 static char buffer[BUFFER_SIZE];
909 uint16_t *binArea16 = (uint16_t*)val; //for the const
911 // how many BUFFER_SIZE long pieces in binArea ?
912 int nbPieces = len/BUFFER_SIZE; //(16 bits = 2 Bytes)
913 int remainingSize = len%BUFFER_SIZE;
915 for (int j=0;j<nbPieces;j++)
917 uint16_t *pbuffer = (uint16_t*)buffer; //reinitialize pbuffer
918 for (int i = 0; i < BUFFER_SIZE/2; i++)
920 *pbuffer = *binArea16 >> 8 | *binArea16 << 8;
924 os.write ( buffer, BUFFER_SIZE );
926 if ( remainingSize > 0)
928 uint16_t *pbuffer = (uint16_t*)buffer; //reinitialize pbuffer
929 for (int i = 0; i < remainingSize/2; i++)
931 *pbuffer = *binArea16 >> 8 | *binArea16 << 8;
935 os.write ( buffer, remainingSize );
939 return os.write(reinterpret_cast<const char*>(val), len);
943 //-------------------------------------------------------------------------
946 //-------------------------------------------------------------------------
949 * \brief Return the IP adress of the machine writting the DICOM image
951 std::string Util::GetIPAddress()
953 // This is a rip from
954 // http://www.codeguru.com/Cpp/I-N/internet/network/article.php/c3445/
955 #ifndef HOST_NAME_MAX
956 // SUSv2 guarantees that `Host names are limited to 255 bytes'.
957 // POSIX 1003.1-2001 guarantees that `Host names (not including the
958 // terminating NUL) are limited to HOST_NAME_MAX bytes'.
959 #define HOST_NAME_MAX 255
960 // In this case we should maybe check the string was not truncated.
961 // But I don't known how to check that...
962 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
963 // with WinSock DLL we need to initialize the WinSock before using gethostname
964 WORD wVersionRequested = MAKEWORD(1,0);
966 int err = WSAStartup(wVersionRequested,&WSAData);
969 // Tell the user that we could not find a usable
976 #endif //HOST_NAME_MAX
979 char szHostName[HOST_NAME_MAX+1];
980 int r = gethostname(szHostName, HOST_NAME_MAX);
985 struct hostent *pHost = gethostbyname(szHostName);
987 for( int i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
989 for( int j = 0; j<pHost->h_length; j++ )
991 if( j > 0 ) str += ".";
993 str += Util::Format("%u",
994 (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);
996 // str now contains one local IP address
998 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
1004 // If an error occur r == -1
1005 // Most of the time it will return 127.0.0.1...
1009 //-------------------------------------------------------------------------
1010 } // end namespace gdcm