Annotation of OpenXM/src/ox_toolkit/mysocket.c, Revision 1.2
1.1 ohara 1: /* -*- mode: C; coding: euc-japan -*- */
1.2 ! ohara 2: /* $OpenXM: OpenXM/src/ox_toolkit/mysocket.c,v 1.1 1999/12/09 22:44:55 ohara Exp $ */
1.1 ohara 3: /*
4: setsockopt()してオプションを設定後,
5: socket, bind
6: するとローカルポートが割り当てられる。
7: その後, getsockname によってポート番号が求まる.
8: */
9:
10: #include <stdio.h>
11: #include <stdlib.h>
12: #include <unistd.h>
13: #include <errno.h>
14: #include <netdb.h>
15: #include <netinet/in.h>
16: #include <sys/types.h>
17: #include <sys/socket.h>
18: #include <fcntl.h>
19:
20: #if defined(__sun__)
21: #include <arpa/inet.h>
22: #endif
23:
24: #include "mysocket.h"
25:
26: static int getsocket(struct sockaddr_in *mp, char *host, short port)
27: {
28: struct hostent *ent = gethostbyname(host);
29:
30: memset(mp, '\0', sizeof(struct sockaddr_in));
31: mp->sin_family = AF_INET;
32: mp->sin_port = htons(port);
33: memcpy((char *)&mp->sin_addr, ent->h_addr, ent->h_length);
34:
35: return socket(AF_INET, SOCK_STREAM, 0);
36: }
37:
38: int mysocketAccept(int s_waiting)
39: {
40: int val = accept(s_waiting, NULL, NULL);
41: return val;
42: }
43:
44: int mysocketListen(char *hostname, short *portp)
45: {
46: int option;
47: int tmp;
48: struct sockaddr_in me;
49:
50: int s_waiting = getsocket(&me, hostname, *portp);
51:
52: option = 1;
53: setsockopt(s_waiting, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
54:
55: if (bind(s_waiting, (struct sockaddr *)&me, sizeof(me)) < 0) {
56: fprintf(stderr, "bind: failed.\n");
57: exit(1);
58: }
59:
60: tmp = sizeof(me);
61: if (getsockname(s_waiting, (struct sockaddr *)&me, &tmp) < 0) {
62: fprintf(stderr, "getsockname is failed.\n");
63: exit(1);
64: }
65:
66: *portp = ntohs(me.sin_port);
67:
68: if (listen(s_waiting, 1) < 0) {
69: fprintf(stderr, "listen: failed.\n");
70: exit(1);
71: }
72:
73: return s_waiting;
74: }
75:
76: int mysocketOpen(char* hostname, short port)
77: {
78: struct sockaddr_in serv;
79: int s = getsocket(&serv, hostname, port);
80:
81: fprintf(stderr, "get socket address for port number %d.\n", port);
82: if (connect(s, (struct sockaddr *)&serv, sizeof(serv)) != 0) {
83: fprintf(stderr, "connect: fail! socket = %d, errno = %d\n", s, errno);
84: exit(-1);
85: }
86: return s;
87: }
88:
89: #if 0
90: int mypipe(char *program, int fd1, int fd2)
91: {
92: int sockfd[2];
93: if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockfd) < 0) {
94: fprintf(stderr, "socketpair: fail! errno = %d\n", errno);
95: }
96: if (fork() == 0) {
1.2 ! ohara 97: /* child process */
1.1 ohara 98: close(sockfd[0]);
99: dup2(sockfd[1], fd1);
100: dup2(sockfd[1], fd2);
101: execl(program, program, NULL);
102: }
1.2 ! ohara 103: /* parent process */
1.1 ohara 104: close(sockfd[1]);
105: return sockfd[0];
106: }
107: #endif
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>