"Untitled Post" - Views: 32 · Hits: 32 - Type: Public

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

#define BUFLEN 256

void error(const char* msg){
    perror(msg);
    exit(1);
}

int main(int argc, const char * argv[]) {
    pthread_t readt;
    pthread_t writet;
    
    int sockfd, portnum;
    size_t n;
    struct sockaddr_in serveraddr;
    struct hostent* server;
    char buffer[BUFLEN];
    
    if(argc < 3){
        perror("You shall provide a port and a ip adress");
    }
    portnum = atoi(argv[2]);
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0){
        error("Error opening socket");
    }
    server = gethostbyname(argv[1]);
    if(!server){
        error("No such host");
    }
    bzero((char*)&serveraddr, sizeof(serveraddr));
    serveraddr.sin_family = AF_INET;
    bcopy((char *)server->h_addr, (char *)&serveraddr.sin_addr.s_addr, sizeof(server->h_length));
    serveraddr.sin_port = htons(portnum);
    
    if(connect(sockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr))<0){
        error("Connection failed");
    }
    
    
    while(1){
        bzero(buffer, BUFLEN);
        fgets(buffer, BUFLEN, stdin);
        n = write(sockfd, buffer, strlen(buffer));
        if(n < 0){
            error("Error on writing");
        }
        bzero(buffer, BUFLEN);
        n = read(sockfd, buffer, (BUFLEN));
        if(n < 0){
            error("Error on reading");
        }
        printf("Server: %s", buffer);
        int i = strncmp("Bye", buffer, 3);
        if(i == 0){
            break;
        }
        
    }
    close(sockfd);
    return 0;
}