• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2016 The SwiftShader Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //    http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "Socket.hpp"
16 
17 #if defined(_WIN32)
18 #	include <ws2tcpip.h>
19 #else
20 #	include <unistd.h>
21 #	include <netdb.h>
22 #	include <netinet/in.h>
23 #	include <sys/select.h>
24 #endif
25 
26 namespace sw {
27 
Socket(SOCKET socket)28 Socket::Socket(SOCKET socket)
29     : socket(socket)
30 {
31 }
32 
Socket(const char * address,const char * port)33 Socket::Socket(const char *address, const char *port)
34 {
35 #if defined(_WIN32)
36 	socket = INVALID_SOCKET;
37 #else
38 	socket = -1;
39 #endif
40 
41 	addrinfo hints = {};
42 	hints.ai_family = AF_INET;
43 	hints.ai_socktype = SOCK_STREAM;
44 	hints.ai_protocol = IPPROTO_TCP;
45 	hints.ai_flags = AI_PASSIVE;
46 
47 	addrinfo *info = 0;
48 	getaddrinfo(address, port, &hints, &info);
49 
50 	if(info)
51 	{
52 		socket = ::socket(info->ai_family, info->ai_socktype, info->ai_protocol);
53 		bind(socket, info->ai_addr, (int)info->ai_addrlen);
54 	}
55 }
56 
~Socket()57 Socket::~Socket()
58 {
59 #if defined(_WIN32)
60 	closesocket(socket);
61 #else
62 	close(socket);
63 #endif
64 }
65 
listen(int backlog)66 void Socket::listen(int backlog)
67 {
68 	::listen(socket, backlog);
69 }
70 
select(int us)71 bool Socket::select(int us)
72 {
73 	fd_set sockets;
74 	FD_ZERO(&sockets);
75 	FD_SET(socket, &sockets);
76 
77 	timeval timeout = { us / 1000000, us % 1000000 };
78 
79 	return ::select(FD_SETSIZE, &sockets, 0, 0, &timeout) >= 1;
80 }
81 
accept()82 Socket *Socket::accept()
83 {
84 	return new Socket(::accept(socket, 0, 0));
85 }
86 
receive(char * buffer,int length)87 int Socket::receive(char *buffer, int length)
88 {
89 	return recv(socket, buffer, length, 0);
90 }
91 
send(const char * buffer,int length)92 void Socket::send(const char *buffer, int length)
93 {
94 	::send(socket, buffer, length, 0);
95 }
96 
startup()97 void Socket::startup()
98 {
99 #if defined(_WIN32)
100 	WSADATA winsockData;
101 	WSAStartup(MAKEWORD(2, 2), &winsockData);
102 #endif
103 }
104 
cleanup()105 void Socket::cleanup()
106 {
107 #if defined(_WIN32)
108 	WSACleanup();
109 #endif
110 }
111 
112 }  // namespace sw
113