Linux socket recognition

Source: Internet
Author: User

Linux in the way of C, the creation of the server is mainly composed of several modules: the creation of the section Word, the encapsulation IP address and port number, and socket connection method, the binding socket and the encapsulated struct sockaddr_in,

Listen to the execution, open the server side, accept client links, accept clients messages, send service-side messages.

Create a section Word:

Code:

int socket;

Socket = new socket (af_inet,sock_stream,0);

Comments:

1.af_inet:ipv4 Network protocol

2.af_inet6:ipv6 Network protocol

3.sock_stream: Link-oriented TCP protocol

4.sock_dgram: Non-linked UDP protocol

Encapsulate IP Address and port number:

Code:

struct SOCKADDR_IN server;

int port = 8888;

Bzero (&server,sizeof (server));

Server.sin_family=af_inet

SERVER.SIN_ADDR.S_ADDR = Inaddr_any;

Server.sin_port = htons (port);

Comments:

1.bzero (); Used to initialize the struct sockaddr_in

2.sin_family set the network protocol, only the Af_inet

3.sin_addr.s_addr used to set the IP address, Inaddr_any represents the native IP address

4.sin_port used to set the port number

Binding sockets and Struct SOCKADDR_IN

Code:

Bind (sock, struct sockaddr*) &server,sizeof (struct sockaddr));

Comments:

Bind (sock handle, struct sockaddr_in pointer, struct sockaddr_in length);

Turn on listening for client connections:

Code:

struct SOCKADDR_IN temp;

int addresssize;

int client_sock;

while (1)

{

Client_sock=accept (sock, (struct sockaddr_in*) &temp,&addresssize);

}

Send and receive client data:

Char buf[1024];

int Len;

Recv (client_sock,buf,1024,0);

printf ("Client recv:%s\n", buf);

Len=strlen (BUF);

Send (client_sock,buf,len,0);

Linux socket recognition

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.