while (nleft > 0) {
if ((nwriten = write (fd, bufp, nleft)) <= 0) {
if (EINTR == errno)
nwriten = 0;
else
return -1;
}
nleft -= nwriten;
bufp += nwriten;
}
return n;
}
/*read line from fd*/
ssize_t readline (int fd, void *buf, size_t maxlen)
{
ssize_t n, rc;
char c, *bufp;
bufp = buf;
for (n = 1; n < maxlen; n ++) {
again:
if (1 == (rc = read (fd, &c, 1))) {
*bufp ++ = c;
if ('\n' == c)
break; /*newline is stored*/
} else if (rc == 0) {
*bufp = 0;
return (n - 1); /*EOF, n-1 bytes were read*/
} else {
if (EINTR == errno) /*interrupt*/
goto again;
return -1; /*Erro, set the errno by read ()*/
}
}
*bufp = 0;
return n;
}
运行结果:
因为客户端没有指定IP地址和端口,所以其IP和端口都是内核随机分配的。