/* * netread.c - Vytvori sitove spojeni a zapisuje do neho. * * This is an example file for the UNIX - Programming and System * Administration II course. * * Copyright (C) 2001 Jan "Yenya" Kasprzak * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include #include #include #include #include #include #include #include #define BUFSIZE (1<<14) int main(int argc, char **argv) { struct servent *se; int sock; struct hostent *hp; struct sockaddr_in sin; unsigned short port; int rd, wr; char buf[BUFSIZE], *p; if (argc != 3) { fprintf(stderr, "Usage: %s \n", *argv); return 1; } if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket()"); return 1; } if (!(hp = gethostbyname(argv[1]))) { herror("gethostbyname"); return 1; } if (!(se = getservbyname(argv[2], "tcp"))) { char *endptr = NULL; port = strtoul(argv[2], &endptr, 0); if (argv[2][0] == '\0' || *endptr != '\0') { fprintf(stderr, "%s/%s: no such service\n", argv[2], argv[1]); return 1; } port = htons(port); } else port = se->s_port; /* Already in network order */ sin.sin_family = AF_INET; sin.sin_addr = **((struct in_addr **)hp->h_addr_list); sin.sin_port = port; if (connect(sock, (struct sockaddr *)&sin, sizeof(sin))) { perror("connect()"); return 1; } puts("Connected. Enter data ending with EOF."); while((rd = read(0, buf, BUFSIZE)) > 0) { for (p = buf; (wr = write(sock, p, rd)) > 0; p+=wr) if (!(rd -= wr)) break; if (wr <= 0) { perror("write()"); return 1; } } if (rd < 0) { perror("read()"); return 1; } return 0; }