1 /*=========================================================================
4 Module: $RCSfile: gdcmUtil.cxx,v $
6 Date: $Date: 2005/06/07 13:48:35 $
7 Version: $Revision: 1.153 $
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...
43 #include <unistd.h> // for gethostname
44 #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;
97 std::string Util::GDCM_MAC_ADRESS = GetMACAddress();
99 //-------------------------------------------------------------------------
102 * \brief Provide a better 'c++' approach for sprintf
103 * For example c code is:
104 * char result[200]; // hope 200 is enough
105 * sprintf(result, "%04x|%04x", group , elem);
108 * std::ostringstream buf;
109 * buf << std::right << std::setw(4) << std::setfill('0') << std::hex
110 * << group << "|" << std::right << std::setw(4) << std::setfill('0')
111 * << std::hex << elem;
116 * result = gdcm::Util::Format("%04x|%04x", group , elem);
118 std::string Util::Format(const char *format, ...)
122 va_start(args, format);
123 vsprintf(buffer, format, args); //might be a security flaw
124 va_end(args); // Each invocation of va_start should be matched
125 // by a corresponding invocation of va_end
126 // args is then 'undefined'
132 * \brief Because not available in C++ (?)
133 * @param str string to check
134 * @param tokens std::vector to receive the tokenized substrings
135 * @param delimiters string containing the character delimitors
138 void Util::Tokenize (const std::string &str,
139 std::vector<std::string> &tokens,
140 const std::string &delimiters)
142 std::string::size_type lastPos = str.find_first_not_of(delimiters,0);
143 std::string::size_type pos = str.find_first_of (delimiters,lastPos);
144 while (std::string::npos != pos || std::string::npos != lastPos)
146 tokens.push_back(str.substr(lastPos, pos - lastPos));
147 lastPos = str.find_first_not_of(delimiters, pos);
148 pos = str.find_first_of (delimiters, lastPos);
153 * \brief Because not available in C++ (?)
154 * Counts the number of occurences of a substring within a string
155 * @param str string to check
156 * @param subStr substring to count
159 int Util::CountSubstring (const std::string &str,
160 const std::string &subStr)
162 int count = 0; // counts how many times it appears
163 std::string::size_type x = 0; // The index position in the string
167 x = str.find(subStr,x); // Find the substring
168 if (x != std::string::npos) // If present
170 count++; // increase the count
171 x += subStr.length(); // Skip this word
174 while (x != std::string::npos);// Carry on until not present
180 * \brief Weed out a string from the non-printable characters (in order
181 * to avoid corrupting the terminal of invocation when printing)
182 * @param s string to remove non printable characters from
184 std::string Util::CreateCleanString(std::string const &s)
188 for(unsigned int i=0; i<str.size(); i++)
190 if(!isprint((unsigned char)str[i]))
198 if(!isprint((unsigned char)s[str.size()-1]))
200 if(s[str.size()-1] == 0)
202 str[str.size()-1] = ' ';
211 * \brief Add a SEPARATOR to the end of the name is necessary
212 * @param pathname file/directory name to normalize
214 std::string Util::NormalizePath(std::string const &pathname)
216 const char SEPARATOR_X = '/';
217 const char SEPARATOR_WIN = '\\';
218 const std::string SEPARATOR = "/";
219 std::string name = pathname;
220 int size = name.size();
222 if( name[size-1] != SEPARATOR_X && name[size-1] != SEPARATOR_WIN )
230 * \brief Get the (directory) path from a full path file name
231 * @param fullName file/directory name to extract Path from
233 std::string Util::GetPath(std::string const &fullName)
235 std::string res = fullName;
236 int pos1 = res.rfind("/");
237 int pos2 = res.rfind("\\");
251 * \brief Get the (last) name of a full path file name
252 * @param fullName file/directory name to extract end name from
254 std::string Util::GetName(std::string const &fullName)
256 std::string filename = fullName;
258 std::string::size_type slash_pos = filename.rfind("/");
259 std::string::size_type backslash_pos = filename.rfind("\\");
260 slash_pos = slash_pos > backslash_pos ? slash_pos : backslash_pos;
261 if(slash_pos != std::string::npos)
263 return filename.substr(slash_pos + 1);
272 * \brief Get the current date of the system in a dicom string
274 std::string Util::GetCurrentDate()
279 strftime(tmp,512,"%Y%m%d", localtime(&tloc) );
284 * \brief Get the current time of the system in a dicom string
286 std::string Util::GetCurrentTime()
291 strftime(tmp,512,"%H%M%S", localtime(&tloc) );
296 * \brief Get both the date and time at the same time to avoid problem
297 * around midnight where two call could be before and after midnight
299 std::string Util::GetCurrentDateTime()
305 // We need implementation specific functions to obtain millisecond precision
306 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
310 milliseconds = tb.millitm;
313 gettimeofday (&tv, NULL);
315 // Compute milliseconds from microseconds.
316 milliseconds = tv.tv_usec / 1000;
318 // Obtain the time of day, and convert it to a tm struct.
319 struct tm *ptm = localtime (&timep);
320 // Format the date and time, down to a single second.
321 strftime (tmp, sizeof (tmp), "%Y%m%d%H%M%S", ptm);
325 r += Format("%03ld", milliseconds);
330 unsigned int Util::GetCurrentThreadID()
332 // FIXME the implementation is far from complete
333 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
334 return (unsigned int)GetCurrentThreadId();
338 // Doesn't work on fedora, but is in the man page...
339 //return (unsigned int)gettid();
342 return (unsigned int)thr_self();
344 //default implementation
351 unsigned int Util::GetCurrentProcessID()
353 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
354 // NOTE: There is also a _getpid()...
355 return (unsigned int)GetCurrentProcessId();
357 // get process identification, POSIX
358 return (unsigned int)getpid();
363 * \brief tells us if the processor we are working with is BigEndian or not
365 bool Util::IsCurrentProcessorBigEndian()
367 #if defined(GDCM_WORDS_BIGENDIAN)
375 * \brief Create a /DICOM/ string:
376 * It should a of even length (no odd length ever)
377 * It can contain as many (if you are reading this from your
378 * editor the following character is is backslash followed by zero
379 * that needed to be escaped with an extra backslash for doxygen) \\0
382 std::string Util::DicomString(const char *s, size_t l)
384 std::string r(s, s+l);
385 gdcmAssertMacro( !(r.size() % 2) ); // == basically 'l' is even
390 * \brief Create a /DICOM/ string:
391 * It should a of even length (no odd length ever)
392 * It can contain as many (if you are reading this from your
393 * editor the following character is backslash followed by zero
394 * that needed to be escaped with an extra backslash for doxygen) \\0
396 * This function is similar to DicomString(const char*),
397 * except it doesn't take a length.
398 * It only pad with a null character if length is odd
400 std::string Util::DicomString(const char *s)
402 size_t l = strlen(s);
407 std::string r(s, s+l);
408 gdcmAssertMacro( !(r.size() % 2) );
413 * \brief Safely compare two Dicom String:
414 * - Both string should be of even length
415 * - We allow padding of even length string by either a null
416 * character of a space
418 bool Util::DicomStringEqual(const std::string &s1, const char *s2)
420 // s2 is the string from the DICOM reference: 'MONOCHROME1'
421 std::string s1_even = s1; //Never change input parameter
422 std::string s2_even = DicomString( s2 );
423 if( s1_even[s1_even.size()-1] == ' ')
425 s1_even[s1_even.size()-1] = '\0'; //replace space character by null
427 return s1_even == s2_even;
431 typedef BOOL(WINAPI * pSnmpExtensionInit) (
432 IN DWORD dwTimeZeroReference,
433 OUT HANDLE * hPollForTrapEvent,
434 OUT AsnObjectIdentifier * supportedView);
436 typedef BOOL(WINAPI * pSnmpExtensionTrap) (
437 OUT AsnObjectIdentifier * enterprise,
438 OUT AsnInteger * genericTrap,
439 OUT AsnInteger * specificTrap,
440 OUT AsnTimeticks * timeStamp,
441 OUT RFC1157VarBindList * variableBindings);
443 typedef BOOL(WINAPI * pSnmpExtensionQuery) (
445 IN OUT RFC1157VarBindList * variableBindings,
446 OUT AsnInteger * errorStatus,
447 OUT AsnInteger * errorIndex);
449 typedef BOOL(WINAPI * pSnmpExtensionInitEx) (
450 OUT AsnObjectIdentifier * supportedView);
453 /// \brief gets current M.A.C adress (for internal use only)
454 int GetMacAddrSys ( unsigned char *addr );
455 int GetMacAddrSys ( unsigned char *addr )
459 if ( (WSAStartup(MAKEWORD(2, 0), &WinsockData)) != 0)
461 std::cerr << "This program requires Winsock 2.x!" << std::endl;
465 HANDLE PollForTrapEvent;
466 AsnObjectIdentifier SupportedView;
467 UINT OID_ifEntryType[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 3 };
468 UINT OID_ifEntryNum[] = { 1, 3, 6, 1, 2, 1, 2, 1 };
469 UINT OID_ipMACEntAddr[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 6 };
470 AsnObjectIdentifier MIB_ifMACEntAddr = {
471 sizeof(OID_ipMACEntAddr) / sizeof(UINT), OID_ipMACEntAddr };
472 AsnObjectIdentifier MIB_ifEntryType = {
473 sizeof(OID_ifEntryType) / sizeof(UINT), OID_ifEntryType };
474 AsnObjectIdentifier MIB_ifEntryNum = {
475 sizeof(OID_ifEntryNum) / sizeof(UINT), OID_ifEntryNum };
476 RFC1157VarBindList varBindList;
477 RFC1157VarBind varBind[2];
478 AsnInteger errorStatus;
479 AsnInteger errorIndex;
480 AsnObjectIdentifier MIB_NULL = { 0, 0 };
485 // Load the SNMP dll and get the addresses of the functions necessary
486 HINSTANCE m_hInst = LoadLibrary("inetmib1.dll");
487 if (m_hInst < (HINSTANCE) HINSTANCE_ERROR)
491 pSnmpExtensionInit m_Init =
492 (pSnmpExtensionInit) GetProcAddress(m_hInst, "SnmpExtensionInit");
493 pSnmpExtensionQuery m_Query =
494 (pSnmpExtensionQuery) GetProcAddress(m_hInst, "SnmpExtensionQuery");
495 m_Init(GetTickCount(), &PollForTrapEvent, &SupportedView);
497 /* Initialize the variable list to be retrieved by m_Query */
498 varBindList.list = varBind;
499 varBind[0].name = MIB_NULL;
500 varBind[1].name = MIB_NULL;
502 // Copy in the OID to find the number of entries in the
504 varBindList.len = 1; // Only retrieving one item
505 SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryNum);
506 m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
508 // printf("# of adapters in this system : %i\n",
509 // varBind[0].value.asnValue.number);
512 // Copy in the OID of ifType, the type of interface
513 SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryType);
515 // Copy in the OID of ifPhysAddress, the address
516 SNMP_oidcpy(&varBind[1].name, &MIB_ifMACEntAddr);
520 // Submit the query. Responses will be loaded into varBindList.
521 // We can expect this call to succeed a # of times corresponding
522 // to the # of adapters reported to be in the system
523 ret = m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
531 // Confirm that the proper type has been returned
532 ret = SNMP_oidncmp(&varBind[0].name, &MIB_ifEntryType,
533 MIB_ifEntryType.idLength);
538 dtmp = varBind[0].value.asnValue.number;
540 // Type 6 describes ethernet interfaces
543 // Confirm that we have an address here
544 ret = SNMP_oidncmp(&varBind[1].name, &MIB_ifMACEntAddr,
545 MIB_ifMACEntAddr.idLength);
546 if ( !ret && varBind[1].value.asnValue.address.stream != NULL )
548 if ( (varBind[1].value.asnValue.address.stream[0] == 0x44)
549 && (varBind[1].value.asnValue.address.stream[1] == 0x45)
550 && (varBind[1].value.asnValue.address.stream[2] == 0x53)
551 && (varBind[1].value.asnValue.address.stream[3] == 0x54)
552 && (varBind[1].value.asnValue.address.stream[4] == 0x00) )
554 // Ignore all dial-up networking adapters
555 std::cerr << "Interface #" << j << " is a DUN adapter\n";
558 if ( (varBind[1].value.asnValue.address.stream[0] == 0x00)
559 && (varBind[1].value.asnValue.address.stream[1] == 0x00)
560 && (varBind[1].value.asnValue.address.stream[2] == 0x00)
561 && (varBind[1].value.asnValue.address.stream[3] == 0x00)
562 && (varBind[1].value.asnValue.address.stream[4] == 0x00)
563 && (varBind[1].value.asnValue.address.stream[5] == 0x00) )
565 // Ignore NULL addresses returned by other network
567 std::cerr << "Interface #" << j << " is a NULL address\n";
570 memcpy( addr, varBind[1].value.asnValue.address.stream, 6);
577 SNMP_FreeVarBind(&varBind[0]);
578 SNMP_FreeVarBind(&varBind[1]);
580 #endif //Win32 version
583 // implementation for POSIX system
584 #if defined(CMAKE_HAVE_NET_IF_ARP_H) && defined(__sun)
585 //The POSIX version is broken anyway on Solaris, plus would require full
587 struct arpreq parpreq;
588 struct sockaddr_in *psa;
589 struct hostent *phost;
590 char hostname[MAXHOSTNAMELEN];
594 if(gethostname(hostname, MAXHOSTNAMELEN) != 0)
596 perror("gethostname");
599 phost = gethostbyname(hostname);
600 paddrs = phost->h_addr_list;
602 sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
608 memset(&parpreq, 0, sizeof(struct arpreq));
609 psa = (struct sockaddr_in *) &parpreq.arp_pa;
611 memset(psa, 0, sizeof(struct sockaddr_in));
612 psa->sin_family = AF_INET;
613 memcpy(&psa->sin_addr, *paddrs, sizeof(struct in_addr));
615 status = ioctl(sock, SIOCGARP, &parpreq);
621 memcpy(addr, parpreq.arp_ha.sa_data, 6);
625 #ifdef CMAKE_HAVE_NET_IF_H
627 struct ifreq ifr, *ifrp;
632 #if defined(AF_LINK) && (!defined(SIOCGIFHWADDR) && !defined(SIOCGENADDR))
633 struct sockaddr_dl *sdlp;
637 // BSD 4.4 defines the size of an ifreq to be
638 // max(sizeof(ifreq), sizeof(ifreq.ifr_name)+ifreq.ifr_addr.sa_len
639 // However, under earlier systems, sa_len isn't present, so the size is
640 // just sizeof(struct ifreq)
641 // We should investiage the use of SIZEOF_ADDR_IFREQ
645 #define max(a,b) ((a) > (b) ? (a) : (b))
647 #define ifreq_size(i) max(sizeof(struct ifreq),\
648 sizeof((i).ifr_name)+(i).ifr_addr.sa_len)
650 #define ifreq_size(i) sizeof(struct ifreq)
651 #endif // HAVE_SA_LEN
653 if( (sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) < 0 )
657 memset(buf, 0, sizeof(buf));
658 ifc.ifc_len = sizeof(buf);
660 if (ioctl (sd, SIOCGIFCONF, (char *)&ifc) < 0)
666 for (i = 0; i < n; i+= ifreq_size(*ifrp) )
668 ifrp = (struct ifreq *)((char *) ifc.ifc_buf+i);
669 strncpy(ifr.ifr_name, ifrp->ifr_name, IFNAMSIZ);
671 if (ioctl(sd, SIOCGIFHWADDR, &ifr) < 0)
673 a = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
676 // In theory this call should also work on Sun Solaris, but apparently
677 // SIOCGENADDR is not implemented properly thus the call
678 // ioctl(sd, SIOCGENADDR, &ifr) always returns errno=2
679 // (No such file or directory)
680 // Furthermore the DLAPI seems to require full root access
681 if (ioctl(sd, SIOCGENADDR, &ifr) < 0)
683 a = (unsigned char *) ifr.ifr_enaddr;
686 sdlp = (struct sockaddr_dl *) &ifrp->ifr_addr;
687 if ((sdlp->sdl_family != AF_LINK) || (sdlp->sdl_alen != 6))
689 a = (unsigned char *) &sdlp->sdl_data[sdlp->sdl_nlen];
691 perror("No way to access hardware");
695 #endif // SIOCGENADDR
696 #endif // SIOCGIFHWADDR
697 if (!a[0] && !a[1] && !a[2] && !a[3] && !a[4] && !a[5]) continue;
708 // Not implemented platforms
709 perror("There was a configuration problem on your plateform");
716 * \brief Mini function to return the last digit from a number express in base 256
717 * pre condition data contain an array of 6 unsigned char
718 * post condition carry contain the last digit
720 inline int getlastdigit(unsigned char *data)
722 int extended, carry = 0;
725 extended = (carry << 8) + data[i];
726 data[i] = extended / 10;
727 carry = extended % 10;
733 * \brief Encode the mac address on a fixed lenght string of 15 characters.
734 * we save space this way.
736 std::string Util::GetMACAddress()
738 // This code is the result of a long internet search to find something
739 // as compact as possible (not OS independant). We only have to separate
740 // 3 OS: Win32, SunOS and 'real' POSIX
741 // http://groups-beta.google.com/group/comp.unix.solaris/msg/ad36929d783d63be
742 // http://bdn.borland.com/article/0,1410,26040,00.html
743 unsigned char addr[6];
745 int stat = GetMacAddrSys(addr);
748 // We need to convert a 6 digit number from base 256 to base 10, using integer
749 // would requires a 48bits one. To avoid this we have to reimplement the div + modulo
756 res = getlastdigit(addr);
757 sres.insert(sres.begin(), '0' + res);
758 zero = (addr[0] == 0) && (addr[1] == 0) && (addr[2] == 0)
759 && (addr[3] == 0) && (addr[4] == 0) && (addr[5] == 0);
766 gdcmWarningMacro("Problem in finding the MAC Address");
772 * \brief Creates a new UID. As stipulate in the DICOM ref
773 * each time a DICOM image is create it should have
774 * a unique identifier (URI)
775 * @param root is the DICOM prefix assigned by IOS group
777 std::string Util::CreateUniqueUID(const std::string &root)
783 // gdcm UID prefix, as supplied by http://www.medicalconnections.co.uk
791 // A root was specified use it to forge our new UID:
793 //append += Util::GetMACAddress(); // to save CPU time
794 append += Util::GDCM_MAC_ADRESS;
796 append += Util::GetCurrentDateTime();
798 //Also add a mini random number just in case:
799 int r = (int) (100.0*rand()/RAND_MAX);
800 append += Format("%02d", r);
802 // If append is too long we need to rehash it
803 if( (prefix + append).size() > 64 )
805 gdcmErrorMacro( "Size of UID is too long." );
806 // we need a hash function to truncate this number
807 // if only md5 was cross plateform
811 return prefix + append;
814 void Util::SetRootUID(const std::string &root)
822 const std::string &Util::GetRootUID()
827 //-------------------------------------------------------------------------
829 * \brief binary_write binary_write
830 * @param os ostream to write to
833 std::ostream &binary_write(std::ostream &os, const uint16_t &val)
835 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
837 //swap = ((( val << 8 ) & 0xff00 ) | (( val >> 8 ) & 0x00ff ) );
839 swap = ( val << 8 | val >> 8 );
841 return os.write(reinterpret_cast<const char*>(&swap), 2);
843 return os.write(reinterpret_cast<const char*>(&val), 2);
844 #endif //GDCM_WORDS_BIGENDIAN
848 * \brief binary_write binary_write
849 * @param os ostream to write to
852 std::ostream &binary_write(std::ostream &os, const uint32_t &val)
854 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
856 // swap = ( ((val<<24) & 0xff000000) | ((val<<8) & 0x00ff0000) |
857 // ((val>>8) & 0x0000ff00) | ((val>>24) & 0x000000ff) );
859 swap = ( (val<<24) | ((val<<8) & 0x00ff0000) |
860 ((val>>8) & 0x0000ff00) | (val>>24) );
861 return os.write(reinterpret_cast<const char*>(&swap), 4);
863 return os.write(reinterpret_cast<const char*>(&val), 4);
864 #endif //GDCM_WORDS_BIGENDIAN
868 * \brief binary_write binary_write
869 * @param os ostream to write to
872 std::ostream &binary_write(std::ostream &os, const char *val)
874 return os.write(val, strlen(val));
879 * @param os ostream to write to
882 std::ostream &binary_write(std::ostream &os, std::string const &val)
884 return os.write(val.c_str(), val.size());
888 * \brief binary_write binary_write
889 * @param os ostream to write to
891 * @param len length of the 'value' to be written
893 std::ostream &binary_write(std::ostream &os, const uint8_t *val, size_t len)
895 // We are writting sizeof(char) thus no need to swap bytes
896 return os.write(reinterpret_cast<const char*>(val), len);
900 * \brief binary_write binary_write
901 * @param os ostream to write to
903 * @param len length of the 'value' to be written
905 std::ostream &binary_write(std::ostream &os, const uint16_t *val, size_t len)
907 // This is tricky since we are writting two bytes buffer.
908 // Be carefull with little endian vs big endian.
909 // Also this other trick is to allocate a small (efficient) buffer that store
910 // intermediate result before writting it.
911 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
912 const int BUFFER_SIZE = 4096;
913 static char buffer[BUFFER_SIZE];
914 uint16_t *binArea16 = (uint16_t*)val; //for the const
916 // how many BUFFER_SIZE long pieces in binArea ?
917 int nbPieces = len/BUFFER_SIZE; //(16 bits = 2 Bytes)
918 int remainingSize = len%BUFFER_SIZE;
920 for (int j=0;j<nbPieces;j++)
922 uint16_t *pbuffer = (uint16_t*)buffer; //reinitialize pbuffer
923 for (int i = 0; i < BUFFER_SIZE/2; i++)
925 *pbuffer = *binArea16 >> 8 | *binArea16 << 8;
929 os.write ( buffer, BUFFER_SIZE );
931 if ( remainingSize > 0)
933 uint16_t *pbuffer = (uint16_t*)buffer; //reinitialize pbuffer
934 for (int i = 0; i < remainingSize/2; i++)
936 *pbuffer = *binArea16 >> 8 | *binArea16 << 8;
940 os.write ( buffer, remainingSize );
944 return os.write(reinterpret_cast<const char*>(val), len);
948 //-------------------------------------------------------------------------
951 //-------------------------------------------------------------------------
954 * \brief Return the IP adress of the machine writting the DICOM image
956 std::string Util::GetIPAddress()
958 // This is a rip from
959 // http://www.codeguru.com/Cpp/I-N/internet/network/article.php/c3445/
960 #ifndef HOST_NAME_MAX
961 // SUSv2 guarantees that `Host names are limited to 255 bytes'.
962 // POSIX 1003.1-2001 guarantees that `Host names (not including the
963 // terminating NUL) are limited to HOST_NAME_MAX bytes'.
964 #define HOST_NAME_MAX 255
965 // In this case we should maybe check the string was not truncated.
966 // But I don't known how to check that...
967 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
968 // with WinSock DLL we need to initialize the WinSock before using gethostname
969 WORD wVersionRequested = MAKEWORD(1,0);
971 int err = WSAStartup(wVersionRequested,&WSAData);
974 // Tell the user that we could not find a usable
981 #endif //HOST_NAME_MAX
984 char szHostName[HOST_NAME_MAX+1];
985 int r = gethostname(szHostName, HOST_NAME_MAX);
990 struct hostent *pHost = gethostbyname(szHostName);
992 for( int i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
994 for( int j = 0; j<pHost->h_length; j++ )
996 if( j > 0 ) str += ".";
998 str += Util::Format("%u",
999 (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);
1001 // str now contains one local IP address
1003 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
1009 // If an error occur r == -1
1010 // Most of the time it will return 127.0.0.1...
1014 //-------------------------------------------------------------------------
1015 } // end namespace gdcm