Unix Network Programming Episode 4

Introduction to TCP/IP

Introduction

Introduction

When writing programs that communicate across a computer network, one must first invent a protocol, an agreement on how those programs will communicate. Before delving into the design details of a protocol, high-level decisions must be made about which program is expected to initiate communication and when responses are expected.

Routers are the building blocks of WANs. The largest WAN today is the Internet. Many companies build their own WANs and these private WANs may or may not be connected to the Internet.

Most discussions of Unix these days include the term “X,” which is the standard that most vendors have adopted. We describe the history of POSIX and how it affects the Application Programming Interfaces (APIs) that we describe in this text, along with the other players in the standards arena.

A Simple Daytime Client
#include "unp.h"

int main(int argc, char **argv)
{
    int sockfd, n;
    char recvline[MAXLINE+1];
    struct sockaddr_in servaddr;

    if(argc!=2)
        err_quit("usage: a.out ");

    if((socfd=socket(AF_INET, SOCK_STREAM,0))<0)
        err_sys("socket error");

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family=AF_INET;
    servaddr.sin_port=htons(13);
    if(inet_pton(AF_INET, argv[1], &servaddr.sin_addr)<=0)
        err_quit("inet_pton error for %s", argv[1]);

    if(connect(sockfd, (SA *)&servaddr, sizeof(servaddr))<0)
        err_sys("connect error");

    while((n=read(sockfd, recvline, MAXLINE))>0)
    {
        recvline[n]=0;
        if(fputs(recvline stdout)==EOF)
            err_sys("fputs error");
    }
    if(n<0)
        err_sys("read error");

    return 0;
}
Protocol Independence
#include "unp.h"

int main(int argc, char **argv)
{
    int sockfd, n;
    char recvline[MAXLINE+1];
    struct sockaddr_in6 servaddr;

    if(argc!=2)
        err_quit("usage: a.out ");

    if((sockfd=sock(AF_INET6, SOCK_STREAM,0))<0)
        err_sys("socket error");

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin6_family=AF_INET6;
    servaddr.sin6_port=htons(13);
    if(inet_pton(AF_INET6,argv[1], &servaddr.sin6_addr)<=0)
        err_quite("inet_pton error for %s",argv[1]);

    if(connect(sockfd, (SA *)&servaddr, sizeof(servaddr))<0)
        err_sys("connect error");

    while((n=read(sockfd, recvline, MAXLINE))<0)
    {
        recvline[n]=0;
        if(fputs(recvline, stdout)==EOF)
            err_sys("fputs error");
    }

    if(n<0)
        err_sys("read error");

    return 0;
}

你可能感兴趣的:(Linux,Unix,Network,Programming)