Themes
[xdock.git] / src / lib / network.c
blobaf30bb7cde7a1816c6de254171e4de06cee1af01
1 #include "network.h"
3 #ifdef WIN32
4 # include <winsock.h>
5 #else
6 # include <sys/socket.h>
7 # include <sys/un.h>
8 # include <netinet/in.h>
9 # include <netdb.h>
10 # include <fcntl.h>
11 # define INVALID_SOCKET -1
12 # define SOCKET_ERROR -1
13 #endif
14 #include <stdio.h>
15 #include <stdarg.h>
16 #include <stdlib.h>
18 int sock;
20 int open_connection(char* name)
22 struct hostent* hostInfo;
23 long hostAddress;
24 struct sockaddr_in address;
26 #ifdef WIN32
27 WORD wVersionRequested;
28 WSADATA wsaData;
29 wVersionRequested = MAKEWORD(1, 1);
30 if(WSAStartup(wVersionRequested, &wsaData) != 0)
32 fprintf(stderr, "Could not open winsock.\n");
33 return 0;
35 #endif
37 sock = socket(PF_INET, SOCK_STREAM, 0);
38 if(sock == SOCKET_ERROR)
40 fprintf(stderr, "Could not make a socket.\n");
41 return 0;
44 hostInfo = gethostbyname(name);
45 if(!hostInfo)
47 fprintf(stderr, "Couldn't find host %s.\n", name);
48 return 0;
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");
61 return 0;
63 else
65 fcntl(sock, F_SETFL, O_NONBLOCK); // set the socket as non-blocking
66 return -1;
70 int send_command(int bytes, ...)
72 va_list(ap);
73 int i;
75 va_start(ap, bytes);
76 unsigned char* data = malloc(bytes + 1);
77 for(i=0; i<bytes; i++)
78 data[i] = (unsigned char)va_arg(ap, int);
79 data[bytes] = 0xff;
80 va_end(ap);
82 int sent = send(sock, data, bytes+1, 0);
83 if(sent == -1)
84 return 0;
85 else
86 return -1;
89 int send_without_eof(int bytes, ...)
91 va_list(ap);
92 int i;
94 va_start(ap, bytes);
95 unsigned char* data = malloc(bytes + 1);
96 for(i=0; i<bytes; i++)
97 data[i] = (unsigned char)va_arg(ap, int);
98 va_end(ap);
100 int sent = send(sock, data, bytes, 0);
101 if(sent == -1)
102 return 0;
103 else
104 return -1;
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);
113 if(sent == -1)
114 return 0;
115 else
116 return -1;
119 unsigned char* read_data(int length)
121 unsigned char* c = malloc(length);
122 int i = recv(sock, c, length, 0);
123 if(i == -1)
125 free(c);;
126 return NULL;
128 else if(i == 0)
130 fprintf(stderr, "Connection lost.\n");
131 exit(1);
133 else
134 return c;
137 void close_connection()
139 #ifdef WIN32
140 closesocket(sock);
141 #else
142 if(close(sock) == SOCKET_ERROR)
143 fprintf(stderr, "Could not close socket\n");
144 #endif