Socket programming practice (2)

Source: Internet
Author: User
Tags socket error htons
Socket api basic Programming Model

Tcp client/server model


 

 

Simple echo server model

 

 

Basic Socket API practices

Socket Functions

#include <sys/types.h>          /* See NOTES */#include <sys/socket.h>

 

Function: Creates a socket for communication.

Prototype

int socket(int domain, int type, int protocol);

Parameters

Domain: Specifies the protocol family. The common value is af_inet (IPv4)

Type: Specifies the socket type, streaming socket sock_stream, datagram socket sock_dgram, original socket sock_raw

Protocol: protocol type. Common Values: 0

 

Return Value:

A non-negative integer is returned successfully. It is similar to a file descriptor. We call it a socket for short. -1 returned for failure

 

Bind Functions

Function: bind a local address to a socket

Prototype

int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);

Parameters

Sockfd: Socket returned by the socket function

ADDR: Address to bind

Addrlen: Address Length

 

Return Value:

0 is returned for success and-1 is returned for failure.

 

Appendix-sockaddr Structure

struct sockaddr{    sa_family_t sa_family;    char        sa_data[14];}

 

Sockaddr_in Structure

struct sockaddr_in{    sa_family_t    sin_family; /* address family: AF_INET */    in_port_t      sin_port;   /* port in network byte order */    struct in_addr sin_addr;   /* internet address */};/* Internet address. */struct in_addr{    uint32_t       s_addr;     /* address in network byte order */};

In_addr is defined as follows:

typedef uint32_t in_addr_t;struct in_addr{    in_addr_t s_addr;};

// Practice int main () {int sockfd = socket (af_inet, sock_stream, 0); If (sockfd =-1) {err_exit ("socket error ");} struct sockaddr_in serveraddr; serveraddr. sin_family = af_inet; serveraddr. sin_port = htons (8001); serveraddr. sin_addr.s_addr = inaddr_any; // bind any IP address of the Local Machine. // serveraddr. sin_addr.s_addr = inet_addr ("10.20.218.20"); If (BIND (sockfd, (struct sockaddr *) & serveraddr, sizeof (serveraddr) =-1) {er R_exit ("BIND error");} else {cout <"bind OK! "<Endl;} return 0 ;}


Listen Function

The listen function should be called after the socket and bind functions are called and before the function accept is called.

SYNOPSIS       #include <sys/types.h>          /* See NOTES */       #include <sys/socket.h>        int listen(int sockfd, int backlog); DESCRIPTION       listen() marks the socket referred to by sockfd as a passive socket, that is, as a socket that will be used to accept incoming connection requests using accept(2).       The sockfd argument is a file descriptor that refers to a socket of type  SOCK_STREAM  or SOCK_SEQPACKET.       The backlog argument defines the maximum length to which the queue of pending connections for sockfd may grow.  If a connection request arrives when the queue is full, the  client may  receive  an  error with an indication of ECONNREFUSED or, if the underlying protocol supports retransmission, the request may be ignored so that a later reattempt at  connection succeeds.

 

Return Value:

Success: 0 is returned; Failure:-1 is returned, and the errno value is set.

 

Backlog description:

For a given listening set interface, the kernel needs to maintain two queues:


1. The client has sent the request to the server, and the server is waiting for the TCP three-way handshake process to be completed.

2. Queue with Connection completed

However, the sum of the two queue lengths cannot exceed the backlog



If the backlog argument is greater than the value in/proc/sys/NET/CORE/somaxconn (Ubuntu 14.04 is set to 128), then it is silently truncated to that value; the default value in this file is 128. in kernels before 2.4.25, this limit was a hard coded value, somaxconn, with the value 128.

// Bind practice int main () {int sockfd = socket (af_inet, sock_stream, 0); If (sockfd =-1) {err_exit ("socket error ");} struct sockaddr_in serveraddr; serveraddr. sin_family = af_inet; serveraddr. sin_port = htons (8001); serveraddr. sin_addr.s_addr = inaddr_any; // bind any IP address of the Local Machine. // serveraddr. sin_addr.s_addr = inet_addr ("10.20.218.20"); If (BIND (sockfd, (struct sockaddr *) & serveraddr, sizeof (serveraddr) =-1) {Err_exit ("BIND error");} // once listen is called, The FD programming passive socket waits for the connection from the client (only connections can be accepted, not connections sent) if (Listen (sockfd, somaxconn) =-1) {err_exit ("Listen error");} else {cout <"somaxconn =" <somaxconn <Endl; cout <"Listen OK! "<Endl;} return 0 ;}


Socket programming practice (2)

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.