2 * Copyright (C) 2011 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 #include "TcpStream.h"
17 #include <cutils/sockets.h>
25 #include <netinet/in.h>
26 #include <netinet/tcp.h>
31 static int _socket_loopback_server(int port, int type)
33 struct sockaddr_in addr;
35 memset(&addr, 0, sizeof(addr));
36 addr.sin_family = AF_INET;
37 addr.sin_port = htons(port);
38 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
41 int s = socket(AF_INET, type, 0);
46 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *) &n, sizeof(n));
48 if (bind(s, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) < 0) {
53 if (type == SOCK_STREAM) {
54 if (listen(s, 4) < 0) {
63 TcpStream::TcpStream(size_t bufSize) :
68 TcpStream::TcpStream(int sock, size_t bufSize) :
69 SocketStream(sock, bufSize)
71 // disable Nagle algorithm to improve bandwidth of small
72 // packets which are quite common in our implementation.
79 setsockopt( sock, IPPROTO_TCP, TCP_NODELAY, (const char*)&flag, sizeof(flag) );
82 int TcpStream::listen(unsigned short port)
84 m_sock = _socket_loopback_server(port, SOCK_STREAM);
85 if (!valid()) return int(ERR_INVALID_SOCKET);
90 SocketStream * TcpStream::accept()
95 struct sockaddr_in addr;
96 socklen_t len = sizeof(addr);
97 clientSock = ::accept(m_sock, (sockaddr *)&addr, &len);
99 if (clientSock < 0 && errno == EINTR) {
105 TcpStream *clientStream = NULL;
107 if (clientSock >= 0) {
108 clientStream = new TcpStream(clientSock, m_bufsize);
113 int TcpStream::connect(unsigned short port)
115 return connect("127.0.0.1",port);
118 int TcpStream::connect(const char* hostname, unsigned short port)
120 m_sock = socket_network_client(hostname, port, SOCK_STREAM);
121 if (!valid()) return -1;