CSCE 313 Lecture 22

From Notes
Jump to navigation Jump to search

« previous | Thursday, April 12, 2012 | next »


Example TCP Client

client-side code

#define LINELEN 128

int connectTCP(const char * host, const char * service) {
    struct sockaddr_in sin;
    memset(&sin, 0, sizeof(sin));
    sin.sin_family = AF_INET;

    // map service to port number
    if (struct servant * pse = getservbyname(service, "tcp") )
        sin.sin_port = pse->s_port;
    else if ((sin.sin_port = htons((unsigned short)atoi(service))) == 0)
        errexit("can't get <%s> service entry\n", service);

    // map host name to IP address, allowing for dotted decimal
    if (struct hostent * phe = gethostbyname(host))
        memcpy(&sin.sin_addr, phe->h_addr, phe->h_length);
    else if ((sin.sin_addr.s_addr = inet_addr(host)) == INADDR_NONE)
        errexit("can't get <%s> host entry\n", host);

    // allocate socket
    int s = socket(AF_INET, SOCK_STREAM, 0);
    if (s<0) errexit("can't create socket: %s\n", strerror(errno));

    if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) < 0)
        errexit("can't connect to %s.%s: %s\n", host, service, strerror(errno));
    return s;
}

int main(argc, char *argv[]) {
    char *host = "localhost";
    char *service = "daytime";

    if (argc > 1) host = argv[1];
    if (argc > 2) service = argv[2];

    int s = connectTCP(host, service);

    while ((int n = read(s, buf, LINELEN)) > 0) {
        buf[n] = '\0';
        (void) fputs(buf, stdout);
    }
}


UDP Connectionless Example

Server Client
socket() socket()
bind() gethostbyname()
recvfrom()
(blocked)
← sendto()
sendto() → recvfrom()
close() close()

Server

sd = socket(AF_INET, SOCK_DGRAM, 0);

// returns information about client
rc = recvfrom(sd, buffer, sieof(buffer), 0, (struct sockaddr*)&clientaddr, &clientaddrlen)

rc = sendto(sd, buffer, sizeof(buffer), 0, (struct sockaddr *)&clientaddr, sizeof(clientaddr));

Beej's Guide to Network Programming using Internet Sockets


Server Design

  • Iterative (simple while loop) vs. Concurrent (multi-user, faster)
  • TCP (reliable, secure, nothing going on when idle) vs. UDP (simple, fast)

Most apps are concurrent and use TCP.

Some simple diagnostic programs are iterative and use UDP

Watch for deadlock (server and client can't both be waiting for data)