#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <stdio.h> #include <errno.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <arpa/inet.h> int main __P((int, char **)); int main(argc, argv) int argc; char **argv; { struct addrinfo hints, *hp; struct servent *sp; unsigned long lport; u_int16_t port; char *ep; int dstlen; size_t l; int s; char buf[1024]; char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV]; /* 引数の数をチェック */ if (argc != 3) { fprintf(stderr, "usage: test host port\n"); exit(1); /*NOTREACHED*/ } /* アドレスをバイナリに変換 */ memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; getaddrinfo(argv[1], argv[2], &hints, &hp); if (!hp) { fprintf(stderr, "%s: %s\n", argv[1], hstrerror(h_errno)); exit(1); /*NOTREACHED*/ } /* ポート番号をバイナリに変換 */ sp = getservbyname(argv[2], "TCP"); if (sp) { port = sp->s_port & 0xffff; } else { ep = NULL; errno = 0; lport = strtoul(argv[2], &ep, 10); if (!*argv[2] || errno || !ep || *ep) { fprintf(stderr, "%s: no such service\n", argv[2]); exit(1); /*NOTREACHED*/ } if (lport & ~0xffff) { fprintf(stderr, "%s: out of range\n", argv[2]); exit(1); /*NOTREACHED*/ } port = htons(lport & 0xffff); } endservent(); s = socket(hp->ai_family, hp->ai_socktype, hp->ai_protocol); if (s < 0) { perror("socket"); exit(1); /*NOTREACHED*/ } getnameinfo(hp->ai_addr, hp->ai_addrlen, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV); fprintf(stderr, "trying %s port %u\n", hbuf, ntohs(port)); if (connect(s, hp->ai_addr, hp->ai_addrlen) < 0) { perror("connect"); exit(1); /*NOTREACHED*/ } while ((l = read(s, buf, sizeof(buf))) > 0) write(STDOUT_FILENO, buf, l); close(s); exit(0); /*NOTREACHED*/ }