Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <netdb.h>
- #include "Practical.h"
- void DieWithUserMessage(const char *msg, const char *detail) {
- fputs(msg, stderr);
- fputs(": ", stderr);
- fputs(detail, stderr);
- fputc('\n', stderr);
- exit(1);
- }
- void DieWithSystemMessage(const char *msg) {
- perror(msg);
- exit(1);
- }
- int main(int argc, char *argv[]) {
- struct addrinfo *result, *rp;
- int sfd, s, j;
- char c;
- if (argc != 3) // Check for correct number of parameters
- DieWithUserMessage("Parameter(s)", "<Server Address> [<Server Port>]");
- char *servHostname = argv[1]; // First arg: Hostname
- char *servPort = argv[2]; // Second arg: Server port
- // Obtain address(es) matching host/port
- struct addrinfo addrCriteria; // Criteria for address match
- memset(&addrCriteria, 0, sizeof(addrCriteria)); // Zero out structure
- addrCriteria.ai_family = AF_UNSPEC; // Any address family
- addrCriteria.ai_socktype = SOCK_STREAM; // Only stream sockets
- addrCriteria.ai_protocol = IPPROTO_TCP; // Only TCP protocol
- s = getaddrinfo(servHostname, servPort, &addrCriteria, &result);
- if (s != 0)
- DieWithUserMessage("getaddrinfo() failed", gai_strerror(s));
- /* We should only get one struct back, but I'll do it the way the man pages say,
- Allowing for multiple possible addresses, trying each address until we connect.
- if socket() or connect() fail, close socket and try the next address */
- for (rp = result; rp != NULL; rp = rp->ai_next) {
- sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
- if (sfd == -1) /* Failure to connect */
- continue;
- if (connect(sfd, rp->ai_addr, rp->ai_addrlen) != -1)
- break; /* Successfully connected */
- shutdown(sfd, SHUT_RDWR); /* Close the socket that failed */
- }
- freeaddrinfo(result); // Free addrinfo allocated in getaddrinfo()
- if (rp == NULL) { /* No address succeeded if the rp is still null */
- fprintf(stderr, "Could not connect\n");
- exit(EXIT_FAILURE);
- }
- /* Read stdin */
- while (EOF != (c = fgetc(stdin))) {
- write(sfd, &c, sizeof(c));
- }
- /* write the stuff coming back from the server */
- while (read(sfd, &c, sizeof(c)) > 0){
- printf("\n");
- fputc(c, stdout);
- }
- shutdown(sfd, SHUT_RDWR); /* Close the socket that failed */
- exit(0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement