update dev300-m57
[ooovba.git] / sal / qa / osl / socket / sockethelper.cxx
blob0fd95d56790671a4b6c7bb4bcfb4604214b56b9d
1 /*************************************************************************
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * Copyright 2008 by Sun Microsystems, Inc.
7 * OpenOffice.org - a multi-platform office productivity suite
9 * $RCSfile: sockethelper.cxx,v $
10 * $Revision: 1.7 $
12 * This file is part of OpenOffice.org.
14 * OpenOffice.org is free software: you can redistribute it and/or modify
15 * it under the terms of the GNU Lesser General Public License version 3
16 * only, as published by the Free Software Foundation.
18 * OpenOffice.org is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU Lesser General Public License version 3 for more details
22 * (a copy is included in the LICENSE file that accompanied this code).
24 * You should have received a copy of the GNU Lesser General Public License
25 * version 3 along with OpenOffice.org. If not, see
26 * <http://www.openoffice.org/license.html>
27 * for a copy of the LGPLv3 License.
29 ************************************************************************/
32 // MARKER(update_precomp.py): autogen include statement, do not remove
33 #include "precompiled_sal.hxx"
34 #include "sockethelper.hxx"
35 #include <cppunit/simpleheader.hxx>
37 //------------------------------------------------------------------------
38 // Ip version definition
39 //------------------------------------------------------------------------
40 #define IP_VER 4 /// currently only IPv4 is considered.
42 //------------------------------------------------------------------------
43 // helper functions
44 //------------------------------------------------------------------------
46 /** compare two OUString.
48 sal_Bool compareUString( const ::rtl::OUString & ustr1, const ::rtl::OUString & ustr2 )
50 sal_Bool bOk = ustr1.equalsIgnoreAsciiCase( ustr2 );
52 return bOk;
55 /** compare a OUString and an ASCII string.
57 sal_Bool compareUString( const ::rtl::OUString & ustr, const sal_Char *astr )
59 ::rtl::OUString ustr2 = rtl::OUString::createFromAscii( astr );
60 sal_Bool bOk = ustr.equalsIgnoreAsciiCase( ustr2 );
62 return bOk;
65 /** compare two socket address.
67 sal_Bool compareSocketAddr( const ::osl::SocketAddr & addr1 , const ::osl::SocketAddr & addr2 )
69 return ( ( sal_True == compareUString( addr1.getHostname( 0 ), addr2.getHostname( 0 ) ) ) && ( addr2.getPort( ) == addr2.getPort( ) ) );
72 /*char * oustring2char( const ::rtl::OUString & str )
74 rtl::OString aString;
75 aString = ::rtl::OUStringToOString( str, RTL_TEXTENCODING_ASCII_US );
76 t_print("oustring2char %s\n", aString.getStr( ) );
77 sal_Char * sStr = aString.getStr( );
78 return (char *)sStr;
79 }*/
81 /** print a UNI_CODE String. And also print some comments of the string.
83 void printUString( const ::rtl::OUString & str, const char* msg)
85 t_print("#%s #printUString_u# ", msg );
86 rtl::OString aString;
87 aString = ::rtl::OUStringToOString( str, RTL_TEXTENCODING_ASCII_US );
88 //char * sStr = aString.getStr( );
89 t_print("%s\n", aString.getStr( ) );
92 /** get the local host name.
93 mindy: gethostbyname( "localhost" ), on Linux, it returns the hostname in /etc/hosts + domain name,
94 if no entry in /etc/hosts, it returns "localhost" + domain name
96 ::rtl::OUString getHost( void )
98 struct hostent *hptr;
100 hptr = gethostbyname( "localhost" );
101 OSL_ENSURE( hptr != NULL, "#In getHostname function, error on gethostbyname()" );
102 ::rtl::OUString aUString = ::rtl::OUString::createFromAscii( (const sal_Char *) hptr->h_name );
104 return aUString;
107 /** get the full host name of the current processor, such as "aegean.prc.sun.com" --mindyliu
109 ::rtl::OUString getThisHostname( void )
111 ::rtl::OUString aUString;
112 #ifdef WNT
113 struct hostent *hptr;
114 hptr = gethostbyname( "localhost" );
115 OSL_ENSURE( hptr != NULL, "#In getHostname function, error on gethostbyname()" );
116 rtl::OString sHostname(hptr->h_name);
117 aUString = ::rtl::OStringToOUString(sHostname, RTL_TEXTENCODING_ASCII_US);
118 #else
119 char hostname[255];
120 if (gethostname(hostname, 255) != 0) {
121 OSL_ENSURE( false, "#Error: gethostname failed." );
124 struct hostent *hptr;
125 //first search /ets/hosts, then search from dns
126 hptr = gethostbyname( hostname);
127 if ( hptr != NULL )
129 strcpy( hostname, hptr->h_name );
132 t_print("hostname is %s \n", hostname );
133 rtl::OString sHostname( hostname );
134 aUString = ::rtl::OStringToOUString( sHostname, RTL_TEXTENCODING_ASCII_US );
135 aUString.getLength();
136 #endif
137 return aUString;
140 /** get IP by name, search /etc/hosts first, then search from dns, fail return OUString("")
142 ::rtl::OUString getIPbyName( rtl::OString const& str_name )
144 ::rtl::OUString aUString;
145 struct hostent *hptr;
146 //first search /ets/hosts, then search from dns
147 hptr = gethostbyname( str_name.getStr());
148 if ( hptr != NULL )
150 struct in_addr ** addrptr;
151 addrptr = (struct in_addr **) hptr->h_addr_list ;
152 //if there are more than one IPs on the same machine, we select one
153 for (; *addrptr; addrptr++)
155 t_print("#Local IP Address: %s\n", inet_ntoa(**addrptr));
156 aUString = ::rtl::OUString::createFromAscii( (sal_Char *) (inet_ntoa(**addrptr)) );
159 return aUString;
162 /** get local ethernet IP
164 ::rtl::OUString getLocalIP( )
166 char hostname[255];
167 gethostname(hostname, 255);
169 return getIPbyName( hostname );
172 /** construct error message
174 ::rtl::OUString outputError( const ::rtl::OUString & returnVal, const ::rtl::OUString & rightVal, const sal_Char * msg )
176 ::rtl::OUString aUString;
177 if ( returnVal.equals( rightVal ) )
178 return aUString;
179 aUString += ::rtl::OUString::createFromAscii(msg);
180 aUString += ::rtl::OUString::createFromAscii(": the returned value is '");
181 aUString += returnVal;
182 aUString += ::rtl::OUString::createFromAscii("', but the value should be '");
183 aUString += rightVal;
184 aUString += ::rtl::OUString::createFromAscii("'.");
185 return aUString;
188 /** wait _nSec seconds.
190 void thread_sleep( sal_Int32 _nSec )
192 /// print statement in thread process must use fflush() to force display.
193 // printf("wait %d seconds. ", _nSec );
194 // fflush(stdout);
196 #ifdef WNT //Windows
197 Sleep( _nSec * 100 );
198 #endif
199 #if ( defined UNX ) || ( defined OS2 ) //Unix
200 usleep(_nSec * 100000);
201 #endif
202 // t_print("# done\n" );
205 /** print Boolean value.
207 void printBool( sal_Bool bOk )
209 t_print("printBool " );
210 ( sal_True == bOk ) ? t_print("YES!" ): t_print("NO!");
211 t_print("\n");
214 /** print content of a ByteSequence.
216 void printByteSequence_IP( const ::rtl::ByteSequence & bsByteSeq, sal_Int32 nLen )
218 t_print("ByteSequence is: " );
219 for ( int i = 0; i < nLen; i++ ){
220 if ( bsByteSeq[i] < 0 )
221 t_print("%d ", 256 + bsByteSeq[i] );
222 else
223 t_print("%d ", bsByteSeq[i] );
225 t_print(" .\n" );
228 /** convert an IP which is stored as a UString format to a ByteSequence array for later use.
230 ::rtl::ByteSequence UStringIPToByteSequence( ::rtl::OUString aUStr )
233 rtl::OString aString = ::rtl::OUStringToOString( aUStr, RTL_TEXTENCODING_ASCII_US );
234 const sal_Char *pChar = aString.getStr( ) ;
235 sal_Char tmpBuffer[4];
236 sal_Int32 nCharCounter = 0;
237 ::rtl::ByteSequence bsByteSequence( IP_VER );
238 sal_Int32 nByteSeqCounter = 0;
240 for ( int i = 0; i < aString.getLength( ) + 1 ; i++ )
242 if ( ( *pChar != '.' ) && ( i !=aString.getLength( ) ) )
243 tmpBuffer[nCharCounter++] = *pChar;
244 else
246 tmpBuffer[nCharCounter] = '\0';
247 nCharCounter = 0;
248 bsByteSequence[nByteSeqCounter++] = static_cast<sal_Int8>(atoi( tmpBuffer ));
250 pChar++;
252 return bsByteSequence;
255 /** print a socket result name.
257 void printSocketResult( oslSocketResult eResult )
259 t_print("printSocketResult: " );
260 if (!eResult)
261 switch (eResult)
263 case osl_Socket_Ok:
264 t_print("client connected\n");
265 break;
266 case osl_Socket_Error:
267 t_print("got an error ... exiting\r\n\r\n" );
268 break;
269 case osl_Socket_TimedOut:
270 t_print("timeout\n");
271 break;
272 case osl_Socket_Interrupted:
273 t_print("interrupted\n");
274 break;
275 case osl_Socket_InProgress:
276 t_print("in progress\n");
277 break;
278 default:
279 t_print("unknown result\n");
280 break;
284 /** if 4 parts of an IP addr are equal to specified values
286 sal_Bool ifIpv4is( const ::rtl::ByteSequence Ipaddr, sal_Int8 seq1, sal_Int8 seq2, sal_Int8 seq3, sal_Int8 seq4 )
288 if ( ( Ipaddr[0] == seq1 ) && ( Ipaddr[1] == seq2 ) && ( Ipaddr[2] == seq3 ) && ( Ipaddr[3] == seq4 ) )
289 return sal_True;
290 return sal_False;
293 /** if the IP or hostname is availble( alive )
295 /*sal_Bool ifAvailable( const char * stringAddrOrHostName )
297 sal_Bool result;
298 int p[2];
299 sal_Char buffer[2000];
300 char stringhost[20];
301 strcpy(stringhost, stringAddrOrHostName );
303 result = sal_False;
304 if (pipe (p) == 0)
306 pid_t pid;
307 int nStatus;
308 pid = fork();
309 if (pid == 0)
311 #if ( defined LINUX )
312 char *argv[] =
314 "/bin/ping",
315 "-c", "3",
316 "-W", "3",
317 stringhost,
318 NULL
320 #endif
321 #if ( defined SOLARIS )
322 char *argv[] =
324 "/usr/sbin/ping",
325 stringhost,
326 "3",
327 NULL
329 #endif
330 close (p[0]);
331 dup2 (p[1], 1);
332 close (p[1]);
333 #if ( defined LINUX )
334 execv ("/bin/ping", argv);
335 #endif
336 #if ( defined SOLARIS )
337 execv ("/usr/sbin/ping", argv);
338 #endif
339 // arriving here means exec failed
340 _exit(-1);
342 else if (pid > 0)
344 sal_Int32 k = 0, n = 2000;
345 close (p[1]);
346 if ((k = read (p[0], buffer, n - 1)) > 0)
348 buffer[k] = 0;
349 if (buffer[k - 1] == '\n')
350 buffer[k - 1] = 0;
351 #if ( defined LINUX )
352 char strOK[] = "bytes from";
353 #endif
354 #if ( defined SOLARIS )
355 char strOK[] = "is alive";
356 #endif
357 if (strstr( buffer, strOK ) != NULL )
358 result = sal_True;
359 t_print("buffer is %s\n", buffer );
361 close (p[0]);
362 waitpid (pid, &nStatus, 0);
364 else
366 close (p[0]);
367 close (p[1]);
371 return result;
374 sal_Bool ifAvailable( rtl::OUString const& strAddrOrHostName )
376 ::osl::ConnectorSocket aSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream );
377 ::osl::SocketAddr aSocketAddr( strAddrOrHostName, 7 );
379 if (! aSocketAddr.is())
381 aSocket.close();
382 return sal_False;
385 aSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True;
387 TimeValue *pTimeout;
388 pTimeout = ( TimeValue* )malloc( sizeof( TimeValue ) );
389 pTimeout->Seconds = 3;
390 pTimeout->Nanosec = 0;
392 oslSocketResult aResult = aSocket.connect( aSocketAddr, pTimeout );
393 free( pTimeout );
394 aSocket.close();
395 if ( aResult != osl_Socket_Ok )
397 t_print("Error: ");
398 printSocketResult(aResult);
399 t_print("\n");
401 return sal_False;
403 return sal_True;