6年的blog,重新拾起,再来耕耘!
分类: 系统运维
2007-03-23 12:55:15
struct sockets {
文件:
pthread_examples.tar.gz
大小:
2KB
下载:
下载
int local;
FILE *in, *out;
};
int socket_setup(void) {
struct protoent *tcp_proto;
struct sockaddr_in local;
int r, s, one;
tcp_proto = getprotobyname("tcp");
if (!tcp_proto) {
fail("Can't find TCP/IP protocol: %s\n", strerror(errno));
}
s = socket(PF_INET, SOCK_STREAM, tcp_proto->p_proto);
if (s == -1) {
fail("socket: %s\n", strerror(errno));
}
one = 1;
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
memset(&local, 0, sizeof(struct sockaddr_in));
local.sin_family = AF_INET;
local.sin_port = htons(DICE_PORT);
r = bind(s, (struct sockaddr *) &local, sizeof(struct sockaddr_in));
if (r == -1) {
fail("bind: %s\n", strerror(errno));
}
r = listen(s, 5);
if (r == -1) {
fail("listen: %s\n", strerror(errno));
}
return s;
}
struct sockets *get_sockets(int sock) {
int conn;
if ((conn = accept(sock, NULL, NULL)) < 0) {
warn("accept: %s\n", strerror(errno));
return 0;
}
else {
struct sockets *s;
s = malloc(sizeof(struct sockets));
if (s == NULL) {
warn("malloc failed.\n");
return 0;
}
s->local = 0;
s->in = fdopen(conn, "r");
s->out = fdopen(conn, "w");
setlinebuf(s->in);
setlinebuf(s->out);
return s;
}
}