#include "sillybot.h"
#include "socket.h"
int connectSock(char *server,int port) {
struct hostent *hp;
struct sockaddr_in sin;
int s;
if ((hp=gethostbyname(server))==NULL) {
printf("conn() -- ERROR: Unknown hostname (%s)\n", server);
exit(1);
}
if ((s=socket(AF_INET, SOCK_STREAM, 0)) < 0) {
printf("conn() -- ERROR: Client: Socket\n");
}
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
bcopy(hp->h_addr, &sin.sin_addr, hp->h_length);
if (connect(s,(struct sockaddr *)&sin, sizeof(sin)) < 0) {
printf("conn() -- ERROR: Client: Connect\n");
exit(1);
}
return s;
}
int sendSock(int socket, const char *fmt, ...) {
char *string;
va_list args;
string = malloc(MAXBUFLENGTH);
va_start(args, fmt);
vsnprintf(string, MAXBUFLENGTH, fmt, args);
va_end(args);
send(socket, string, strlen(string), 0);
return(strlen(string));
}
int readSock(int s,char *buf) {
char inc;
int bufnum, n;
fd_set fds;
struct timeval wait;
u_long brx = 0;
bufnum = 0;
if (s==-1) {
return(-1);
}
wait.tv_sec = 0L;
wait.tv_usec = 2500L;
FD_ZERO(&fds);
FD_SET(s, &fds);
if (select(s+1, &fds, NULL, 0, &wait) > 0) {
do {
n = read(s, &inc, 1);
if (n == 0) {
return -1;
}
if (bufnum < BUFFER_SIZE - 1 ) {
buf[bufnum++] = inc;
}
} while (inc != '\n'); {
buf[bufnum] = '\0';
}
brx += bufnum;
return bufnum;
}
return 0;
}