tcp.cpp 2.06 KB
#include "tcp.h"

int createSocket()
{
    int sockfd;
    if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        cout << "Could not create socket" << endl;
        exit(3);
    }
    return sockfd;
}

void connect(int s, uint16_t port, char *hostname, int timeout)
{
    struct in_addr *addr_ptr;
    struct hostent *hostPtr;
    string add;
    hostPtr = gethostbyname(hostname);
    if(hostPtr == NULL)
    {
        cout << "Could not resolve hostname" << endl;
        exit(3);
    }
    addr_ptr = (struct in_addr *)*hostPtr->h_addr_list;
    add = inet_ntoa(*addr_ptr);
    if(add == "")
    {
        cout << "Invalid address" << endl;
        exit(3);
    }
    struct sockaddr_in newSockAddr;
    newSockAddr.sin_family = AF_INET;
    newSockAddr.sin_port = htons(port);
    newSockAddr.sin_addr.s_addr = inet_addr(add.c_str());
    if(connect(s, (struct sockaddr *)&newSockAddr, sizeof(struct sockaddr)) != 0)
    {
        cout << "Could not connect to " << hostname << " on port " << port << endl;
        exit(3);
    }

    struct timeval tv;
    tv.tv_sec = timeout;
    tv.tv_usec = 0;
    if(setsockopt(s, SOL_SOCKET, SO_RCVTIMEO,&tv,sizeof(tv)) < 0)
    {
        cout << "Error setting socket timeout" << endl;
        exit(3);
    }
    fcntl(s, F_SETFL, O_NONBLOCK);
}

int sendMsg(int s, const char *msg, size_t msgLength)
{
    int bytes, total = 0;
    while(total != msgLength)
    {
        bytes = send(s,msg+total,msgLength-total,0);
        if(bytes == -1)
        {
            cout << "TCP: Could not write to socket." << endl;
            exit(3);
        }
        total += bytes;
    }
    return total;
}

int recvMsg(int s, char *msg, size_t msgLength)
{
    int bytes, total = 0;
    while(total != msgLength)
    {
        bytes = recv(s, msg+total, msgLength-total,0);
        if ( bytes <= 0 )
        {
            if(errno == EWOULDBLOCK || errno == EAGAIN)
            {
                return 0;
            }
            cout << "TCP: Could not read from socket." << endl;
            exit(3);
        }
        total += bytes;
    }
    return total;
}