Sockets programming -- Connection refused
Alexandros Andreou
andreou at kerveros.gr
Sat Aug 5 20:25:09 EEST 2000
Ti 3exasa, ti 3exasa... To attached arxeio :-)
-------------- next part --------------
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define SUCCESS 0
#define ERROR (-1)
#define PORT 5820
#define KB 1024
#define BUFSIZE KB/8
static const char *version =\
"sysmgr.c:v0.1 Aug 5 2000\n(C) 2000 Alexandros Andreou <andreou at kerveros.gr>\nReleased under GNU GPL.\n";
int main(int argc, char *argv[])
{
int sockfd = 0;
unsigned short int port = PORT;
struct hostent *he;
struct sockaddr_in sin;
FILE *fp = 0,
*sockfp = 0;
char buf[BUFSIZE];
printf(version);
if (argc < 2 || argc > 3) {
fprintf(stderr, "\n\tUsage: %s <hostname> [<port>]\n", argv[0]);
exit(ERROR);
}
if (argc == 3)
port = (unsigned short int)strtol(argv[2], NULL, 10);
if ((he = gethostbyname(argv[1])) == NULL) {
perror("sysmgr.c: gethostbyname()");
exit(ERROR);
}
sin.sin_family = AF_INET;
sin.sin_port = port;
sin.sin_addr = *((struct in_addr *)he->h_addr);
bzero(&sin.sin_zero, 8);
bzero(&buf, BUFSIZE);
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == ERROR) {
perror("sysmgr.c: socket()");
exit(ERROR);
}
printf("Trying to connect to %s (%s) on port %d...\n", argv[1], inet_ntoa(sin.sin_addr), sin.sin_port);
if (connect(sockfd, (struct sockaddr *)&sin, sizeof(sin)) == ERROR) {
perror("sysmgr.c: connect()");
exit(ERROR);
}
if ((fp = fdopen((int)stdin, "r")) == NULL) {
perror("sysmgr.c: fdopen(stdin)");
exit(ERROR);
}
if ((fp = fdopen(sockfd, "r")) == NULL) {
perror("sysmgr.c: fdopen(sockfd)");
exit(ERROR);
}
while (fgets(buf, BUFSIZE, fp) != NULL) {
if (!strncasecmp("QUIT", buf, strlen(buf))) {
fputs(buf, sockfp);
break;
} else
fputs(buf, sockfp);
}
fclose(sockfp);
return (SUCCESS);
}
More information about the Linux-greek-users
mailing list