-
Notifications
You must be signed in to change notification settings - Fork 0
/
header.cc
81 lines (77 loc) · 1.69 KB
/
header.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include"header.h"
using namespace std;
void error(char *msg) {
perror(msg);
exit(0);
}
ssize_t read1(int fd, void *vptr, size_t n) throw (int) {
size_t nleft;
ssize_t nread = 0;
char *ptr;
ptr = (char *) (vptr);
nleft = n;
while (nleft > 0) {
// if ptr not reach the end of vptr
// read the massage from the socket.
if ((nread = read(fd, ptr, nleft)) < 0) {
if (errno == EINTR)
nread = 0;
else {
printf("reading error");
throw 1;
}
} else if (nread == 0)
break;
nleft -= nread;
ptr += nread;
}
// return how many elements have been read.
return (n - nleft);
}
ssize_t write1(int fd, void *vptr, size_t n) throw (int) {
size_t nleft;
ssize_t nwritten;
char *ptr = (char *) vptr;
nleft = n;
while (nleft > 0) {
// if ptr not reach the end of vptr
// write the massage to the server.
if ((nwritten = write(fd, ptr, nleft)) <= 0) {
if (nwritten < 0 && errno == EINTR)
nwritten = 0;
else {
printf("writting error");
throw 1;
}
}
nleft -= nwritten;
ptr += nwritten;
}
// return how many elements have been writen.
return (n - nleft);
}
struct hostent* get_ipaddr(char *name, int connfd) {
struct hostent hostbuf, *hp;
size_t hstbuflen;
char *tmphstbuf;
int res;
int herr;
hstbuflen = 1024;
// allocate buffer.
try {
tmphstbuf = (char *) malloc(hstbuflen);
while ((res = gethostbyname_r(name, &hostbuf, tmphstbuf, hstbuflen,
&hp, &herr)) == ERANGE) {
// enlarge the buffer.
hstbuflen *= 2;
tmphstbuf = (char *) realloc(tmphstbuf, hstbuflen);
}
} catch (exception &ex) {
printf("bad allocation in dns %s\n", ex.what());
}
free(tmphstbuf);
// check for errors.
if (res || hp == NULL)
return NULL;
return hp;
}