diff --git a/src/ca/localHostName.cpp b/src/ca/localHostName.cpp index 64210c88c..5c2e3d6d8 100644 --- a/src/ca/localHostName.cpp +++ b/src/ca/localHostName.cpp @@ -25,19 +25,17 @@ epicsSingleton < localHostName > localHostNameAtLoadTime; -localHostName::localHostName () +localHostName::localHostName () : + attachedToSockLib ( osiSockAttach () != 0 ), length ( 0u ) { - int status = osiSockAttach (); - if ( status ) { - this->attachedToSockLib = true; - status = gethostname ( this->cache, sizeof ( this->cache ) - 1 ); - if ( status ) { - strncpy ( this->cache, "", sizeof ( this->cache ) ); - } + const char * pErrStr = ""; + int status = -1; + if ( this->attachedToSockLib ) { + status = gethostname ( + this->cache, sizeof ( this->cache ) ); } - else { - this->attachedToSockLib = false; - strncpy ( this->cache, "", sizeof ( this->cache ) ); + if ( status ) { + strncpy ( this->cache, pErrStr, sizeof ( this->cache ) ); } this->cache [ sizeof ( this->cache ) - 1u ] = '\0'; this->length = strlen ( this->cache ); @@ -49,3 +47,20 @@ localHostName::~localHostName () osiSockRelease (); } } + +unsigned localHostName::getName ( + char * pBuf, unsigned bufLength ) const +{ + if ( bufLength ) { + strncpy ( pBuf, this->cache, bufLength ); + if ( this->length < bufLength ) { + return this->length; + } + else { + unsigned reducedSize = bufLength - 1; + pBuf [ reducedSize ] = '\0'; + return reducedSize; + } + } + return 0u; +} diff --git a/src/ca/localHostName.h b/src/ca/localHostName.h index 7b24861e4..d608dbef9 100644 --- a/src/ca/localHostName.h +++ b/src/ca/localHostName.h @@ -40,8 +40,8 @@ public: localHostName (); ~localHostName (); const char * pointer () const; - void copy ( char *pBuf, unsigned bufLength ) const; - unsigned stringLength () const; + unsigned getName ( char * pBuf, unsigned bufLength ) const; + unsigned nameLength () const; private: bool attachedToSockLib; unsigned length; @@ -50,19 +50,11 @@ private: extern epicsSingleton < localHostName > localHostNameAtLoadTime; -inline unsigned localHostName::stringLength () const +inline unsigned localHostName::nameLength () const { return this->length; } -inline void localHostName::copy ( char *pBuf, unsigned bufLength ) const -{ - if ( bufLength ) { - strncpy ( pBuf, this->cache, bufLength ); - pBuf [ bufLength - 1 ] = '\0'; - } -} - inline const char * localHostName::pointer () const { return this->cache;