c - TCP connect() always passes -
i have simple tcp client follows. problem connect()
call returns 0 when there no server on other side.
int tcpsend(struct sockaddr_in* ipv4_client, const void* buffer, size_t size) { int sd_client = 0; int status = -1; // grab ipv4 tcp socket. sd_client = socket(af_inet, sock_stream, 0); if (sd_client == -1) { return -1; } // make socket non-blocking connect may fail status = fcntl(sd_client, f_setfl, o_nonblock); if (status < 0) { close(sd_client); return -1; } // bind , connect status = connect(sd_client, (struct sockaddr*)ipv4_client, sizeof(*ipv4_client)); if (status == -1) { close(sd_client); return -1; } printf("status: %d %s\n", status, strerror(errno)); //// ??? : status = 0 here // send message server port on machine host. // ignore fact send might not have sent complete data status = send(sd_client, buffer, size, 0); //// consequently sigpipe here if (status == -1) { close(sd_client); return -1; } close(sd_client); return 0; }
i understand connect()
pass if binding succeeds , connection doesn't happen. shouldn't happen when socket made o_nonblock
. code passes @ connect()
, sigpipe
error inside send()
.
after connect in non-blocking mode need call select() socket fd in writable set, i.e. wait until becomes writable, either (1) check errors on socket via getsockopt(),
or (2) call connect() again , check error. after valid start calling send()
or recv().
Comments
Post a Comment