<Beginning Linux Programming_4th>  chapter 15 Sockets

 

1  A simple local client/server

1)  client.c

// 1) header files
// int socket(int domain, int type, int protocol);
#include <sys/types.h>
// int connect(int socket, const struct sockaddr*address,size_t address_len);
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
/* struct sockaddr_in{
    short int sin_family; // AF_INET
    unsigned short int sin_port; // Port number
    struct in_addr sin_addr; //Internet address
}; */
#include <netinet/in.h>
#include <arpa/inet.h>
// size_t write(int fildes, const void *buf, size_t nbytes);
// size_t read(int fildes, const void *buf, size_t nbytes);
#include <unistd.h>

// 2) socket
int main ()
{
// 127.0.0.1    loopback network
// 192.168.1.1  local area network via an Ethernet adaptor
// 158.152.x.x  modem link to an Internet service provider
    int  sockfd;
    int  len;
    struct  sockaddr_in  address;
    int  result;
    char  ch = 'A';

/* struct in_addr{
    unsigned long int s_addr;
}; */
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = inet_addr("127.0.0.1");
    address.sin_port = htons(9734);
    len = sizeof(address);
/* sizeof(变量/数据类型); // 结果是一个整数
   变量或此种数据类型的变量所占的内存空间字节数
   printf("the size of char is %d bytes\n", sizeof(char)); */
// 3)  connect
    result = connect(sockfd, (struct sockaddr*) &address, len);
    if(result == -1)
    {
        perror("oops: client");
        exit(1);
    }

// 4)  write, read and close
    write(sockfd, &ch, 1);
    read(sockfd, &ch, 1);
    printf("char from server = %c\n", ch);

    close(sockfd);
    exit(0);
}

/* convert 16-bit/32-bit integers between host and network ordering
<netinet/in.h>
unsigned long int htol(unsigned long int hostlong);
unsigned short int htos(unsigned short int hostshort);
unsigned long int ntohl(unsigned long int netlong);
unsigned short int ntohs(unsigned short int netshort);
View Code

相关文章: