1 // sg_socket.cxx -- Socket I/O routines
3 // Written by Curtis Olson, started November 1999.
5 // Copyright (C) 1999 Curtis L. Olson - curt@flightgear.org
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 #include <simgear/compiler.h>
26 #if ! defined( _MSC_VER )
27 # include <sys/time.h> // select()
28 # include <sys/types.h> // socket(), bind(), select(), accept()
29 # include <sys/socket.h> // socket(), bind(), listen(), accept()
30 # include <netinet/in.h> // struct sockaddr_in
31 # include <netdb.h> // gethostbyname()
32 # include <unistd.h> // select(), fsync()/fdatasync()
34 # include <sys/timeb.h> // select()
35 # include <winsock2.h> // socket(), bind(), listen(), accept(),
36 // struct sockaddr_in, gethostbyname()
47 #include <simgear/debug/logstream.hxx>
49 #include "sg_socket.hxx"
54 SGSocket::SGSocket() :
57 set_type( sgSocketType );
61 SGSocket::~SGSocket() {
65 int SGSocket::make_server_socket () {
66 struct sockaddr_in name;
68 #if defined( __CYGWIN__ ) || defined( __CYGWIN32__ ) || defined( sgi ) || defined( _MSC_VER )
75 sock = socket (PF_INET, SOCK_STREAM, 0);
77 FG_LOG( FG_IO, FG_ALERT,
78 "Error: socket() failed in make_server_socket()" );
82 // Give the socket a name.
83 name.sin_family = AF_INET;
84 name.sin_addr.s_addr = INADDR_ANY;
85 name.sin_port = htons(port); // set port to zero to let system pick
86 name.sin_addr.s_addr = htonl (INADDR_ANY);
87 if (bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) {
88 FG_LOG( FG_IO, FG_ALERT,
89 "Error: bind() failed in make_server_socket()" );
93 // Find the assigned port number
94 length = sizeof(struct sockaddr_in);
95 if ( getsockname(sock, (struct sockaddr *) &name, &length) ) {
96 FG_LOG( FG_IO, FG_ALERT,
97 "Error: getsockname() failed in make_server_socket()" );
100 port = ntohs(name.sin_port);
106 int SGSocket::make_client_socket () {
107 struct sockaddr_in name;
110 FG_LOG( FG_IO, FG_INFO, "Make client socket()" );
112 // Create the socket.
113 sock = socket (PF_INET, SOCK_STREAM, 0);
115 FG_LOG( FG_IO, FG_ALERT,
116 "Error: socket() failed in make_client_socket()" );
120 // specify address family
121 name.sin_family = AF_INET;
123 // get the hosts official name/info
124 hp = gethostbyname( hostname.c_str() );
126 // Connect this socket to the host and the port specified on the
128 #if defined( __CYGWIN__ ) || defined( __CYGWIN32__ )
129 bcopy(hp->h_addr, (char *)(&(name.sin_addr.s_addr)), hp->h_length);
131 bcopy(hp->h_addr, &(name.sin_addr.s_addr), hp->h_length);
133 name.sin_port = htons(port);
135 if ( connect(sock, (struct sockaddr *) &name,
136 sizeof(struct sockaddr_in)) < 0 )
143 FG_LOG( FG_IO, FG_ALERT,
144 "Error: connect() failed in make_client_socket()" );
152 // If specified as a server (out direction for now) open the master
153 // listening socket. If specified as a client, open a connection to a
156 bool SGSocket::open( SGProtocolDir dir ) {
157 if ( port_str == "" || port_str == "any" ) {
160 port = atoi( port_str.c_str() );
163 client_connections.clear();
165 if ( dir == SG_IO_OUT ) {
166 // this means server for now
168 // Setup socket to listen on. Set "port" before making this
169 // call. A port of "0" indicates that we want to let the os
170 // pick any available port.
171 sock = make_server_socket();
172 FG_LOG( FG_IO, FG_INFO, "socket is connected to port = " << port );
174 // Specify the maximum length of the connection queue
175 listen(sock, SG_MAX_SOCKET_QUEUE);
177 } else if ( dir == SG_IO_IN ) {
178 // this means client for now
180 sock = make_client_socket();
182 FG_LOG( FG_IO, FG_ALERT,
183 "Error: bidirection mode not available yet for sockets." );
188 FG_LOG( FG_IO, FG_ALERT, "Error opening socket: " << hostname
197 // read data from socket (client)
198 // read a block of data of specified size
199 int SGSocket::read( char *buf, int length ) {
202 // check for potential input
205 FD_SET(sock, &ready);
210 // test for any input read on sock (returning immediately, even if
212 select(32, &ready, 0, 0, &tv);
214 if ( FD_ISSET(sock, &ready) ) {
216 result = _read( sock, buf, length );
218 result = std::read( sock, buf, length );
220 if ( result != length ) {
221 FG_LOG( FG_IO, FG_INFO,
222 "Warning: read() not enough bytes." );
230 // read a line of data, length is max size of input buffer
231 int SGSocket::readline( char *buf, int length ) {
234 // check for potential input
237 FD_SET(sock, &ready);
242 // test for any input read on sock (returning immediately, even if
244 select(32, &ready, 0, 0, &tv);
246 if ( FD_ISSET(sock, &ready) ) {
247 // read a chunk, keep in the save buffer until we have the
248 // requested amount read
250 char *buf_ptr = save_buf + save_len;
252 result = _read( sock, buf_ptr, SG_IO_MAX_MSG_SIZE - save_len );
254 result = std::read( sock, buf_ptr, SG_IO_MAX_MSG_SIZE - save_len );
257 // cout << "current read = " << buf_ptr << endl;
258 // cout << "current save_buf = " << save_buf << endl;
259 // cout << "save_len = " << save_len << endl;
262 // look for the end of line in save_buf
264 for ( i = 0; i < save_len && save_buf[i] != '\n'; ++i );
265 if ( save_buf[i] == '\n' ) {
268 // no end of line yet
269 // cout << "no eol found" << endl;
272 // cout << "line length = " << result << endl;
274 // we found an end of line
276 // copy to external buffer
277 strncpy( buf, save_buf, result );
279 // cout << "sg_socket line = " << buf << endl;
282 for ( i = result; i < save_len; ++i ) {
283 save_buf[ i - result ] = save_buf[i];
291 // write data to socket (server)
292 int SGSocket::write( char *buf, int length ) {
294 // check for any new client connection requests
297 FD_SET(sock, &ready);
302 // test for any input on sock (returning immediately, even if
304 select(32, &ready, 0, 0, &tv);
306 // any new connections?
307 if ( FD_ISSET(sock, &ready) ) {
308 int msgsock = accept(sock, 0, 0);
310 FG_LOG( FG_IO, FG_ALERT,
311 "Error: accept() failed in write()" );
314 client_connections.push_back( msgsock );
318 bool error_condition = false;
319 FG_LOG( FG_IO, FG_INFO, "Client connections = " <<
320 client_connections.size() );
321 for ( int i = 0; i < (int)client_connections.size(); ++i ) {
322 int msgsock = client_connections[i];
324 // read and junk any possible incoming messages.
325 // char junk[ SG_IO_MAX_MSG_SIZE ];
326 // std::read( msgsock, junk, SG_IO_MAX_MSG_SIZE );
328 // write the interesting data to the socket
330 if ( _write(msgsock, buf, length) < 0 ) {
332 if ( std::write(msgsock, buf, length) < 0 ) {
334 FG_LOG( FG_IO, FG_ALERT, "Error writing to socket: " << port );
335 error_condition = true;
337 #ifdef _POSIX_SYNCHRONIZED_IO
338 // fdatasync(msgsock);
345 if ( error_condition ) {
353 // write null terminated string to socket (server)
354 int SGSocket::writestring( char *str ) {
355 int length = strlen( str );
356 return write( str, length );
361 bool SGSocket::close() {
362 for ( int i = 0; i < (int)client_connections.size(); ++i ) {
363 int msgsock = client_connections[i];
367 std::close( msgsock );