Network Programming Basics

Source: Internet
Author: User
Tags get ip to domain

1. client-server model

1) when a client needs services, it sends a request to the server and initiates a transaction.

2) After receiving the request, the server interprets it and operates its resources in an appropriate way.

3) The service end sends a response to the client and waits for the next request.

4) The client receives the response and processes it.

 

2. Network

For a host, the network is only an I/O device.

Physically, a network is a hierarchical system composed of geographical distances.

On the internet, it takes eight steps to transmit data from one host to another:

3. TCP/IP

TCP/IP is actually a protocol family, each of which provides different functions. The IP protocol provides basic naming and transmission mechanisms to send data packets from one host to another.

The IP address mechanism is unreliable. UDP slightly extends the IP protocol, and packets can be transmitted between processes rather than between hosts. TCP is a complex protocol built on an IP address, providing reliable full-duplex and reliable connections between processes.

IP Address:

An IP address is a 32-bit unsigned integer. IP addresses are mapped to domain names through the DNS (Domain Name System) Database

struct in_addr {    unsigned int s_addr; /* Network byte order (big-endian) */};

4. Socket

From the program perspective, the socket is an open file with the corresponding descriptor. A socket is an endpoint of a connection. Each socket has a socket address, which consists of an Internet address and a 16-bit integer port.

The client socket address is automatically allocated by the kernel, which is called a temporary port. The server socket address is usually a well-known port number on UNIX.

The/etc/services file contains the services provided by this machine and their list of well-known port numbers.

The socket address at both ends of a connection is uniquely identified.

(cliaddr:cliport, servaddr:servport)

IOS socket:

The Network Programming hierarchy model for iOS is divided into three layers:

Cocoa layer: nsurl, bonjour, game kit, WebKit

Core Foundation layer:C-basedCfnetwork and cfnetservices

OS layer: C-based BSD socket

- (void)loadDataFromServerWithURL:(NSURL *)url{    NSString * host = [url host];    NSNumber * port = [url port];        // Create socket    //    int socketFileDescriptor = socket(AF_INET, SOCK_STREAM, 0);    if (-1 == socketFileDescriptor) {        NSLog(@"Failed to create socket.");        return;    }        // Get IP address from host    //    struct hostent * remoteHostEnt = gethostbyname([host UTF8String]);    if (NULL == remoteHostEnt) {        close(socketFileDescriptor);                [self networkFailedWithErrorMessage:@"Unable to resolve the hostname of the warehouse server."];        return;    }        struct in_addr * remoteInAddr = (struct in_addr *)remoteHostEnt->h_addr_list[0];        // Set the socket parameters    //    struct sockaddr_in socketParameters;    socketParameters.sin_family = AF_INET;    socketParameters.sin_addr = *remoteInAddr;    socketParameters.sin_port = htons([port intValue]);        // Connect the socket    //    int ret = connect(socketFileDescriptor, (struct sockaddr *) &socketParameters, sizeof(socketParameters));    if (-1 == ret) {        close(socketFileDescriptor);                NSString * errorInfo = [NSString stringWithFormat:@" >> Failed to connect to %@:%@", host, port];        [self networkFailedWithErrorMessage:errorInfo];        return;    }        NSLog(@" >> Successfully connected to %@:%@", host, port);    NSMutableData * data = [[NSMutableData alloc] init];    BOOL waitingForData = YES;        // Continually receive data until we reach the end of the data    //    int maxCount = 5;   // just for test.    int i = 0;    while (waitingForData && i < maxCount) {        const char * buffer[1024];        int length = sizeof(buffer);                // Read a buffer‘s amount of data from the socket; the number of bytes read is returned        //        int result = recv(socketFileDescriptor, &buffer, length, 0);        if (result > 0) {            [data appendBytes:buffer length:result];        }        else {            // if we didn‘t get any data, stop the receive loop            //            waitingForData = NO;        }                ++i;    }        // Close the socket    //    close(socketFileDescriptor);        [self networkSucceedWithData:data];}

 

 

5. The sockets Interface

A socket interface is a group of functions that are combined with Unix I/O functions to create network applications.

The internet socket address is stored in the 16 addr_in 16-byte structure.

/* Internet-style socket address structure */struct sockaddr_in  {    unsigned short  sin_family;  /* Address family (always AF_INET) */    unsigned short  sin_port;    /* Port number in network byte order */    struct in_addr  sin_addr;    /* IP address in network byte order */    unsigned char   sin_zero[8]; /* Pad to sizeof(struct sockaddr) */?};

Socket function:

The client and the server use the socket function to create a socket descriptor.

#include <sys/types.h> #include <sys/socket.h>int socket(int domain, int type, int protocol);//Returns: nonnegative descriptor if OK, −1 on error

Connect function:
The client calls the connect function to establish a connection with the server.

#include <sys/socket.h>int connect(int sockfd, struct sockaddr *serv_addr, int addrlen);//Returns: 0 if OK, −1 on error

The connect function is blocked until the connection is successful or an error occurs. After the connection is successful, the sockfd descriptor can be read and written.

Bing function:

#include <sys/socket.h>int bind(int sockfd, struct sockaddr *my_addr, int addrlen);//Returns: 0 if OK, −1 on error

The BIND function tells the kernel that the server socket address in my_addr is associated with the socket descriptor sockfd.

Listen function:
The listen function tells the kernel that the descriptor is used by the server rather than the client.

#include <sys/socket.h>int listen(int sockfd, int backlog);Returns: 0 if OK, −1 on error

Accept function:

??#include <sys/socket.h>int accept(int listenfd, struct sockaddr *addr, int *addrlen);//Returns: nonnegative connected descriptor if OK, −1 on error

The accept function waits for the connection request from the client to arrive at the listener descriptor listenfd, then fill in the client socket address in ADDR, and return a connection descriptor, which is used to communicate with the client.

The listener descriptor returned by the listen function is an endpoint of the client request. It is created once and has the entire declaration cycle with the server, the connected descriptor is a connection endpoint established between the client and the server segment. Each time the Server accepts the request Shiite, it is created. It only exists in the Process of serving the server as a client.

6. Web Servers

The Web Client interacts with the server segment using an application-level protocol called HTTP for sending text.

For the client and server, the content is a byte sequence related to the mime (Multipurpose Internet Mail Extensions) type.

 

Each piece of content returned by the Web server is associated with a file managed by the Web server. Each of these files has a unique name:

URL (Universal Resource Locator), for example:

http://www.google.com:80/index.html

Indicates a/index.html file on the host www.google.com. the URL of the executable file can include program parameters after the file name. "?" The file names and parameters are separated by characters, and each parameter is separated by the "&" character, for example:

http://bluefish.ics.cs.cmu.edu:8000/cgi-bin/adder?15000&213

Indicates an executable file named/cgi-bin/adder with two parameters 15000 and 213.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.