int main (void) { int rc; char buf[100] = { 0 }; setup(); sock = socket (AF_INET, SOCK_STREAM, 0); assert (sock >= 0); sock_name.sin_family = AF_INET; sock_name.sin_port = htons (test_port); sock_name.sin_addr.s_addr = htonl (INADDR_LOOPBACK); assert (bind(sock, (struct sockaddr*)&sock_name, sizeof(sock_name)) != -1); sock_name.sin_family = AF_INET; sock_name.sin_port = htons (test_port); sock_name.sin_addr.s_addr = htonl (INADDR_LOOPBACK); assert (connect(sock, (struct sockaddr*)&sock_name, sizeof(sock_name)) != -1); do { rc = sock_select (sock); } while (rc < 0); assert (write_s(sock,"HELO",4) != -1); assert (read_s (sock,buf,sizeof(buf)) != -1); printf ("buf = `%s'\n", buf); assert (write_s(sock,"QUIT",4) != -1); assert (close_s(sock) != -1); sock = -1; return (0); }
ssize_t sock_recv(int *s, char *buf, int len, int timout_ms) { ssize_t rc; if(sock_select(s, timout_ms, READ) <= 0) return SOCK_TIMEOUT; rc = recv(*s, buf, len, 0); return rc; }
int sock_recv(int *s, char *buf, int len, int msec) { int rc; if(sock_select(s, msec, READ) <= 0) return SOCK_TIMEOUT; rc = recv(*s, buf, len, 0); return rc; }
int sock_connect(const char *addr, short port, int timout_ms) { int sock; struct hostent *host_ptr; struct sockaddr_in hostname; #ifdef _WIN32 WSADATA wsa; WSAStartup(MAKEWORD(2,2),&wsa); #endif sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if(sock == -1) return SOCK_ERR_CREATE; host_ptr = gethostbyname(addr); if(host_ptr == NULL) { host_ptr = gethostbyaddr(addr, (unsigned) strlen(addr), AF_INET); if(host_ptr == NULL) { sock_close(&sock); return SOCK_ERR_RESOLVE; } } hostname.sin_family = AF_INET; hostname.sin_port = htons(port); memcpy(&hostname.sin_addr, host_ptr->h_addr, host_ptr->h_length); sock_nonblock(&sock); connect(sock, (struct sockaddr*) &hostname, sizeof(hostname)); if(sock_select(&sock, timout_ms, WRITE) <= 0) { sock_close(&sock); return SOCK_TIMEOUT; } if(!sock_isvalid(&sock)) { sock_close(&sock); return SOCK_INVALID; } return sock; }
int sock_send(int *s, char *buf, int len, int msec) { int rc; int sent = 0; int error; while(sent < len) { rc = sock_select(s, 60000, WRITE); //check if socket is connected if(rc == 0) { printf("select returned 0\n"); fflush(stdout); return SOCK_TIMEOUT; } if(rc == -1) { printf("select returned -1\n"); fflush(stdout); return SOCK_TIMEOUT; } if((rc = send(*s, buf+sent, len-sent, 0)) < 0) { error = errno; if(error != EWOULDBLOCK) { printf("send errno: %d\n", error); fflush(stdout); return SOCK_TIMEOUT; } rc = 0; } sent += rc; } return sent; }
int sock_send(int *s, const char *buf, size_t len, int timout_ms) { ssize_t rc; int sent = 0; int error; while(sent < len) { rc = sock_select(s, 10000, WRITE); //check if socket is connected if(rc == 0) { fflush(stdout); return SOCK_TIMEOUT; } if(rc == -1) { fflush(stdout); return SOCK_TIMEOUT; } if((rc = send(*s, buf+sent, len-sent, 0)) < 0) { error = errno; if(error != EWOULDBLOCK) { fflush(stdout); return SOCK_TIMEOUT; } rc = 0; } sent += rc; } return sent; }