Socket Programming Practice (3)--socket API

Source: Internet
Author: User
Tags socket error server port htons

Socket function

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

Create a socket for communication

Parameters:

Domain: Specify communication protocol family (protocol family), common value af_inet(IPV4)

Type: Specify socket type, stream socket sock_stream, datagram socket sock_dgram, raw socket Sock_raw

Protocol: protocol type, common 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

Parameters:

socket returned by the Sockfd:socket function

Addr: The address to bind to


/** Example: Use of Inaddr_any, bind the machine arbitrary 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 any 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 the bind function , 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 connected queue (established status)

However, 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.

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 If the connection queue has been completed empty, it is blocked. The original

Socket SOCKFD is unaffected by this call.

Parameters:

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 it is 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

Parameters:

SOCKFD: Socket not connected

Addr: Socket address to connect to

Addrlen: Addr Length of the second parameter

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.