6 # include <sys/socket.h>
8 # include <netinet/in.h>
11 # define INVALID_SOCKET -1
12 # define SOCKET_ERROR -1
20 int open_connection(char* name
)
22 struct hostent
* hostInfo
;
24 struct sockaddr_in address
;
27 WORD wVersionRequested
;
29 wVersionRequested
= MAKEWORD(1, 1);
30 if(WSAStartup(wVersionRequested
, &wsaData
) != 0)
32 fprintf(stderr
, "Could not open winsock.\n");
37 sock
= socket(PF_INET
, SOCK_STREAM
, 0);
38 if(sock
== SOCKET_ERROR
)
40 fprintf(stderr
, "Could not make a socket.\n");
44 hostInfo
= gethostbyname(name
);
47 fprintf(stderr
, "Couldn't find host %s.\n", name
);
51 memcpy(&hostAddress
, hostInfo
->h_addr
, hostInfo
->h_length
);
53 address
.sin_addr
.s_addr
= hostAddress
;
54 address
.sin_port
= htons(52530);
55 address
.sin_family
= AF_INET
;
56 memset(address
.sin_zero
, '\0', sizeof(address
.sin_zero
));
58 if(connect(sock
, (struct sockaddr
*)&address
, sizeof(address
)) == SOCKET_ERROR
)
60 fprintf(stderr
, "Could not connect to applet server. Check if the applet server is running.\n");
65 fcntl(sock
, F_SETFL
, O_NONBLOCK
); // set the socket as non-blocking
70 int send_command(int bytes
, ...)
76 unsigned char* data
= malloc(bytes
+ 1);
77 for(i
=0; i
<bytes
; i
++)
78 data
[i
] = (unsigned char)va_arg(ap
, int);
82 int sent
= send(sock
, data
, bytes
+1, 0);
89 int send_without_eof(int bytes
, ...)
95 unsigned char* data
= malloc(bytes
+ 1);
96 for(i
=0; i
<bytes
; i
++)
97 data
[i
] = (unsigned char)va_arg(ap
, int);
100 int sent
= send(sock
, data
, bytes
, 0);
107 int send_bytes(size_t bytes
, unsigned char* c
)
109 unsigned char eof
[1] = { 0xff };
111 send(sock
, c
, bytes
, 0);
112 int sent
= send(sock
, eof
, 1, 0);
119 unsigned char* read_data(int length
)
121 unsigned char* c
= malloc(length
);
122 int i
= recv(sock
, c
, length
, 0);
130 fprintf(stderr
, "Connection lost.\n");
137 void close_connection()
142 if(close(sock
) == SOCKET_ERROR
)
143 fprintf(stderr
, "Could not close socket\n");