2 * Copyright (C) Volition, Inc. 1999. All rights reserved.
4 * All source code herein is the property of Volition, Inc. You may not sell
5 * or otherwise commercially exploit the source or things you created based on
10 * $Logfile: /Freespace2/code/Network/Psnet2.cpp $
15 * C file containing application level network-interface.
18 * Revision 1.14 2005/10/02 09:30:10 taylor
19 * sync up rest of big-endian network changes. it should at least be as good as what's in FS2_Open now, only better :)
21 * Revision 1.13 2005/10/01 22:01:28 taylor
22 * some cleanup of earlier big-endian changes
24 * Revision 1.12 2004/07/04 11:39:06 taylor
25 * fix missing debrief text, crash on exit, path separator's, warning fixes, no GR_SOFT
27 * Revision 1.11 2004/06/11 01:52:15 tigital
28 * byte-swapping changes for bigendian systems
30 * Revision 1.10 2003/08/03 16:10:30 taylor
31 * cleanup; compile warning fixes
33 * Revision 1.9 2002/07/27 19:52:54 relnev
34 * add missing structure packing
36 * Revision 1.8 2002/06/09 04:41:24 relnev
37 * added copyright header
39 * Revision 1.7 2002/06/02 05:31:17 relnev
42 * Revision 1.6 2002/06/02 02:29:39 relnev
45 * Revision 1.5 2002/05/27 04:04:43 relnev
46 * 155 undefined references left
48 * Revision 1.4 2002/05/26 21:27:53 theoddone33
49 * More progress (I hate psnet2)
51 * Revision 1.3 2002/05/26 20:49:54 theoddone33
54 * Revision 1.2 2002/05/07 03:16:48 theoddone33
55 * The Great Newline Fix
57 * Revision 1.1.1.1 2002/05/03 03:28:10 root
61 * 25 9/14/99 2:21p Dave
62 * Fixed observer mode joining and ingame stuff.
64 * 24 9/10/99 9:44p Dave
65 * Bumped version # up. Make server reliable connects not have such a huge
68 * 23 9/07/99 4:01p Dave
69 * Fixed up a string.tbl paroblem (self destruct message). Make sure IPX
70 * does everything properly (setting up address when binding). Remove
71 * black rectangle background from UI_INPUTBOX.
73 * 22 8/26/99 8:51p Dave
74 * Gave multiplayer TvT messaging a heavy dose of sanity. Cheat codes.
76 * 21 8/16/99 4:06p Dave
77 * Big honking checkin.
79 * 20 7/26/99 5:50p Dave
80 * Revised ingame join. Better? We'll see....
82 * 19 7/20/99 1:49p Dave
83 * Peter Drake build. Fixed some release build warnings.
85 * 18 7/15/99 9:20a Andsager
86 * FS2_DEMO initial checkin
88 * 17 7/03/99 4:08p Dave
89 * Fixed wss_slots size issues. Fixed potentially nasty bug in low level
92 * 16 6/25/99 5:02p Jasenw
93 * Removed old debug code.
95 * 15 6/07/99 9:51p Dave
96 * Consolidated all multiplayer ports into one.
98 * 14 4/30/99 12:18p Dave
99 * Several minor bug fixes.
101 * 13 4/27/99 5:55p Dave
102 * Fixed Ras_connected bug with VSDK code.
104 * 12 4/27/99 2:59p Dave
105 * Potential fix for reliable socket connection problem.
107 * 11 4/23/99 11:07a Dave
108 * Added lots of debug multi.log output to psnet2
110 * 10 4/12/99 10:07p Dave
111 * Made network startup more forgiving. Added checkmarks to dogfight
112 * screen for players who hit commit.
114 * 9 3/10/99 6:50p Dave
115 * Changed the way we buffer packets for all clients. Optimized turret
116 * fired packets. Did some weapon firing optimizations.
118 * 8 3/09/99 6:24p Dave
119 * More work on object update revamping. Identified several sources of
120 * unnecessary bandwidth.
122 * 7 3/08/99 7:03p Dave
123 * First run of new object update system. Looks very promising.
125 * 6 1/24/99 11:37p Dave
126 * First full rev of beam weapons. Very customizable. Removed some bogus
127 * Int3()'s in low level net code.
129 * 5 1/06/99 2:24p Dave
130 * Stubs and release build fixes.
132 * 4 11/20/98 11:16a Dave
133 * Fixed up IPX support a bit. Making sure that switching modes and
134 * loading/saving pilot files maintains proper state.
136 * 3 11/19/98 4:19p Dave
137 * Put IPX sockets back in psnet. Consolidated all multiplayer config
140 * 2 11/19/98 8:04a Dave
141 * Full support for D3-style reliable sockets. Revamped packet lag/loss
142 * system, made it receiver side and at the lowest possible level.
149 #include <windowsx.h>
153 #include <raserror.h>
155 #include <sys/types.h>
156 #include <sys/socket.h>
157 #include <netinet/in.h>
158 #include <arpa/inet.h>
168 #include "multiutil.h"
169 #include "multilag.h"
170 #include "osregistry.h"
172 #include "multi_log.h"
173 #include "multi_rate.h"
178 // -------------------------------------------------------------------------------------------------------
179 // PSNET 2 DEFINES/VARS
182 int Psnet_my_addr_valid;
183 net_addr_t Psnet_my_addr;
185 const ubyte Null_address[4] = { 0x00, 0x00, 0x00, 0x00 };
188 int Can_broadcast; // can we do broadcasting on our socket?
189 int Tcp_can_broadcast = 0;
194 int Tcp_failure_code = 0;
196 int Psnet_connection;
198 ushort Psnet_default_port;
200 // specified their internet connnection type
201 #define NETWORK_CONNECTION_NONE 1
202 #define NETWORK_CONNECTION_DIALUP 2
203 #define NETWORK_CONNECTION_LAN 3
205 // defines and variables to indicate network connection status
206 #define NETWORK_STATUS_NOT_INITIALIZED 1
207 #define NETWORK_STATUS_NO_WINSOCK 2 // winsock failed to initialize
208 #define NETWORK_STATUS_NO_PROTOCOL 3 // TCP/IP doesn't appear to be loaded
209 #define NETWORK_STATUS_NO_RELIABLE 4
210 #define NETWORK_STATUS_RUNNING 5 // everything should be running
212 // defintion of structures that actually leave this machine. psnet_send give us only
213 // the data that we want to send. We will add a header onto this data (packet sequence
214 // number, possibly a checksum). We must include a 2 byte flags variable into both structure
215 // since the receiving end of this packet must know whether or not to checksum the packet.
217 #define MAX_TOP_LAYER_PACKET_SIZE 680
219 // use the pack pragma to pack these structures to 2 byte aligment. Really only needed for
221 #define MAX_PACKET_BUFFERS 75
224 #pragma pack(push, 2)
227 // definition for a non-checksum packet
228 typedef struct network_packet
232 ubyte data[MAX_TOP_LAYER_PACKET_SIZE];
233 } network_naked_packet;
235 // structure definition for our packet buffers
236 typedef struct network_packet_buffer
240 net_addr_t from_addr;
241 ubyte data[MAX_TOP_LAYER_PACKET_SIZE];
242 } network_packet_buffer;
244 // struct for a bunch of network packet buffers
245 typedef struct network_packet_buffer_list {
246 network_packet_buffer psnet_buffers[MAX_PACKET_BUFFERS];
247 int psnet_seq_number;
249 int psnet_highest_id;
250 } network_packet_buffer_list;
257 #define MAXHOSTNAME 128
259 #define MAX_RECEIVE_BUFSIZE 4096 // 32 K, eh?
260 #define MAX_SEND_RETRIES 20 // number of retries when sending would block
261 #define MAX_LINGER_TIME 0 // in seconds -- when lingering to close a socket
264 //*******************************
265 #define MAXNETBUFFERS 150 // Maximum network buffers (For between network and upper level functions, which is
266 // required in case of out of order packets
267 #define NETRETRYTIME 0.75f // Time after sending before we resend
268 #define MIN_NET_RETRYTIME 0.2f
269 #define NETTIMEOUT 30 // Time after receiving the last packet before we drop that user
270 #define NETHEARTBEATTIME 3 // How often to send a heartbeat
271 #define MAXRELIABLESOCKETS 40 // Max reliable sockets to open at once...
272 #define NETBUFFERSIZE 600 // Max size of a network packet
274 #define RELIABLE_CONNECT_TIME 7 // how long we'll wait for a response when doing a reliable connect
276 int Nettimeout = NETTIMEOUT;
278 // Reliable packet stuff
279 #define RNT_ACK 1 // ACK Packet
280 #define RNT_DATA 2 // Data Packet
281 #define RNT_DATA_COMP 3 // Compressed Data Packet
282 #define RNT_REQ_CONN 4 // Requesting a connection
283 #define RNT_DISCONNECT 5 // Disconnecting a connection
284 #define RNT_HEARTBEAT 6 // Heartbeat -- send every NETHEARTBEATTIME
285 #define RNT_I_AM_HERE 7
288 #pragma pack(push,r_udp)
292 #define PACKED __attribute__((packed))
296 ubyte type; // packet type
298 ushort seq; // sequence packet 0-65535 used for ACKing also
299 ushort data_len; // length of data
300 float send_time; // Time the packet was sent, if an ACK the time the packet being ACK'd was sent.
301 ubyte data[NETBUFFERSIZE]; // Packet data
302 } PACKED reliable_header;
304 #define RELIABLE_PACKET_HEADER_ONLY_SIZE (sizeof(reliable_header)-NETBUFFERSIZE)
305 #define MAX_PING_HISTORY 10
308 ubyte buffer[NETBUFFERSIZE];
310 } PACKED reliable_net_sendbuffer;
313 ubyte buffer[NETBUFFERSIZE];
314 } PACKED reliable_net_rcvbuffer;
317 reliable_net_sendbuffer *sbuffers[MAXNETBUFFERS]; // This is an array of pointers for quick sorting
318 unsigned short ssequence[MAXNETBUFFERS]; // This is the sequence number of the given packet
319 float timesent[MAXNETBUFFERS];
320 int send_len[MAXNETBUFFERS];
321 reliable_net_rcvbuffer *rbuffers[MAXNETBUFFERS];
322 int recv_len[MAXNETBUFFERS];
323 unsigned short rsequence[MAXNETBUFFERS]; // This is the sequence number of the given packet
324 float last_packet_received; // For a given connection, this is the last packet we received
325 float last_packet_sent;
326 struct sockaddr addr; // struct sockaddr of our peer
327 ushort status; // Status of this connection
328 unsigned short oursequence; // This is the next sequence number the application is expecting
329 unsigned short theirsequence; // This is the next sequence number the peer is expecting
330 net_addr_t net_addr; // A FS2 network address structure
331 ubyte connection_type; // IP, modem, etc.
332 float pings[MAX_PING_HISTORY];
334 unsigned int num_ping_samples;
338 reliable_socket Reliable_sockets[MAXRELIABLESOCKETS];
340 // socket TCP (unreliable)
343 // the sockets that the game will use when selecting network type
344 SOCKET Unreliable_socket = INVALID_SOCKET;
347 // SOCKET Reliable_UDP_socket = INVALID_SOCKET;
349 float First_sent_iamhere = 0;
350 float Last_sent_iamhere = 0;
352 #define CONNECTSEQ 0x142 // Magic number for starting a connection, just so it isn't 0
354 unsigned int Serverconn = 0xffffffff;
357 #pragma pack(pop,r_udp)
361 //*******************************
364 network_packet_buffer_list Psnet_top_buffers[PSNET_NUM_TYPES];
366 // -------------------------------------------------------------------------------------------------------
367 // PSNET 2 FORWARD DECLARATIONS
370 // if the string is a legally formatted ip string
371 int psnet_is_valid_numeric_ip(char *ip);
373 // functions to get the status of a RAS connection
374 unsigned int psnet_ras_status();
376 // set some options on a socket
377 void psnet_socket_options( SOCKET sock );
379 // initialize tcp socket
380 int psnet_init_tcp();
382 // get time in seconds
383 float psnet_get_time();
385 // returns the ip address of this machine. use for calling bind() with to associate with the proper
386 // IP address and network device.
389 // initialize reliable sockets
390 int psnet_init_rel_tcp(int port, int should_listen);
392 // shutdown reliable sockets
393 void psnet_rel_close();
395 // initialize the buffering system
396 void psnet_buffer_init(network_packet_buffer_list *l);
398 // buffer a packet (maintain order!)
399 void psnet_buffer_packet(network_packet_buffer_list *l, ubyte *data, int length, net_addr_t *from);
401 // get the index of the next packet in order!
402 int psnet_buffer_get_next(network_packet_buffer_list *l, ubyte *data, int *length, net_addr_t *from);
405 // -------------------------------------------------------------------------------------------------------
406 // PSNET 2 TOP LAYER FUNCTIONS - these functions simply buffer and store packets based upon type (see PSNET_TYPE_* defines)
409 // wrappers around select() and recvfrom() for lagging/losing data
410 int RECVFROM(SOCKET s, char *buf, int len, int flags, sockaddr *from, int *fromlen, int psnet_type)
412 network_packet_buffer_list *l;
418 SDL_assert((psnet_type >= 0) && (psnet_type < PSNET_NUM_TYPES));
419 if((psnet_type < 0) || (psnet_type >= PSNET_NUM_TYPES)){
422 l = &Psnet_top_buffers[psnet_type];
424 // if we have no buffer! The user should have made sure this wasn't the case by calling SELECT()
425 ret = psnet_buffer_get_next(l, (ubyte*)buf, &ret_len, &addr);
431 // otherwise, stuff the outgoing data
432 ((struct sockaddr_in*)from)->sin_port = htons(addr.port);
433 memcpy(&((struct sockaddr_in*)from)->sin_addr.s_addr, addr.addr, 4);
434 ((struct sockaddr_in*)from)->sin_family = AF_INET;
435 *fromlen = sizeof(struct sockaddr_in);
441 // wrappers around select() and recvfrom() for lagging/losing data
442 int SELECT(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout, int psnet_type)
444 network_packet_buffer_list *l;
446 // if this is a check for writability, just return the select
447 if(writefds != NULL){
448 return select(nfds, readfds, writefds, exceptfds, timeout);
452 SDL_assert((psnet_type >= 0) && (psnet_type < PSNET_NUM_TYPES));
453 if((psnet_type < 0) || (psnet_type >= PSNET_NUM_TYPES)){
456 l = &Psnet_top_buffers[psnet_type];
458 // do we have any buffers in here?
459 if((l->psnet_lowest_id == -1) || (l->psnet_lowest_id > l->psnet_highest_id)){
467 // wrappers around sendto to sorting through different packet types
468 int SENDTO(SOCKET s, char * buf, int len, int flags, sockaddr *to, int tolen, int psnet_type)
470 char outbuf[MAX_TOP_LAYER_PACKET_SIZE + 150];
473 outbuf[0] = (char)psnet_type;
474 memcpy(&outbuf[1], buf, len);
476 // is the socket writeable?
479 return sendto(s, outbuf, len + 1, flags, (struct sockaddr*)to, tolen);
482 // call this once per frame to read everything off of our socket
483 void PSNET_TOP_LAYER_PROCESS()
486 struct sockaddr_in ip_addr; // UDP/TCP socket structure
495 net_addr_t from_addr;
496 network_naked_packet packet_read;
498 // clear the addresses to remove compiler warnings
499 memset(&ip_addr, 0, sizeof(struct sockaddr_in));
501 if ( Network_status != NETWORK_STATUS_RUNNING ) {
502 ml_printf("Network ==> socket not inited in PSNET_TOP_LAYER_PROCESS\n");
507 // check if there is any data on the socket to be read. The amount of data that can be
508 // atomically read is stored in len.
511 FD_SET( Unreliable_socket, &rfds );
515 if ( select( Unreliable_socket+1, &rfds, NULL, NULL, &timeout) == SOCKET_ERROR ) {
516 ml_printf("Error %d doing a socket select on read\n", WSAGetLastError());
520 // if the read file descriptor is not set, then bail!
521 if ( !FD_ISSET(Unreliable_socket, &rfds) ){
525 // get data off the socket and process
526 from_len = sizeof(struct sockaddr_in);
527 read_len = recvfrom( Unreliable_socket, (char*)packet_read.data, MAX_TOP_LAYER_PACKET_SIZE, 0, (struct sockaddr*)&ip_addr, &from_len);
529 // set the from_addr for storage into the packet buffer structure
530 from_addr.type = Socket_type;
531 from_addr.port = ntohs( ip_addr.sin_port );
532 memcpy(from_addr.addr, &ip_addr.sin_addr.s_addr, 4);
534 if ( read_len == SOCKET_ERROR ) {
535 // int x = WSAGetLastError();
536 ml_printf("Socket error on socket_get_data()");
540 // determine the packet type
541 int packet_type = packet_read.data[0];
542 // mprintf(("TOP LAYER PACKET %d!\n", packet_type));
543 if((packet_type < 0) || (packet_type >= PSNET_NUM_TYPES)){
547 psnet_buffer_packet(&Psnet_top_buffers[packet_type], packet_read.data + 1, read_len - 1, &from_addr);
553 // -------------------------------------------------------------------------------------------------------
557 // initialize psnet to use the specified port
558 void psnet_init( int protocol, int port_num )
560 const char *internet_connection;
567 #if defined(DEMO) || defined(OEM_BUILD) // not for FS2_DEMO
571 // GAME PORT INITIALIZATION STUFF
572 if ( Network_status == NETWORK_STATUS_RUNNING ){
573 ml_string("Skipping psnet_init() because network already running");
577 // 'lan' should be a safe default in 2015
578 internet_connection = os_config_read_string("Network", "NetworkConnection", "LAN");
580 if ( !SDL_strcasecmp(internet_connection, NOX("dialup")) ) {
581 ml_string("psnet_init() detected dialup connection");
583 Psnet_connection = NETWORK_CONNECTION_DIALUP;
584 } else if ( !SDL_strcasecmp(internet_connection, NOX("lan")) ) {
585 ml_string("psnet_init() detected lan connection");
587 Psnet_connection = NETWORK_CONNECTION_LAN;
589 ml_string("psnet_init() detected no connection");
591 Psnet_connection = NETWORK_CONNECTION_NONE;
594 Network_status = NETWORK_STATUS_NO_WINSOCK;
596 if (WSAStartup(0x101, &wsa_data )){
601 // get the port for running this game on. Be careful that it cannot be out of bounds
602 Psnet_default_port = DEFAULT_GAME_PORT;
603 if ( (port_num > 1023) && (port_num < USHRT_MAX) ) {
604 Psnet_default_port = (ushort)port_num;
607 // initialize TCP now
609 if(!psnet_init_tcp()){
610 ml_printf("Error on TCP startup %d\n", Tcp_failure_code);
614 if(!psnet_init_rel_tcp(Psnet_default_port + 1, 0)){
615 ml_printf("Network", "Error on TCP startup %d\n", Tcp_failure_code);
621 // clear reliable sockets
622 reliable_socket *rsocket;
624 for(j=0; j<MAXRELIABLESOCKETS; j++){
625 rsocket=&Reliable_sockets[j];
626 memset(rsocket,0,sizeof(reliable_socket));
629 // determine if we've successfully initialized the protocol we want
631 Network_status = NETWORK_STATUS_NO_PROTOCOL;
633 ml_string("No protocol in psnet_init()!");
636 // specified network timeout
637 Nettimeout = NETTIMEOUT;
638 if(Cmdline_timeout > 0){
639 Nettimeout = Cmdline_timeout;
645 if(Network_status != NETWORK_STATUS_NO_PROTOCOL){
646 // set network to be running
647 Network_status = NETWORK_STATUS_RUNNING;
649 // determine if our socket can broadcast
650 Can_broadcast = Tcp_can_broadcast;
652 // initialize all packet type buffers
653 for(idx=0; idx<PSNET_NUM_TYPES; idx++){
654 psnet_buffer_init(&Psnet_top_buffers[idx]);
662 if ( Network_status != NETWORK_STATUS_RUNNING ){
667 WSACancelBlockingCall();
670 if ( TCP_socket != (int)INVALID_SOCKET ) {
671 shutdown( TCP_socket, 1 );
672 closesocket( TCP_socket );
677 //Warning( LOCATION, "Error closing wsock!\n" );
681 // close down all reliable sockets - this forces them to
682 // send a disconnect to any remote machines
685 Network_status = NETWORK_STATUS_NOT_INITIALIZED;
688 // set the protocol to use
689 int psnet_use_protocol( int protocol )
696 struct sockaddr_in ip_addr;
698 // zero out my address
699 Psnet_my_addr_valid = 0;
700 memset( &Psnet_my_addr, 0, sizeof(Psnet_my_addr) );
702 // wait until we choose a protocol to determine if we can broadcast
705 ml_string("In psnet_use_protocol()");
707 if (protocol != NET_TCP) {
713 if ( Network_status != NETWORK_STATUS_RUNNING ){
714 ml_string("Network_status != NETWORK_STATUS_RUNNING in NET_TCP in psnet_use_protocol()");
718 // assign the TCP_* sockets to the socket values used elsewhere
719 Unreliable_socket = TCP_socket;
721 Can_broadcast = Tcp_can_broadcast;
723 ml_printf("Psnet : TCP broadcast\n");
726 // get the socket name, and put it into My_addr
727 len = sizeof(struct sockaddr_in);
728 if ( getsockname(TCP_socket, (struct sockaddr *)&ip_addr, &len) == SOCKET_ERROR ) {
729 ml_printf("Unable to get sock name for TCP unreliable socket (%d)\n", WSAGetLastError() );
734 memcpy(Psnet_my_addr.addr, &ip_addr.sin_addr, 4);
735 Psnet_my_addr.port = Psnet_default_port;
737 ml_printf("Psnet using - NET_TCP\n");
740 Psnet_my_addr.type = protocol;
741 Socket_type = protocol;
746 // get the status of the network
747 int psnet_get_network_status()
749 // first case is when "none" is selected
750 if ( Psnet_connection == NETWORK_CONNECTION_NONE ) {
751 return NETWORK_ERROR_NO_TYPE;
754 // first, check the connection status of the network
755 if ( Network_status == NETWORK_STATUS_NO_WINSOCK )
756 return NETWORK_ERROR_NO_WINSOCK;
758 if ( Network_status == NETWORK_STATUS_NO_PROTOCOL ){
759 return NETWORK_ERROR_NO_PROTOCOL;
762 // network is running -- be sure that the RAS people know to connect if they currently cannot.
764 if ( Psnet_connection == NETWORK_CONNECTION_DIALUP ) {
765 // if on a dialup connection, be sure that RAS is active.
766 if ( !Ras_connected ) {
767 return NETWORK_ERROR_CONNECT_TO_ISP;
769 } else if ( Psnet_connection == NETWORK_CONNECTION_LAN ) {
770 // if on a LAN, and they have a dialup connection active, return error to indicate that they need
771 // to pick the right connection type
772 if ( Ras_connected ) {
773 return NETWORK_ERROR_LAN_AND_RAS;
776 return NETWORK_ERROR_NONE;
779 // convert a net_addr to a string
780 char* psnet_addr_to_string( char * text, const int max_textlen, net_addr_t * address )
783 if ( Network_status != NETWORK_STATUS_RUNNING ) {
784 SDL_strlcpy( text, XSTR("[no networking]",910), max_textlen );
790 SDL_assert(address->type == NET_TCP);
792 memcpy(&temp_addr.s_addr, address->addr, 4);
793 SDL_strlcpy( text, inet_ntoa(temp_addr), max_textlen );
798 // convert a string to a net addr
799 void psnet_string_to_addr( net_addr_t * address, char * text, const int max_textlen )
802 char str[255], *c, *port;
805 if ( Network_status != NETWORK_STATUS_RUNNING ) {
806 SDL_strlcpy( text, XSTR("[no networking]",910), max_textlen );
810 // copy the text string to local storage to look for ports
811 SDL_assert( strlen(text) < 255 );
812 SDL_strlcpy(str, text, SDL_arraysize(str));
813 c = strrchr(str, ':');
820 SDL_assert(address->type == NET_TCP);
823 addr.s_addr = inet_addr(str);
824 // if we get INADDR_NONE returns, then we need to try and resolve the host
826 if ( addr.s_addr == INADDR_NONE ) {
827 he = gethostbyname( str );
828 // returns a non-null pointer if successful, so get the address
830 addr.s_addr = ((in_addr *)(he->h_addr))->s_addr; // this is the address in network byte order
832 addr.s_addr = INADDR_NONE;
836 memcpy(address->addr, &addr.s_addr, 4);
839 address->port = (ushort)(atoi(port));
843 // compare 2 addresses
844 int psnet_same( net_addr_t * a1, net_addr_t * a2 )
846 return !memcmp(a1->addr, a2->addr, 4);
849 // send data unreliably
850 int psnet_send( net_addr_t * who_to, void * data, int len, int np_index )
852 // send data unreliably
854 struct sockaddr_in sockaddr; // UDP/TCP socket structure
856 ubyte iaddr[4], *send_data;
859 struct timeval timeout;
861 // always use the reliable socket
862 send_sock = Unreliable_socket;
864 if ( Network_status != NETWORK_STATUS_RUNNING ) {
865 ml_printf("Network ==> Socket not inited in psnet_send\n");
869 if ( psnet_same( who_to, &Psnet_my_addr) ){
873 if (who_to->type != NET_TCP) {
878 memcpy(iaddr, who_to->addr, 4);
880 if ( memcmp(iaddr, Null_address, 4) == 0) {
881 ml_printf("Network ==> send to address is 0 in psnet_send\n");
888 ml_printf("Network ==> destination port %d invalid in psnet_send\n", port);
892 // stuff the data with the type
893 send_data = (ubyte*)data;
897 FD_SET( send_sock, &wfds );
901 if ( SELECT( send_sock+1, NULL, &wfds, NULL, &timeout, PSNET_TYPE_UNRELIABLE) == SOCKET_ERROR ) {
902 ml_printf("Error on blocking select for write %d\n", WSAGetLastError() );
906 // if the write file descriptor is not set, then bail!
907 if ( !FD_ISSET(send_sock, &wfds ) ){
911 sockaddr.sin_family = AF_INET;
912 memcpy(&sockaddr.sin_addr.s_addr, iaddr, 4);
913 sockaddr.sin_port = htons(port);
915 multi_rate_add(np_index, "udp(h)", send_len + UDP_HEADER_SIZE);
916 multi_rate_add(np_index, "udp", send_len);
917 ret = SENDTO( send_sock, (char *)send_data, send_len, 0, (struct sockaddr*)&sockaddr, sizeof(sockaddr), PSNET_TYPE_UNRELIABLE );
919 if ( ret != SOCKET_ERROR ) {
922 //Warning( LOCATION, "Couldn't send data (0x%x)!\n", WSAGetLastError() );
926 // get data from the unreliable socket
927 int psnet_get( void * data, net_addr_t * from_addr )
931 // try and get a free buffer and return its size
932 if(psnet_buffer_get_next(&Psnet_top_buffers[PSNET_TYPE_UNRELIABLE], (ubyte*)data, &buffer_size, from_addr)){
940 // broadcast data on unreliable socket
941 int psnet_broadcast( net_addr_t * who_to, void * data, int len )
943 if ( Network_status != NETWORK_STATUS_RUNNING ) {
944 ml_printf("Network ==> Socket not inited in psnet_broadcast\n");
948 if ( !Can_broadcast ) {
949 ml_printf("Cannot broadcast -- returning without doing anything\n");
953 ubyte broadcast[4] = { 0xff, 0xff, 0xff, 0xff };
955 // broadcasting works on a local subnet which is all we really want to do for now anyway.
956 // we might keep this in as an option for freespace later.
957 memcpy(who_to->addr, broadcast, 4);
958 psnet_send(who_to, data, len);
966 ubyte data[MAX_TOP_LAYER_PACKET_SIZE + 250];
967 net_addr_t from_addr;
969 while ( psnet_get( data, &from_addr ) > 0 ) ;
972 // if the passed string is a valid IP string
973 int psnet_is_valid_ip_string( char *ip_string, int allow_port )
976 struct hostent *host_ent;
979 // our addresses may have ports, so make local copy and remove port number
980 SDL_assert( strlen(ip_string) < 255 );
981 SDL_strlcpy(str, ip_string, SDL_arraysize(str));
982 c = strrchr(str, ':');
987 addr.s_addr = inet_addr(ip_string);
988 if ( addr.s_addr != INADDR_NONE ){
989 // make sure the ip string is a valid format string
990 if(psnet_is_valid_numeric_ip(ip_string)){
995 // try name resolution
996 host_ent = gethostbyname( ip_string );
1001 // valid host entry so return 1;
1006 // -------------------------------------------------------------------------------------------------------
1007 // PSNET 2 RELIABLE SOCKET FUNCTIONS
1011 int psnet_rel_ping_compare( const void *arg1, const void *arg2 )
1013 float *ping1 = (float *)arg1;
1014 float *ping2 = (float *)arg2;
1016 if(*ping1==*ping2) return 0;
1017 else if(*ping1>*ping2) return 1;
1018 else if(*ping1<*ping2) return -1;
1023 void psnet_rel_send_ack(struct sockaddr *raddr, unsigned int sig, ubyte link_type, float time_sent)
1026 reliable_header ack_header;
1028 if (link_type != NET_TCP) {
1033 ack_header.type = RNT_ACK;
1034 ack_header.data_len = sizeof(unsigned int);
1035 ack_header.send_time = INTEL_FLOAT( time_sent );
1036 sig_tmp = INTEL_INT( sig );
1037 memcpy(&ack_header.data,&sig_tmp,sizeof(unsigned int));
1039 if ( !Tcp_active ) {
1040 ml_string("No TCP in rel_send_ack()");
1044 SENDTO(Unreliable_socket, (char *)&ack_header, RELIABLE_PACKET_HEADER_ONLY_SIZE+sizeof(unsigned int), 0, raddr, sizeof(struct sockaddr), PSNET_TYPE_RELIABLE);
1047 // function to shutdown and close the given socket. It takes a couple of things into consideration
1048 // when closing, such as possibly reiniting reliable sockets if they are closed here.
1049 void psnet_rel_close_socket( PSNET_SOCKET_RELIABLE *sockp )
1051 reliable_header diss_conn_header;
1053 // if the socket is out of range
1054 if(*sockp>=MAXRELIABLESOCKETS)
1056 ml_printf("Invalid socket id passed to nw_NewCloseSocket() -- %d\n",*sockp);
1059 ml_printf("Closing socket %d\n",*sockp);
1061 // go through every buffer and "free it up(tm)"
1063 for(i=0;i<MAXNETBUFFERS;i++){
1064 if(Reliable_sockets[*sockp].rbuffers[i]){
1065 if(Reliable_sockets[*sockp].rbuffers[i] != NULL){
1066 free(Reliable_sockets[*sockp].rbuffers[i]);
1068 Reliable_sockets[*sockp].rbuffers[i] = NULL;
1069 Reliable_sockets[*sockp].rsequence[i] = 0;
1071 if(Reliable_sockets[*sockp].sbuffers[i]){
1072 if(Reliable_sockets[*sockp].sbuffers[i] != NULL){
1073 free(Reliable_sockets[*sockp].sbuffers[i]);
1075 Reliable_sockets[*sockp].sbuffers[i] = NULL;
1076 Reliable_sockets[*sockp].rsequence[i] = 0;
1080 // send a disconnect packet to the socket on the other end
1081 diss_conn_header.type = RNT_DISCONNECT;
1082 diss_conn_header.seq = CONNECTSEQ;
1083 diss_conn_header.data_len = 0;
1084 if(*sockp==Serverconn){
1085 Serverconn = 0xffffffff;
1088 if (Reliable_sockets[*sockp].connection_type == NET_TCP) {
1089 SDL_assert(Tcp_active);
1090 SENDTO(Unreliable_socket, (char *)&diss_conn_header,RELIABLE_PACKET_HEADER_ONLY_SIZE,0,&Reliable_sockets[*sockp].addr,sizeof(struct sockaddr), PSNET_TYPE_RELIABLE);
1092 ml_printf("Unknown protocol type in nw_CloseSocket()!\n");
1096 memset(&Reliable_sockets[*sockp],0,sizeof(reliable_socket));
1097 Reliable_sockets[*sockp].status = RNF_UNUSED;
1100 // function to check the status of the reliable socket and try to re-initialize it if necessary.
1101 // win95 seems to have trouble doing a reinit of the socket immediately after close, so this
1102 // function exists to check the status, and reinitialize if we need to
1103 int psnet_rel_check()
1108 // send data reliably
1109 int psnet_rel_send(PSNET_SOCKET_RELIABLE socketid, ubyte *data, int length, int np_index)
1113 reliable_socket *rsocket;
1115 if(socketid >= MAXRELIABLESOCKETS){
1116 ml_printf("Invalid socket id passed to psnet_rel_send() -- %d\n",socketid);
1120 SDL_assert( length < (int)(sizeof(reliable_header)) );
1123 rsocket=&Reliable_sockets[socketid];
1124 if(rsocket->status!=RNF_CONNECTED) {
1125 //We can't send because this isn't a connected reliable socket.
1126 ml_printf("Can't send packet because of status %d in nw_SendReliable(). socket = %d\n",rsocket->status,socketid);
1130 // Add the new packet to the sending list and send it.
1131 for(i=0;i<MAXNETBUFFERS;i++){
1132 if(NULL==rsocket->sbuffers[i]){
1133 reliable_header send_header;
1134 int send_this_packet=1;
1136 rsocket->send_len[i] = length;
1137 rsocket->sbuffers[i] = (reliable_net_sendbuffer *)malloc(sizeof(reliable_net_sendbuffer));
1139 memcpy(rsocket->sbuffers[i]->buffer,data,length);
1141 send_header.seq = INTEL_SHORT( rsocket->theirsequence );
1142 rsocket->ssequence[i] = rsocket->theirsequence;
1144 memcpy(send_header.data,data,length);
1145 send_header.data_len = INTEL_SHORT( (ushort)length );
1146 send_header.type = RNT_DATA;
1147 send_header.send_time = psnet_get_time();
1148 send_header.send_time = INTEL_FLOAT( send_header.send_time );
1149 // struct sockaddr_in * rsockaddr = (struct sockaddr_in *)&rsocket->addr;
1151 if (send_this_packet){
1152 if (rsocket->connection_type == NET_TCP) {
1153 SDL_assert(Tcp_active);
1154 multi_rate_add(np_index, "tcp(h)", RELIABLE_PACKET_HEADER_ONLY_SIZE+rsocket->send_len[i]);
1155 bytesout = SENDTO(Unreliable_socket, (char *)&send_header,RELIABLE_PACKET_HEADER_ONLY_SIZE+rsocket->send_len[i],0,&rsocket->addr,sizeof(struct sockaddr), PSNET_TYPE_RELIABLE);
1157 ml_printf("Unknown protocol type in nw_SendReliable()!\n");
1161 int error = WSAGetLastError();
1162 if((bytesout==SOCKET_ERROR)&&NETCALL_WOULDBLOCK(error)){
1163 //This will cause it to try to send again next frame. (or sooner)
1164 rsocket->timesent[i] = psnet_get_time()-(NETRETRYTIME*4);
1166 rsocket->timesent[i] = psnet_get_time();
1170 rsocket->theirsequence++;
1174 ml_printf("PSNET RELIABLE SEND BUFFER OVERRUN. socket = %d\n",socketid);
1180 // -1 socket not connected
1181 // 0 No packet ready to receive
1182 // >0 Buffer filled with the number of bytes recieved
1183 int psnet_rel_get(PSNET_SOCKET socketid, ubyte *buffer, int max_len)
1187 reliable_socket *rsocket = NULL;
1189 if(socketid >= MAXRELIABLESOCKETS){
1190 ml_printf("Invalid socket id passed to nw_NewReceiveReliable() -- %d\n",socketid);
1193 rsocket = &Reliable_sockets[socketid];
1194 if( (RNF_CONNECTED!=rsocket->status) && (RNF_LIMBO!=rsocket->status) ){
1195 ml_printf("Can't receive packet because it isn't connected in nw_ReceiveReliable(). socket = %d\n",socketid);
1198 //If the buffer position is the position we are waiting for, fill in
1199 //the buffer we received in the call to this function and return true
1201 for(i=0; i<MAXNETBUFFERS; i++){
1202 if((rsocket->rsequence[i] == rsocket->oursequence) && rsocket->rbuffers[i]){
1203 memcpy(buffer,rsocket->rbuffers[i]->buffer, rsocket->recv_len[i]);
1204 free(rsocket->rbuffers[i]);
1205 rsocket->rbuffers[i] = NULL;
1206 rsocket->rsequence[i] = 0;
1207 rsocket->oursequence++;
1208 return rsocket->recv_len[i];
1215 // process all active reliable sockets
1216 void psnet_rel_work()
1220 int max_len = NETBUFFERSIZE;
1222 struct timeval timeout;
1223 static reliable_header rcv_buff;
1224 static struct sockaddr rcv_addr;
1226 int addrlen = sizeof(struct sockaddr);
1230 PSNET_TOP_LAYER_PROCESS();
1232 // negotitate initial connection with the server
1233 reliable_socket *rsocket = NULL;
1234 if(Serverconn != 0xffffffff){
1235 //Check to see if we need to send a packet out.
1236 if((Reliable_sockets[Serverconn].status==RNF_LIMBO) && ((Serverconn != 0xffffffff) && fl_abs((psnet_get_time() - Last_sent_iamhere))>NETRETRYTIME) ){
1237 reliable_header conn_header;
1238 //Now send I_AM_HERE packet
1239 conn_header.type = RNT_I_AM_HERE;
1240 conn_header.seq = (ushort)(~CONNECTSEQ);
1241 conn_header.data_len = 0;
1242 Last_sent_iamhere = psnet_get_time();
1243 int ret = SOCKET_ERROR;
1245 if (Reliable_sockets[Serverconn].connection_type == NET_TCP) {
1246 SDL_assert(Tcp_active);
1247 ret = SENDTO(Unreliable_socket, (char *)&conn_header,RELIABLE_PACKET_HEADER_ONLY_SIZE,0,&Reliable_sockets[Serverconn].addr,sizeof(struct sockaddr), PSNET_TYPE_RELIABLE);
1250 int error = WSAGetLastError();
1251 if((ret == SOCKET_ERROR) && NETCALL_WOULDBLOCK(error)){
1252 Reliable_sockets[Serverconn].last_packet_sent = psnet_get_time()-NETRETRYTIME;
1254 Reliable_sockets[Serverconn].last_packet_sent = psnet_get_time();
1260 net_addr_t d3_rcv_addr;
1261 struct sockaddr_in *rcvaddr;
1262 int udp_has_data = 0;
1267 FD_SET(Unreliable_socket, &read_fds);
1269 udp_has_data = SELECT(Unreliable_socket+1,&read_fds,NULL,NULL,&timeout, PSNET_TYPE_RELIABLE);
1271 if (udp_has_data <= 0) {
1275 addrlen = sizeof(struct sockaddr);
1276 struct sockaddr_in *tcp_addr = (struct sockaddr_in *)&rcv_addr;
1277 memset(&d3_rcv_addr,0,sizeof(net_addr_t));
1278 memset(&rcv_addr,0,sizeof(struct sockaddr));
1279 bytesin = RECVFROM(Unreliable_socket, (char *)&rcv_buff,sizeof(reliable_header), 0, (struct sockaddr *)&rcv_addr,&addrlen, PSNET_TYPE_RELIABLE);
1280 rcv_buff.seq = INTEL_SHORT( rcv_buff.seq );
1281 rcv_buff.data_len = INTEL_SHORT( rcv_buff.data_len );
1282 rcv_buff.send_time = INTEL_FLOAT( rcv_buff.send_time );
1283 memcpy(d3_rcv_addr.addr, &tcp_addr->sin_addr.s_addr, 4);
1284 d3_rcv_addr.port = tcp_addr->sin_port;
1285 d3_rcv_addr.type = NET_TCP;
1286 link_type = NET_TCP;
1289 ml_printf("recvfrom returned an error! -- %d\n",WSAGetLastError());
1290 //Int3();//See Kevin
1294 //Someone wants to connect, so find a slot
1295 if(rcv_buff.type == RNT_REQ_CONN){
1296 for(i=1; i<MAXRELIABLESOCKETS; i++){
1297 if( (Reliable_sockets[i].status == RNF_CONNECTED) || (Reliable_sockets[i].status == RNF_LIMBO) ){
1298 //if(memcmp(&rcv_addr,&reliable_sockets[i].addr,sizeof(struct sockaddr))==0)
1299 if(memcmp(&d3_rcv_addr, &Reliable_sockets[i].net_addr, sizeof(net_addr_t)) == 0){
1300 //We already have a reliable link to this user, so we will ignore it...
1301 ml_printf("Received duplicate connection request. %d\n",i);
1302 //reliable_sockets[i].last_packet_received = timer_GetTime();
1303 psnet_rel_send_ack(&Reliable_sockets[i].addr, rcv_buff.seq, link_type, rcv_buff.send_time);
1304 //We will change this as a hack to prevent later code from hooking us up
1305 rcv_buff.type = 0xff;
1310 for(i=1; i<MAXRELIABLESOCKETS; i++){
1311 if(Reliable_sockets[i].status == RNF_UNUSED){
1312 //Add the new connection here.
1313 Reliable_sockets[i].connection_type=link_type;
1314 memcpy(&Reliable_sockets[i].net_addr, &d3_rcv_addr, sizeof(net_addr_t));
1315 memcpy(&Reliable_sockets[i].addr ,&rcv_addr, sizeof(struct sockaddr));
1316 Reliable_sockets[i].ping_pos = 0;
1317 Reliable_sockets[i].num_ping_samples = 0;
1318 Reliable_sockets[i].status = RNF_LIMBO;
1319 Reliable_sockets[i].last_packet_received = psnet_get_time();
1320 rsocket = &Reliable_sockets[i];
1321 rcvaddr = (struct sockaddr_in *)&rcv_addr;
1322 ml_printf("Connect from %s:%d\n", inet_ntoa(rcvaddr->sin_addr), htons(rcvaddr->sin_port));
1326 if(i==MAXRELIABLESOCKETS){
1327 //No more connections!
1328 ml_printf("Out of incoming reliable connection sockets\n");
1329 //Int3();//See Kevin
1332 psnet_rel_send_ack(&rsocket->addr, rcv_buff.seq, link_type, rcv_buff.send_time);
1335 //Find out if this is a packet from someone we were expecting a packet.
1336 rcvaddr = (struct sockaddr_in *)&rcv_addr;
1337 for(i=1; i<MAXRELIABLESOCKETS; i++){
1338 if(memcmp(&d3_rcv_addr,&Reliable_sockets[i].net_addr,sizeof(net_addr_t)) == 0){
1339 rsocket=&Reliable_sockets[i];
1343 if(rsocket == NULL){
1344 ml_printf("Received reliable data from unconnected client.\n");
1345 ml_printf("Received from %s:%d\n",inet_ntoa(rcvaddr->sin_addr),rcvaddr->sin_port);
1348 rsocket->last_packet_received = psnet_get_time();
1350 if(rsocket->status != RNF_CONNECTED){
1352 if(rsocket->status == RNF_LIMBO){
1353 //this is our connection to the server
1354 if(Serverconn != 0xffffffff){
1355 if(rcv_buff.type == RNT_ACK){
1356 ushort *acknum = (ushort *)&rcv_buff.data;
1357 if(*acknum == (~CONNECTSEQ & 0xffff)){
1358 rsocket->status = RNF_CONNECTED;
1359 ml_printf("Got ACK for IAMHERE!\n");
1363 } else if(rcv_buff.type == RNT_I_AM_HERE){
1364 rsocket->status = RNF_CONNECTING;
1365 psnet_rel_send_ack(&rsocket->addr, rcv_buff.seq, link_type, rcv_buff.send_time);
1366 ml_printf("Got IAMHERE!\n");
1370 if((rcv_buff.type == RNT_DATA) && (Serverconn != 0xffffffff)){
1371 rsocket->status = RNF_CONNECTED;
1373 rsocket->last_packet_received = psnet_get_time();
1377 //Update the last recv variable so we don't need a heartbeat
1378 rsocket->last_packet_received = psnet_get_time();
1380 if(rcv_buff.type == RNT_HEARTBEAT){
1383 if(rcv_buff.type == RNT_ACK){
1385 rsocket->num_ping_samples++;
1387 rsocket->pings[rsocket->ping_pos] = rsocket->last_packet_received - rcv_buff.send_time;
1388 if(rsocket->num_ping_samples >= MAX_PING_HISTORY){
1389 float sort_ping[MAX_PING_HISTORY];
1390 for(int a=0;a<MAX_PING_HISTORY;a++){
1391 sort_ping[a] = rsocket->pings[a];
1394 qsort(sort_ping ,MAX_PING_HISTORY, sizeof(float), psnet_rel_ping_compare);
1395 rsocket->mean_ping = ((sort_ping[MAX_PING_HISTORY/2]+sort_ping[(MAX_PING_HISTORY/2)+1]))/2;
1397 rsocket->ping_pos++;
1398 if(rsocket->ping_pos >= MAX_PING_HISTORY){
1399 rsocket->ping_pos=0;
1402 // if this is an ack for a send buffer on the socket, kill the send buffer. its done
1403 for(i=0; i<MAXNETBUFFERS; i++){
1404 unsigned int *acksig = (unsigned int *)&rcv_buff.data;
1406 if(rsocket->sbuffers[i]){
1407 if(rsocket->ssequence[i] == INTEL_INT(*acksig) ){
1408 SDL_assert(rsocket->sbuffers[i] != NULL);
1409 free(rsocket->sbuffers[i]);
1410 rsocket->sbuffers[i] = NULL;
1411 rsocket->ssequence[i] = 0;
1416 //remove that packet from the send buffer
1417 rsocket->last_packet_received = psnet_get_time();
1421 if(rcv_buff.type == RNT_DATA_COMP){
1423 //Decompress it. Put it back in the buffer. Process it as RNT_DATA
1424 rcv_buff.type = RNT_DATA;
1426 if(rcv_buff.type == RNT_DATA){
1427 //If the data is out of order by >= MAXNETBUFFERS-1 ignore that packet for now
1429 seqdelta = rcv_buff.seq - rsocket->oursequence;
1430 if(seqdelta<0) seqdelta = seqdelta*-1;
1431 if(seqdelta>=MAXNETBUFFERS - 1){
1432 ml_printf("Received reliable packet out of order!\n");
1433 //It's out of order, so we won't ack it, which will mean we will get it again soon.
1436 //else move data into the proper buffer position
1439 if(rsocket->oursequence < (0xffff - (MAXNETBUFFERS-1))){
1440 if (rsocket->oursequence > rcv_buff.seq){
1444 //Sequence is high, so prepare for wrap around
1445 if( ((unsigned short)(rcv_buff.seq + rsocket->oursequence)) > (MAXNETBUFFERS-1)){
1450 for(i=0; i<MAXNETBUFFERS; i++){
1451 if( (NULL != rsocket->rbuffers[i]) && (rsocket->rsequence[i] == rcv_buff.seq)){
1452 //Received duplicate packet!
1457 for(i=0; i<MAXNETBUFFERS; i++){
1458 if(NULL == rsocket->rbuffers[i]){
1459 if(rcv_buff.data_len>max_len){
1460 rsocket->recv_len[i] = rcv_buff.data_len;
1462 rsocket->recv_len[i] = rcv_buff.data_len;
1464 rsocket->rbuffers[i] = (reliable_net_rcvbuffer *)malloc(sizeof(reliable_net_rcvbuffer));
1465 memcpy(rsocket->rbuffers[i]->buffer,rcv_buff.data,rsocket->recv_len[i]);
1466 rsocket->rsequence[i] = rcv_buff.seq;
1471 psnet_rel_send_ack(&rsocket->addr, rcv_buff.seq, link_type, rcv_buff.send_time);
1475 } while (udp_has_data > 0);
1477 // Go through each reliable socket that is connected and do any needed work.
1478 for(j=0; j<MAXRELIABLESOCKETS; j++){
1479 rsocket=&Reliable_sockets[j];
1481 if(Serverconn == 0xffffffff){
1482 if(rsocket->status==RNF_LIMBO){
1483 if(fl_abs((psnet_get_time() - rsocket->last_packet_received))>Nettimeout){
1484 ml_printf("Reliable (but in limbo) socket (%d) timed out in nw_WorkReliable().\n",j);
1485 memset(rsocket,0,sizeof(reliable_socket));
1486 rsocket->status = RNF_UNUSED;//Won't work if this is an outgoing connection.
1490 if((rsocket->status == RNF_LIMBO) && (fl_abs((psnet_get_time() - First_sent_iamhere)) > Nettimeout)){
1491 rsocket->status = RNF_BROKEN;
1492 ml_printf("Reliable socket (%d) timed out in nw_WorkReliable().\n",j);
1496 if(rsocket->status == RNF_CONNECTED){
1497 float retry_packet_time;
1498 if((rsocket->mean_ping==0) || (rsocket->mean_ping > (NETRETRYTIME*4))){
1499 retry_packet_time = NETRETRYTIME;
1501 if(rsocket->mean_ping<MIN_NET_RETRYTIME) {
1502 retry_packet_time = (float)MIN_NET_RETRYTIME;
1504 retry_packet_time = ((float)(float)rsocket->mean_ping * (float)1.25);
1507 //Iterate through send buffers.
1508 for(i=0;i<MAXNETBUFFERS;i++){
1510 if((rsocket->sbuffers[i]) && (fl_abs((psnet_get_time() - rsocket->timesent[i])) >= retry_packet_time)) {
1511 reliable_header send_header;
1512 send_header.send_time = psnet_get_time();
1513 send_header.send_time = INTEL_FLOAT( send_header.send_time );
1514 send_header.seq = INTEL_SHORT( rsocket->ssequence[i] );
1515 memcpy(send_header.data,rsocket->sbuffers[i]->buffer,rsocket->send_len[i]);
1516 send_header.data_len = INTEL_SHORT( (ushort)rsocket->send_len[i] );
1517 send_header.type = RNT_DATA;
1518 if(rsocket->connection_type == NET_TCP){
1519 rcode = SENDTO(Unreliable_socket, (char *)&send_header,RELIABLE_PACKET_HEADER_ONLY_SIZE+rsocket->send_len[i],0,&rsocket->addr,sizeof(struct sockaddr), PSNET_TYPE_RELIABLE);
1521 int error = WSAGetLastError();
1522 if((rcode == SOCKET_ERROR) && NETCALL_WOULDBLOCK(error)){
1523 //The packet didn't get sent, flag it to try again next frame
1524 rsocket->timesent[i] = psnet_get_time()-(NETRETRYTIME*4);
1526 rsocket->last_packet_sent = psnet_get_time();
1527 rsocket->timesent[i] = psnet_get_time();
1533 if((rsocket->status == RNF_CONNECTED) && (fl_abs((psnet_get_time() - rsocket->last_packet_sent)) > NETHEARTBEATTIME)) {
1534 reliable_header send_header;
1535 send_header.send_time = psnet_get_time();
1536 send_header.send_time = INTEL_FLOAT( send_header.send_time );
1537 send_header.seq = 0;
1538 send_header.data_len = 0;
1539 send_header.type = RNT_HEARTBEAT;
1542 if(rsocket->connection_type == NET_TCP){
1543 rcode = SENDTO(Unreliable_socket, (char *)&send_header,RELIABLE_PACKET_HEADER_ONLY_SIZE,0,&rsocket->addr,sizeof(struct sockaddr), PSNET_TYPE_RELIABLE);
1545 int error = WSAGetLastError();
1546 if((rcode != SOCKET_ERROR) && NETCALL_WOULDBLOCK(error)){
1547 //It must have been sent
1548 rsocket->last_packet_sent = psnet_get_time();
1552 if((rsocket->status == RNF_CONNECTED) && (fl_abs((psnet_get_time() - rsocket->last_packet_received))>Nettimeout)){
1553 //This socket is hosed.....inform someone?
1554 ml_printf("Reliable Socket (%d) timed out in nw_WorkReliable().\n",j);
1555 rsocket->status = RNF_BROKEN;
1561 // get the status of a reliable socket, see RNF_* defines above
1562 int psnet_rel_get_status(PSNET_SOCKET_RELIABLE socketid)
1564 if(socketid >= MAXRELIABLESOCKETS){
1568 return Reliable_sockets[socketid].status;
1571 // function which checks the Listen_socket for possibly incoming requests to be connected.
1572 // returns 0 on error or nothing waiting. 1 if we should try to accept
1573 int psnet_rel_check_for_listen(net_addr_t *from_addr)
1575 struct sockaddr_in *ip_addr; // UDP/TCP socket structure
1579 for(i=1; i<MAXRELIABLESOCKETS; i++){
1580 if(Reliable_sockets[i].status == RNF_CONNECTING){
1581 Reliable_sockets[i].status = RNF_CONNECTED;
1582 //memcpy(from_addr,&reliable_sockets[i].addr,sizeof(struct sockaddr));
1583 ml_printf("New reliable connection in nw_CheckListenSocket().\n");
1585 if (Reliable_sockets[i].connection_type != NET_TCP) {
1589 ip_addr = (struct sockaddr_in *)&Reliable_sockets[i].addr;
1590 memset(from_addr, 0x00, sizeof(net_addr_t));
1591 from_addr->port = ntohs( ip_addr->sin_port );
1592 from_addr->type = NET_TCP;
1593 memcpy(from_addr->addr, &ip_addr->sin_addr.s_addr, 4);
1596 char dbg_output[50];
1597 nw_GetNumbersFromHostAddress(from_addr,dbg_output);
1598 mprintf((0,"Got address from: %s\n",dbg_output));
1603 return INVALID_SOCKET;
1606 // attacmpt to connect() to the server's tcp socket. socket parameter is simply assigned to the
1607 // Reliable_socket socket created in psnet_init
1608 void psnet_rel_connect_to_server(PSNET_SOCKET *socket, net_addr_t *server_addr)
1610 //Send out a RNT_REQ_CONN packet, and wait for it to be acked.
1611 struct sockaddr_in sockaddr; // UDP/TCP socket structure
1612 struct sockaddr *addr = NULL; // pointer to struct sockaddr to make coding easier
1613 struct sockaddr rcv_addr;
1617 // float time_sent_req = 0;
1618 float first_sent_req = 0;
1619 static reliable_header conn_header;
1620 static reliable_header ack_header;
1622 struct timeval timeout;
1625 *socket = INVALID_SOCKET;
1627 memcpy(iaddr, &server_addr->addr, 4);
1628 port = (ushort)(server_addr->port); // Talk to the server listen port
1630 conn_header.type = RNT_REQ_CONN;
1631 conn_header.seq = CONNECTSEQ;
1632 conn_header.data_len = 0;
1637 if (server_addr->type != NET_TCP) {
1641 SDL_assert(Tcp_active);
1643 //Flush out any left overs
1645 FD_SET(Unreliable_socket, &read_fds);
1646 while(SELECT(Unreliable_socket+1, &read_fds, NULL, NULL, &timeout, PSNET_TYPE_RELIABLE)){
1647 addrlen = sizeof(struct sockaddr);
1648 bytesin = RECVFROM(Unreliable_socket, (char *)&ack_header,sizeof(reliable_header),0,(struct sockaddr *)&rcv_addr,&addrlen, PSNET_TYPE_RELIABLE);
1650 //Int3();//See Kevin
1651 ml_printf("UDP recvfrom returned an error! -- %d\n",WSAGetLastError());
1656 FD_SET(Unreliable_socket, &read_fds);
1659 memset(&ack_header,0,sizeof(reliable_header));
1660 SOCKET typeless_sock = 0;
1661 net_addr_t d3_rcv_addr;
1662 memset(&d3_rcv_addr,0,sizeof(net_addr_t));
1665 sockaddr.sin_family = AF_INET;
1666 memcpy(&sockaddr.sin_addr.s_addr, iaddr, 4);
1667 sockaddr.sin_port = htons(port);
1668 addr = (struct sockaddr *)&sockaddr;
1669 if( SOCKET_ERROR == SENDTO(Unreliable_socket, (char *)&conn_header,RELIABLE_PACKET_HEADER_ONLY_SIZE,0,addr,sizeof(struct sockaddr), PSNET_TYPE_RELIABLE) ){
1670 ml_printf("Unable to send UDP packet in nw_ConnectToServer()! -- %d\n",WSAGetLastError());
1673 memcpy(d3_rcv_addr.addr, &sockaddr.sin_addr.s_addr, 4);
1674 d3_rcv_addr.port = sockaddr.sin_port;
1675 d3_rcv_addr.type = NET_TCP;
1676 typeless_sock = Unreliable_socket;
1679 first_sent_req = psnet_get_time();
1680 // time_sent_req = psnet_get_time();
1682 //Wait until we get a response from the server or we timeout
1685 PSNET_TOP_LAYER_PROCESS();
1688 FD_SET(typeless_sock, &read_fds);
1689 if(SELECT(typeless_sock+1, &read_fds, NULL,NULL,&timeout, PSNET_TYPE_RELIABLE)){
1690 ml_string("selected() in psnet_rel_connect_to_server()");
1692 addrlen = sizeof(struct sockaddr);
1693 bytesin = RECVFROM(typeless_sock,(char *)&ack_header,sizeof(reliable_header),0,(struct sockaddr *)&rcv_addr,&addrlen, PSNET_TYPE_RELIABLE);
1695 ml_printf("recvfrom returned an error! -- %d\n",WSAGetLastError());
1700 ml_string("received data after select in psnet_rel_connect_to_server()");
1702 ml_string("about to check ack_header.type");
1703 if(ack_header.type == RNT_ACK){
1704 short *acknum = (short *)&ack_header.data;
1705 if(*acknum == CONNECTSEQ){
1706 for(i=1; i<MAXRELIABLESOCKETS; i++){
1707 if(Reliable_sockets[i].status==RNF_UNUSED){
1708 //Add the new connection here.
1709 memset(&Reliable_sockets[i],0,sizeof(reliable_socket));
1710 Reliable_sockets[i].connection_type = (ubyte)server_addr->type;
1711 memcpy(&Reliable_sockets[i].net_addr,&d3_rcv_addr,sizeof(net_addr_t));
1712 Reliable_sockets[i].last_packet_received = psnet_get_time();
1713 memcpy(&Reliable_sockets[i].addr,&rcv_addr,sizeof(struct sockaddr));
1714 Reliable_sockets[i].status = RNF_LIMBO;
1716 ml_printf("Succesfully connected to server in nw_ConnectToServer().\n");
1717 //Now send I_AM_HERE packet
1718 conn_header.type = RNT_I_AM_HERE;
1719 conn_header.seq = (ushort)(~CONNECTSEQ);
1720 conn_header.data_len = 0;
1722 First_sent_iamhere = psnet_get_time();
1723 Last_sent_iamhere = psnet_get_time();
1724 int rcode = SENDTO(typeless_sock,(char *)&conn_header,RELIABLE_PACKET_HEADER_ONLY_SIZE,0,addr,sizeof(struct sockaddr), PSNET_TYPE_RELIABLE);
1725 if(rcode == SOCKET_ERROR){
1726 *socket = INVALID_SOCKET;
1727 Reliable_sockets[i].status = RNF_UNUSED;
1728 memset(&Reliable_sockets[i],0,sizeof(reliable_socket));
1729 ml_printf("Unable to send packet in nw_ConnectToServer()\n");
1732 Reliable_sockets[i].last_packet_sent = psnet_get_time();
1734 f = psnet_get_time();
1735 while((fl_abs((psnet_get_time() - f))<2) && (Reliable_sockets[i].status != RNF_CONNECTING)){
1742 ml_printf("Out of reliable socket space in nw_ConnectToServer().\n");
1744 } else ml_printf("Received out of sequence ACK in nw_ConnectToServer().\n");
1745 } else ml_printf("Received something that isn't an ACK in nw_ConnectToServer().\n");
1746 } else ml_printf("Received 0 bytes from recvfrom() in nw_ConnectToServer().\n");
1749 if((psnet_get_time()-time_sent_req)>2)
1751 ml_printf("Resending connect request.\n");
1752 int ret = SENDTO(typeless_sock,(char *)&conn_header,RELIABLE_PACKET_HEADER_ONLY_SIZE,0,addr,sizeof(struct sockaddr), PSNET_TYPE_RELIABLE);
1753 if(ret != SOCKET_ERROR){
1754 time_sent_req = psnet_get_time();
1756 ml_printf("Error sending connection request! -- %d\n",WSAGetLastError() );
1761 } while(fl_abs((psnet_get_time() - first_sent_req)) < RELIABLE_CONNECT_TIME);
1764 // returns the ip address of this computer
1766 int psnet_rel_get_ip()
1770 struct sockaddr_in local_address;
1773 // Get the local host name
1774 memset(&local_address, 0, sizeof(local_address));
1775 ret = gethostname(local, 255 );
1776 if (ret != SOCKET_ERROR ){
1777 // Resolve host name for local address
1778 hostent = gethostbyname((char *)local);
1780 local_address.sin_addr.s_addr = *((u_long FAR *)(hostent->h_addr));
1783 ml_string("SOCKET_ERROR in psnet_rel_get_ip()!");
1785 ml_printf(%s:%d\n", inet_ntoa(rcvaddr->sin_addr), htons(rcvaddr->sin_port)
1786 return local_address.sin_addr.s_addr;
1790 // returns the ip address of this computer
1793 struct sockaddr_in local_address;
1795 if(Psnet_connection == NETWORK_CONNECTION_DIALUP){
1796 local_address.sin_addr.s_addr = psnet_ras_status();
1797 if(local_address.sin_addr.s_addr == INADDR_NONE){
1798 local_address.sin_addr.s_addr = INADDR_ANY;
1801 // Init local address to zero
1802 local_address.sin_addr.s_addr = INADDR_ANY;
1805 // NOTE: for memeory checkers, do NOT try to free this
1806 ml_printf("psnet_get_ip() reports IP : %s\n", inet_ntoa(local_address.sin_addr));
1808 return local_address.sin_addr.s_addr;
1811 // initialize reliable sockets
1812 int psnet_init_rel_tcp(int port, int should_listen)
1815 struct sockaddr_in sockaddr;
1817 sockaddr.sin_port = htons((ushort)port);
1818 sockaddr.sin_family = AF_INET;
1820 ml_printf("Setting up reliable sockets.\n");
1822 my_ip = psnet_get_ip();
1824 memcpy(&sockaddr.sin_addr.s_addr, &my_ip, sizeof(uint));
1826 Reliable_UDP_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP );
1827 if(INVALID_SOCKET == Reliable_UDP_socket){
1828 ml_printf("Unable to create reliable UDP socket -- %d\n", WSAGetLastError() );
1831 } else if(bind(Reliable_UDP_socket,(struct sockaddr *)&sockaddr,sizeof(struct sockaddr))!=0){
1832 ml_printf("Unable to bind reliable socket -- %d\n", WSAGetLastError() );
1837 // make any reliable sockets which we create that aren't listening non-blocking sockets
1842 error = ioctlsocket( Reliable_UDP_socket, FIONBIO, &arg );
1843 if ( error == SOCKET_ERROR ) {
1844 ml_printf("Unable to make reliable UDP socket non-blocking -- %d\n", WSAGetLastError() );
1854 void psnet_rel_close()
1857 PSNET_SOCKET_RELIABLE sock;
1860 for(idx=0; idx<MAXRELIABLESOCKETS; idx++){
1861 if(Reliable_sockets[idx].status != RNF_UNUSED){
1863 psnet_rel_close_socket(&sock);
1868 // ------------------------------------------------------------------------------------------------------
1869 // PACKET BUFFERING FUNCTIONS
1872 // initialize the buffering system
1873 void psnet_buffer_init(network_packet_buffer_list *l)
1877 // blast the buffer clean
1878 memset(l->psnet_buffers, 0, sizeof(network_packet_buffer) * MAX_PACKET_BUFFERS);
1880 // set all buffer sequence #'s to -1
1881 for(idx=0;idx<MAX_PACKET_BUFFERS;idx++){
1882 l->psnet_buffers[idx].sequence_number = -1;
1885 // initialize the sequence #
1886 l->psnet_seq_number = 0;
1887 l->psnet_lowest_id = -1;
1888 l->psnet_highest_id = -1;
1891 // buffer a packet (maintain order!)
1892 void psnet_buffer_packet(network_packet_buffer_list *l, ubyte *data, int length, net_addr_t *from)
1897 // find the first empty packet
1898 for(idx=0;idx<MAX_PACKET_BUFFERS;idx++){
1899 if(l->psnet_buffers[idx].sequence_number == -1){
1905 // if we didn't find the buffer, report an overrun
1907 ml_printf("WARNING - Buffer overrun in psnet\n");
1910 memcpy(l->psnet_buffers[idx].data, data, length);
1911 l->psnet_buffers[idx].len = length;
1912 memcpy(&l->psnet_buffers[idx].from_addr, from, sizeof(net_addr_t));
1913 l->psnet_buffers[idx].sequence_number = l->psnet_seq_number;
1915 // keep track of the highest id#
1916 l->psnet_highest_id = l->psnet_seq_number++;
1918 // set the lowest id# for the first time
1919 if(l->psnet_lowest_id == -1){
1920 l->psnet_lowest_id = l->psnet_highest_id;
1925 // get the index of the next packet in order!
1926 int psnet_buffer_get_next(network_packet_buffer_list *l, ubyte *data, int *length, net_addr_t *from)
1930 // if there are no buffers, do nothing
1931 if((l->psnet_lowest_id == -1) || (l->psnet_lowest_id > l->psnet_highest_id)){
1935 // search until we find the lowest packet index id#
1936 for(idx=0;idx<MAX_PACKET_BUFFERS;idx++){
1937 // if we found the buffer
1938 if(l->psnet_buffers[idx].sequence_number == l->psnet_lowest_id){
1943 // at this point, we should _always_ have found the buffer
1944 if (idx == MAX_PACKET_BUFFERS) {
1949 // copy out the buffer data
1950 memcpy(data, l->psnet_buffers[idx].data, l->psnet_buffers[idx].len);
1951 *length = l->psnet_buffers[idx].len;
1952 memcpy(from, &l->psnet_buffers[idx].from_addr, sizeof(net_addr_t));
1954 // now we need to cleanup the packet list
1956 // mark the buffer as free
1957 l->psnet_buffers[idx].sequence_number = -1;
1958 l->psnet_lowest_id++;
1963 // -------------------------------------------------------------------------------------------------------
1964 // PSNET 2 FORWARD DEFINITIONS
1967 // if the string is a legally formatted ip string
1968 int psnet_is_valid_numeric_ip(char *ip)
1972 int val1,val2,val3,val4;
1974 // get the first ip value
1975 SDL_strlcpy(copy, ip, SDL_arraysize(copy));
1976 token = strtok(copy,".");
1980 // get the value of the token
1982 if((val1 < 0) || (val1 > 255)){
1988 token = strtok(NULL,".");
1992 // get the value of the token
1994 if((val2 < 0) || (val2 > 255)){
2000 token = strtok(NULL,".");
2004 // get the value of the token
2006 if((val3 < 0) || (val3 > 255)){
2012 token = strtok(NULL,"");
2016 // get the value of the token
2018 if((val4 < 0) || (val4 > 255)){
2023 // make sure he hasn't entered all 0's
2024 if((val1 == 0) && (val2 == 0) && (val3 == 0) && (val4 == 0)){
2032 // function called from high level FreeSpace code to determine the status of the networking
2033 // code returns one of a handful of macros
2035 DWORD (__stdcall *pRasEnumConnections)(LPRASCONN lprasconn, LPDWORD lpcb, LPDWORD lpcConnections) = NULL;
2036 DWORD (__stdcall *pRasGetConnectStatus)(HRASCONN hrasconn, LPRASCONNSTATUS lprasconnstatus ) = NULL;
2037 DWORD (__stdcall *pRasGetProjectionInfo)(HRASCONN hrasconn, RASPROJECTION rasprojection, LPVOID lpprojection, LPDWORD lpcb ) = NULL;
2039 // functions to get the status of a RAS connection
2040 unsigned int psnet_ras_status()
2043 unsigned long size, num_connections, i;
2044 RASCONN rasbuffer[25];
2045 HINSTANCE ras_handle;
2046 unsigned long rasip=0;
2047 RASPPPIP projection;
2048 // int Ras_connected;
2052 // first, call a LoadLibrary to load the RAS api
2053 ras_handle = LoadLibrary( (LPCWSTR)"rasapi32.dll" );
2054 if ( ras_handle == NULL ) {
2058 pRasEnumConnections = (DWORD (__stdcall *)(LPRASCONN, LPDWORD, LPDWORD))GetProcAddress(ras_handle, "RasEnumConnectionsA");
2059 if (!pRasEnumConnections) {
2060 FreeLibrary( ras_handle );
2063 pRasGetConnectStatus = (DWORD (__stdcall *)(HRASCONN, LPRASCONNSTATUS))GetProcAddress(ras_handle, "RasGetConnectStatusA");
2064 if (!pRasGetConnectStatus) {
2065 FreeLibrary( ras_handle );
2068 pRasGetProjectionInfo = (DWORD (__stdcall *)(HRASCONN, RASPROJECTION, LPVOID, LPDWORD))GetProcAddress(ras_handle, "RasGetProjectionInfoA");
2069 if (!pRasGetProjectionInfo) {
2070 FreeLibrary( ras_handle );
2074 size = sizeof(rasbuffer);
2075 rasbuffer[0].dwSize = sizeof(RASCONN);
2077 rval = pRasEnumConnections( rasbuffer, &size, &num_connections );
2079 FreeLibrary( ras_handle );
2083 // JAS: My computer gets to this point, but I have no RAS connections,
2085 if ( num_connections < 1 ) {
2086 ml_string("Found no RAS connections");
2087 FreeLibrary( ras_handle );
2091 ml_printf("Found %d connections", num_connections);
2093 for (i = 0; i < num_connections; i++ ) {
2094 RASCONNSTATUS status;
2097 ml_printf("Connection %d:", i);
2098 ml_printf("Entry Name: %s", rasbuffer[i].szEntryName);
2099 ml_printf("Device Type: %s", rasbuffer[i].szDeviceType);
2100 ml_printf("Device Name: %s", rasbuffer[i].szDeviceName);
2102 // get the connection status
2103 status.dwSize = sizeof(RASCONNSTATUS);
2104 rval = pRasGetConnectStatus(rasbuffer[i].hrasconn, &status);
2106 FreeLibrary( ras_handle );
2110 // get the projection informatiom
2111 size = sizeof(projection);
2112 projection.dwSize = size;
2113 rval = pRasGetProjectionInfo(rasbuffer[i].hrasconn, RASP_PppIp, &projection, &size );
2115 FreeLibrary( ras_handle );
2119 ml_printf("IP Address: %s", projection.szIpAddress);
2124 FreeLibrary( ras_handle );
2125 rasip = inet_addr((const char *)projection.szIpAddress);
2126 if(rasip==INADDR_NONE){
2130 //The ip of the RAS connection
2134 unsigned int psnet_ras_status()
2142 // functions to get the status of a RAS connection
2144 void psnet_ras_status()
2147 unsigned long size, num_connections, i;
2148 RASCONN rasbuffer[25];
2149 HINSTANCE ras_handle;
2153 // first, call a LoadLibrary to load the RAS api
2154 ras_handle = LoadLibrary( NOX("rasapi32.dll") );
2155 if ( ras_handle == NULL ) {
2159 pRasEnumConnections = (DWORD (__stdcall *)(LPRASCONN, LPDWORD, LPDWORD))GetProcAddress(ras_handle, NOX("RasEnumConnectionsA"));
2160 if (!pRasEnumConnections) {
2161 FreeLibrary( ras_handle );
2164 pRasGetConnectStatus = (DWORD (__stdcall *)(HRASCONN, LPRASCONNSTATUS))GetProcAddress(ras_handle, NOX("RasGetConnectStatusA"));
2165 if (!pRasGetConnectStatus) {
2166 FreeLibrary( ras_handle );
2169 pRasGetProjectionInfo = (DWORD (__stdcall *)(HRASCONN, RASPROJECTION, LPVOID, LPDWORD))GetProcAddress(ras_handle, NOX("RasGetProjectionInfoA"));
2170 if (!pRasGetProjectionInfo) {
2171 FreeLibrary( ras_handle );
2175 size = sizeof(rasbuffer);
2176 rasbuffer[0].dwSize = sizeof(RASCONN);
2178 rval = pRasEnumConnections( rasbuffer, &size, &num_connections );
2180 FreeLibrary( ras_handle );
2184 // JAS: My computer gets to this point, but I have no RAS connections,
2186 if ( num_connections < 1 ) {
2187 ml_printf("Found no connections\n" );
2188 FreeLibrary( ras_handle );
2192 ml_printf("Found %d connections\n", num_connections);
2194 for (i = 0; i < num_connections; i++ ) {
2195 RASCONNSTATUS status;
2196 RASPPPIP projection;
2199 ml_printf("Connection %d:\n", i);
2200 ml_printf("Entry Name: %s\n", rasbuffer[i].szEntryName);
2201 ml_printf("Device Type: %s\n", rasbuffer[i].szDeviceType);
2202 ml_printf("Device Name: %s\n", rasbuffer[i].szDeviceName);
2204 // get the connection status
2205 status.dwSize = sizeof(RASCONNSTATUS);
2206 rval = pRasGetConnectStatus(rasbuffer[i].hrasconn, &status);
2208 FreeLibrary( ras_handle );
2212 ml_printf("\tStatus: %s\n", (status.rasconnstate==RASCS_Connected)?"Connected":"Not Connected");
2214 // get the projection informatiom
2215 size = sizeof(projection);
2216 projection.dwSize = size;
2217 rval = pRasGetProjectionInfo(rasbuffer[i].hrasconn, RASP_PppIp, &projection, &size );
2219 FreeLibrary( ras_handle );
2223 ml_printf("IP Address: %s", projection.szIpAddress));
2228 FreeLibrary( ras_handle );
2232 // set some options on a socket
2233 void psnet_socket_options( SOCKET sock )
2235 int broadcast;//, ret;
2237 int cursize, cursizesize, bufsize;
2239 socklen_t cursize, cursizesize, bufsize;
2242 // Set the mode of the socket to allow broadcasting
2244 if(setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char *)&broadcast, sizeof(broadcast) )){
2251 // setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&broadcast, sizeof(broadcast) );
2253 // try and increase the size of my receive buffer
2254 bufsize = MAX_RECEIVE_BUFSIZE;
2256 // set the current size of the receive buffer
2257 cursizesize = sizeof(int);
2258 getsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *)&cursize, &cursizesize);
2259 // for ( trysize = bufsize; trysize >= cursize; trysize >>= 1 ) {
2260 /*ret =*/ setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *)&bufsize, sizeof(bufsize));
2261 /*if ( ret == SOCKET_ERROR ) {
2264 wserr = WSAGetLastError();
2265 // if ( (wserr == WSAENOPROTOOPT) || (wserr == WSAEINVAL) )
2269 getsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *)&cursize, &cursizesize);
2270 ml_printf("Receive buffer set to %d\n", cursize);
2272 // set the current size of the send buffer
2273 cursizesize = sizeof(int);
2274 getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *)&cursize, &cursizesize);
2275 // for ( trysize = bufsize; trysize >= cursize; trysize >>= 1 ) {
2276 /*ret =*/ setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *)&bufsize, sizeof(bufsize));
2277 /*if ( ret == SOCKET_ERROR ) {
2280 wserr = WSAGetLastError();
2281 // if ( (wserr == WSAENOPROTOOPT) || (wserr == WSAEINVAL) ){
2285 getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *)&cursize, &cursizesize);
2286 ml_printf("Send buffer set to %d\n", cursize);
2289 // initialize tcp socket
2290 int psnet_init_tcp()
2292 struct sockaddr_in sockaddr;
2294 TCP_socket = INVALID_SOCKET;
2296 TCP_socket = socket( AF_INET, SOCK_DGRAM, 0 );
2297 if ( TCP_socket == (int)INVALID_SOCKET ) {
2298 Tcp_failure_code = WSAGetLastError();
2299 ml_printf("Error on TCP startup %d\n", Tcp_failure_code);
2304 memset(&sockaddr,0,sizeof(struct sockaddr_in));
2305 sockaddr.sin_family = AF_INET;
2306 sockaddr.sin_addr.s_addr = psnet_get_ip();
2307 sockaddr.sin_port = htons( Psnet_default_port );
2308 if ( bind(TCP_socket, (struct sockaddr*)&sockaddr, sizeof (sockaddr)) == SOCKET_ERROR) {
2309 Tcp_failure_code = WSAGetLastError();
2310 ml_printf("Couldn't bind TCP socket (%d)! Invalidating TCP\n", Tcp_failure_code );
2314 // set socket options
2315 psnet_socket_options( TCP_socket );
2316 Tcp_can_broadcast = Can_broadcast;
2322 // get time in seconds
2323 float psnet_get_time()
2325 return (float)timer_get_milliseconds() / 1000.0f;
2328 // mark a socket as having received data
2329 void psnet_mark_received(PSNET_SOCKET_RELIABLE socket)
2332 if((socket == 0xffffffff) || (socket >= MAXRELIABLESOCKETS)){
2337 Reliable_sockets[socket].last_packet_received = psnet_get_time();