Socket Programming Practice (3)--socket API

Source: Internet
Author: User
Tags socket error htons

Socket function

#include <sys/types.h> #include <sys/socket.h>int sockets (int domain, int type, int protocol);

Create a socket for communication

Number of references:

Domain: Specifies the Communication protocol family (protocol family), often using the value af_inet(IPV4)

Type: Specifies the socket type, stream socket sock_stream. Datagram Socket Sock_dgram, raw socket Sock_raw

Protocol: protocol type, often using value 0, using default protocol

return value:

Success: Returns a non-negative integer, socket;

Failure: return-1


Bind function

int bind (int sockfd, const struct SOCKADDR *addr, socklen_t Addrlen);

Bind a local address to a socket

Number of references:

socket returned by the Sockfd:socket function

Addr: The address to bind to


/** Demo Sample: Inaddr_any use, bind the machine casual address **/int main () {    int listenfd = socket (af_inet, sock_stream, 0);    if (LISTENFD = =-1)        err_exit ("socket error");    struct sockaddr_in addr;    addr.sin_family = af_inet;    Addr.sin_port = htons (8001);    Bind the random IP address of the machine, acting with the following two lines of statements    addr.sin_addr.s_addr = htonl (inaddr_any);    Inet_aton ("127.0.0.1", &addr.sin_addr);    ADDR.SIN_ADDR.S_ADDR = inet_addr ("127.0.0.1");    if (Bind (LISTENFD, (const struct sockaddr *) &addr, sizeof (addr)) = =-1)        err_exit ("bind error");    else        cout << bind success << Endl;}

Listen function

int listen (int sockfd, int backlog);

The Listen function should be used after calling the socket and bind functions , and before calling accept that transforms a socket from an active socket into a passive socket.

Backlog Description:

For a given listening socket interface, the kernel maintains two queues:

1, has been issued by the customer and reached the server, the server is waiting to complete the corresponding TCP three-way handshake process (SYN_RCVD State)

2, completed the connected queue (established status)

But the sum of two queue lengths cannot exceed the backlog


The backlog recommends using Somaxconn (this value is 128 in 3.13.0-44-generic), using the maximum waiting queue;

Description of Listen in Man-page:

Listen () marks the socket referred to by SOCKFD as a passive sockets, that's, as a socket that

Would be used to accept incoming connection requests using accept (2).

The SOCKFD argument is a file descriptor this 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 was full and the client may receive

An error with an indication of econnrefused or, if the underlying protocol supports retransmission,

The request is ignored so a later reattempt At connection succeeds.

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvempmmjgwndqxntg5/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center "/>

If The backlog argument is greater than the value In/proc/sys/net/core/somaxconn (Ubuntu 14.04 values are), then it's SIL Ently truncated to that value;  The default value in this file is 128. In kernels

Before 2.4.25, this limit is a hard coded value, Somaxconn, with the value 128.

Accept function

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

returns the first connectionfrom the completed connection queue (the initial connection request on the queue of pending connections for the listening

Socket, SOCKFD, creates a new connected socket, and returns a new file descriptor referring to that socket.

The newly created socket is not in the listening state ), assuming that the connection queue is complete empty. is blocked. The original

Socket SOCKFD is unaffected by this call.

Number of references:

SOCKFD: Server sockets

Addr: The socket address of the peer will be returned, without concern, can be set to null

Addrlen: Returns the socket address length of the peer, which can be set to NULL if not concerned, or it must be initialized

return value:

on success, these system calls return a non-negative integer so is a descriptor for the accepted

socket. On error, 1 are returned, and errno is set appropriately.

Connect function

int connect (int sockfd, const struct SOCKADDR *addr, socklen_t Addrlen);

Establish a connection to the socket specified by addr

Number of references:

SOCKFD: Socket not connected

Addr: Socket address to connect to

Addrlen: second parameter addr length

Demo Sample: Echo server/client implementation

Server-side code int main () {int LISTENFD = socket (af_inet, sock_stream, 0);    if (LISTENFD = =-1) err_exit ("Socket error");    struct sockaddr_in addr;    addr.sin_family = af_inet;    Addr.sin_port = htons (8001);    ADDR.SIN_ADDR.S_ADDR = htonl (Inaddr_any);    if (Bind (LISTENFD, (const struct sockaddr *) &addr, sizeof (addr)) = =-1) err_exit ("Bind error");    if (Listen (LISTENFD, somaxconn) = =-1) err_exit ("Listen error");    Char buf[512];    int readbytes;    struct sockaddr_in clientaddr;    Remember: Be sure to initialize socklen_t Addrlen = sizeof (CLIENTADDR) here;        while (true) {int clientfd = accept (LISTENFD, (struct sockaddr *) &clientaddr, &addrlen);        if (clientfd = =-1) err_exit ("Accept error");  Print client IP address and port number cout << "Client information:" << Inet_ntoa (clientaddr.sin_addr) << ",        "<< Ntohs (clientaddr.sin_port) << Endl;        memset (buf, 0, sizeof (BUF)); while ((readbytes = reAD (Clientfd, buf, sizeof (BUF))) > 0) {cout << buf;            if (Write (CLIENTFD, buf, readbytes) = =-1) err_exit ("Write socket error");        memset (buf, 0, sizeof (BUF));            } if (readbytes = = 0) {cerr << "client connect closed ..." << Endl;        Close (CLIENTFD);    } else if (readbytes = =-1) err_exit ("Read socket error"); } close (LISTENFD);}
Client-side code int main () {int SOCKFD = socket (af_inet, sock_stream, 0);    if (SOCKFD = =-1) err_exit ("Socket error");    Fill in the server port number and IP address struct sockaddr_in serveraddr;    serveraddr.sin_family = af_inet;    Serveraddr.sin_port = htons (8001);    SERVERADDR.SIN_ADDR.S_ADDR = inet_addr ("127.0.0.1");     if (Connect (SOCKFD, (const struct sockaddr *) &serveraddr, sizeof (serveraddr)) = =-1) err_exit ("Connect error");    Char buf[512]; while (Fgets (buf, sizeof (BUF), stdin)! = NULL) {if (write (SOCKFD, buf, strlen (buf)) = = =-1) err_exit (        "Write socket error");        memset (buf, 0, sizeof (BUF));        int readbytes = Read (SOCKFD, buf, sizeof (BUF));            if (readbytes = = 0) {cerr << "server connect closed ... \nexiting ..." << Endl;        Break        } else if (readbytes = =-1) err_exit ("Read socket error");        cout << buf;    memset (buf, 0, sizeof (BUF)); } close (SOCKFD);}

Attached-makefile

. Phony:clean all CC = g++ Cppflags =-wall-g-pthread-std=c++11bin = Server Clientsources = $ (bin.=.cpp) All: $ (BIN) $ (bin ): $ (SOURCES) Clean:    -RM-RF $ (BIN) Bin/obj/core


Socket Programming Practice (3)--socket API

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.