/* Compile: gcc socket_client.c -lnsl -lsocket -o socket_client */ /* Usage: for example, socket_client cs 6500 Hello */ /* socket_client 193.167.42.127 6500 "Hello again" */ #include #include #include #include #include main(argc,argv) int argc; char **argv; { int sock,len,N; struct sockaddr_in server; struct hostent *hp, *gethostbyname(); char buff[1024]; if (argc != 4) { fprintf(stderr,"usage: %s host port data\n",argv[0]); exit(1); } /* Create a socket */ /* AF_INET = address family Internet domain */ /* SOCK_STREAM = communication semantics */ /* Protocols, see /etc/protocols */ sock=socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) { perror("opening socket"); exit(1);} /* Find the IP-address for a name */ /* gethostbyname returns a structure of tyoe hostent for a given hostname */ /* See netdb.h or man gethostbyname for a definition on a structure */ /* hp contains a structure */ hp = gethostbyname(argv[1]); if (hp == 0) { fprintf(stderr,"unknown host [%s]\n",argv[1]); exit(1); } /* Set address family, IP-address, and a port number to structure */ /* sockaddr_in (server) */ /* bcopy copies the first n bytes of the source string src to the */ /* destination string dest. */ /* void bcopy (const void *src, void *dest, size_t n); */ bcopy((char *)hp->h_addr, (char *) &server.sin_addr, hp->h_length); /* set domain */ server.sin_family=AF_INET; /* Next change the order of bytes to order of network standard */ /* The htons() function converts the short integer hostshort */ /* from host byte order to network byte order. */ if (atoi(argv[2]) != 0) server.sin_port = htons(atoi(argv[2])); else /* default port */ server.sin_port = htons(6500); /* Send a request to a server */ if (connect(sock,(struct sockaddr *) &server, sizeof(struct sockaddr_in)) < 0) { perror("sending"); exit(1); } /* Now connection is open. Now you can write to socket as writing to a file*/ N=strlen(argv[3]); if (write(sock,argv[3],N+1) != N+1) { perror("sending"); exit(1); } /* Close connection (socket) */ close(sock); exit(0); }