3 Copyright (C) 2010 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #define WIN32_LEAN_AND_MEAN
24 // Without this some of the network functions are not found on mingw
26 #define _WIN32_WINNT 0x0501
32 #pragma comment(lib, "ws2_32.lib")
34 typedef SOCKET socket_t;
35 typedef int socklen_t;
37 #include <sys/types.h>
38 #include <sys/socket.h>
39 #include <netinet/in.h>
43 #include <arpa/inet.h>
47 #include "constants.h"
55 bool socket_enable_debug_output = false;
56 #define DP socket_enable_debug_output
57 // This is prepended to everything printed here
60 bool g_sockets_initialized = false;
66 if(WSAStartup( MAKEWORD(2,2), &WsaData ) != NO_ERROR)
67 throw SocketException("WSAStartup failed");
70 g_sockets_initialized = true;
73 void sockets_cleanup()
86 Address::Address(unsigned int address, unsigned short port)
92 Address::Address(unsigned int a, unsigned int b,
93 unsigned int c, unsigned int d,
96 m_address = (a<<24) | (b<<16) | ( c<<8) | d;
100 bool Address::operator==(Address &address)
102 return (m_address == address.m_address
103 && m_port == address.m_port);
106 bool Address::operator!=(Address &address)
108 return !(*this == address);
111 void Address::Resolve(const char *name)
113 struct addrinfo *resolved;
114 int e = getaddrinfo(name, NULL, NULL, &resolved);
116 throw ResolveError("");
118 FIXME: This is an ugly hack; change the whole class
119 to store the address as sockaddr
121 struct sockaddr_in *t = (struct sockaddr_in*)resolved->ai_addr;
122 m_address = ntohl(t->sin_addr.s_addr);
123 freeaddrinfo(resolved);
126 std::string Address::serializeString() const
128 unsigned int a, b, c, d;
129 a = (m_address & 0xFF000000)>>24;
130 b = (m_address & 0x00FF0000)>>16;
131 c = (m_address & 0x0000FF00)>>8;
132 d = (m_address & 0x000000FF);
133 return itos(a)+"."+itos(b)+"."+itos(c)+"."+itos(d);
136 unsigned int Address::getAddress() const
141 unsigned short Address::getPort() const
146 void Address::setAddress(unsigned int address)
151 void Address::setAddress(unsigned int a, unsigned int b,
152 unsigned int c, unsigned int d)
154 m_address = (a<<24) | (b<<16) | ( c<<8) | d;
157 void Address::setPort(unsigned short port)
162 void Address::print(std::ostream *s) const
164 (*s)<<((m_address>>24)&0xff)<<"."
165 <<((m_address>>16)&0xff)<<"."
166 <<((m_address>>8)&0xff)<<"."
167 <<((m_address>>0)&0xff)<<":"
171 void Address::print() const
176 UDPSocket::UDPSocket()
178 if(g_sockets_initialized == false)
179 throw SocketException("Sockets not initialized");
181 m_handle = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
184 dstream<<DPS<<"UDPSocket("<<(int)m_handle<<")::UDPSocket()"<<std::endl;
188 throw SocketException("Failed to create socket");
192 DWORD nonblocking = 0;
193 if(ioctlsocket(m_handle, FIONBIO, &nonblocking) != 0)
195 throw SocketException("Failed set non-blocking mode");
199 if(fcntl(m_handle, F_SETFL, O_NONBLOCK, nonblocking) == -1)
201 throw SocketException("Failed set non-blocking mode");
208 UDPSocket::~UDPSocket()
211 dstream<<DPS<<"UDPSocket("<<(int)m_handle<<")::~UDPSocket()"<<std::endl;
214 closesocket(m_handle);
220 void UDPSocket::Bind(unsigned short port)
223 dstream<<DPS<<"UDPSocket("<<(int)m_handle
224 <<")::Bind(): port="<<port<<std::endl;
227 address.sin_family = AF_INET;
228 address.sin_addr.s_addr = INADDR_ANY;
229 address.sin_port = htons(port);
231 if(bind(m_handle, (const sockaddr*)&address, sizeof(sockaddr_in)) < 0)
233 #ifndef DISABLE_ERRNO
234 dstream<<(int)m_handle<<": Bind failed: "<<strerror(errno)<<std::endl;
236 throw SocketException("Failed to bind socket");
240 void UDPSocket::Send(const Address & destination, const void * data, int size)
242 bool dumping_packet = false;
243 if(INTERNET_SIMULATOR)
244 dumping_packet = (myrand()%10==0); //easy
245 //dumping_packet = (myrand()%4==0); // hard
248 /*dstream<<DPS<<"UDPSocket("<<(int)m_handle
249 <<")::Send(): destination=";*/
251 dstream<<(int)m_handle<<" -> ";
253 dstream<<", size="<<size<<", data=";
254 for(int i=0; i<size && i<20; i++){
255 if(i%2==0) DEBUGPRINT(" ");
256 unsigned int a = ((const unsigned char*)data)[i];
257 DEBUGPRINT("%.2X", a);
262 dstream<<" (DUMPED BY INTERNET_SIMULATOR)";
265 else if(dumping_packet)
267 // Lol let's forget it
268 dstream<<"UDPSocket::Send(): "
269 "INTERNET_SIMULATOR: dumping packet."
277 address.sin_family = AF_INET;
278 address.sin_addr.s_addr = htonl(destination.getAddress());
279 address.sin_port = htons(destination.getPort());
281 int sent = sendto(m_handle, (const char*)data, size,
282 0, (sockaddr*)&address, sizeof(sockaddr_in));
286 throw SendFailedException("Failed to send packet");
290 int UDPSocket::Receive(Address & sender, void * data, int size)
292 if(WaitData(m_timeout_ms) == false)
298 socklen_t address_len = sizeof(address);
300 int received = recvfrom(m_handle, (char*)data,
301 size, 0, (sockaddr*)&address, &address_len);
306 unsigned int address_ip = ntohl(address.sin_addr.s_addr);
307 unsigned int address_port = ntohs(address.sin_port);
309 sender = Address(address_ip, address_port);
312 //dstream<<DPS<<"UDPSocket("<<(int)m_handle<<")::Receive(): sender=";
313 dstream<<DPS<<(int)m_handle<<" <- ";
315 //dstream<<", received="<<received<<std::endl;
316 dstream<<", size="<<received<<", data=";
317 for(int i=0; i<received && i<20; i++){
318 if(i%2==0) DEBUGPRINT(" ");
319 unsigned int a = ((const unsigned char*)data)[i];
320 DEBUGPRINT("%.2X", a);
330 int UDPSocket::GetHandle()
335 void UDPSocket::setTimeoutMs(int timeout_ms)
337 m_timeout_ms = timeout_ms;
340 bool UDPSocket::WaitData(int timeout_ms)
345 // Initialize the set
347 FD_SET(m_handle, &readset);
349 // Initialize time out struct
352 tv.tv_usec = timeout_ms * 1000;
354 result = select(m_handle+1, &readset, NULL, NULL, &tv);
358 /*dstream<<"Select timed out (timeout_ms="
359 <<timeout_ms<<")"<<std::endl;*/
362 else if(result < 0 && errno == EINTR){
367 #ifndef DISABLE_ERRNO
368 dstream<<(int)m_handle<<": Select failed: "<<strerror(errno)<<std::endl;
371 int e = WSAGetLastError();
372 dstream<<(int)m_handle<<": WSAGetLastError()="<<e<<std::endl;
373 if(e == 10004 /*=WSAEINTR*/)
375 dstream<<"WARNING: Ignoring WSAEINTR."<<std::endl;
379 throw SocketException("Select failed");
381 else if(FD_ISSET(m_handle, &readset) == false){
383 //dstream<<"Select reported no data in m_handle"<<std::endl;
388 //dstream<<"Select reported data in m_handle"<<std::endl;