• 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 #endif
24 
25 namespace sw
26 {
Socket(SOCKET socket)27 	Socket::Socket(SOCKET socket) : socket(socket)
28 	{
29 	}
30 
Socket(const char * address,const char * port)31 	Socket::Socket(const char *address, const char *port)
32 	{
33 		#if defined(_WIN32)
34 			socket = INVALID_SOCKET;
35 		#else
36 			socket = -1;
37 		#endif
38 
39 		addrinfo hints = {};
40 		hints.ai_family = AF_INET;
41 		hints.ai_socktype = SOCK_STREAM;
42 		hints.ai_protocol = IPPROTO_TCP;
43 		hints.ai_flags = AI_PASSIVE;
44 
45 		addrinfo *info = 0;
46 		getaddrinfo(address, port, &hints, &info);
47 
48 		if(info)
49 		{
50 			socket = ::socket(info->ai_family, info->ai_socktype, info->ai_protocol);
51 			bind(socket, info->ai_addr, (int)info->ai_addrlen);
52 		}
53 	}
54 
~Socket()55 	Socket::~Socket()
56 	{
57 		#if defined(_WIN32)
58 			closesocket(socket);
59 		#else
60 			close(socket);
61 		#endif
62 	}
63 
listen(int backlog)64 	void Socket::listen(int backlog)
65 	{
66 		::listen(socket, backlog);
67 	}
68 
select(int us)69 	bool Socket::select(int us)
70 	{
71 		fd_set sockets;
72 		FD_ZERO(&sockets);
73 		FD_SET(socket, &sockets);
74 
75 		timeval timeout = {us / 1000000, us % 1000000};
76 
77 		return ::select(FD_SETSIZE, &sockets, 0, 0, &timeout) >= 1;
78 	}
79 
accept()80 	Socket *Socket::accept()
81 	{
82 		return new Socket(::accept(socket, 0, 0));
83 	}
84 
receive(char * buffer,int length)85 	int Socket::receive(char *buffer, int length)
86 	{
87 		return recv(socket, buffer, length, 0);
88 	}
89 
send(const char * buffer,int length)90 	void Socket::send(const char *buffer, int length)
91 	{
92 		::send(socket, buffer, length, 0);
93 	}
94 
startup()95 	void Socket::startup()
96 	{
97 		#if defined(_WIN32)
98 			WSADATA winsockData;
99 			WSAStartup(MAKEWORD(2, 2), &winsockData);
100 		#endif
101 	}
102 
cleanup()103 	void Socket::cleanup()
104 	{
105 		#if defined(_WIN32)
106 			WSACleanup();
107 		#endif
108 	}
109 }
110