A detailed explanation of TCP programming functions and steps

Source: Internet
Author: User
Tags bind socket port number

The server-side general step of TCP programming is

1, create a socket, with the function socket ();

2, set the socket property, with function setsockopt (); * Optional

3, binding IP address, port and other information to the socket, with the function bind ();

4, open listening, with function listen ();

5, receive the connection from the client, use function accept ();

6, send and receive data, use the function send () and recv (), the person read () and write ();

7, close the network connection;

8, close the monitoring;

The typical client steps for TCP programming are:

1, create a socket, with the function socket ();

2, set the socket property, with function setsockopt (); * Optional

3, binding IP address, port and other information to the socket, with the function bind (); * Optional

4, set to connect the other side of the IP address and Port properties;

5, connect the server, use the function connect ();

6, send and receive data, use the function send () and recv (), or read () and write ();

7, close the network connection;

The server-side general procedure for UDP programming is:

1, create a socket, with the function socket ();

2, set the socket property, with function setsockopt (); * Optional

3, binding IP address, port and other information to the socket, with the function bind ()

4, the circulation receives the data, uses the function recvfrom ();

5, close the network connection;

The client-side general procedure for UDP programming is:

1, create a socket, with the function socket ();

2, set the socket property, with function setsockopt (); * Optional

3, binding IP address, port and other information to the socket, with the function bind (); * Optional

4, set the IP address of each other and port and other attributes;

5, send data, use function sendto ();

6, close the network connection;

Common network commands:

Netstat

Command netstat is used to display information about networks such as connections, routing tables, and interface statistics. Netstat has a number of options our common option is-an to display detailed network status. As for the other options, we can use help.

Telnet

Telnet is a program for remote control, but we can use this program to debug our server program. For example, our server program is listening on port 8888, we can use Telnet localhost 8888来 to view the service side condition

Data

1, Address structure

struct SOCKADDR_IN {

short int sin_family; /* Address family generally for af-inet * *

unsigned short int sin_port; /* Port Number * *

struct IN_ADDR sin_addr; /* IP Address * *

unsigned char sin_zero[8]; /* Fill 0 to maintain the same size as the struct sockaddr using memset () or bzero () to fill the */

};

struct SOCKADDR {

unsigned short sa_family; * * Address family, AF_XXX * *

Char sa_data[14]; /* 14-BYTE protocol address * *

};

2. DNS Structure

struct Hostent {

Char *h_name; /* Host's official domain name * *

Char **h_aliases; /* A null-terminated host alias Array/*

int h_addrtype; /* return type of address, in the context of the Internet for af-inet * *

int h_length; /* Address byte length * *

Char **h_addr_list; /* A 0-terminated array containing all the addresses of the host.

};

Action function

1. Socket:

Create a Socket descriptor

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

The type of domain=af_inet,socket, Type=sock_stream or SOCK_DGRAM, representing the TCP connection and the UDP connection respectively; protocol=0.

Returns an integral socket descriptor.

2.bind:

Associate the socket descriptor with a port on your computer (server only)

int bind (int sockfd,struct sockaddr *my_addr, int addrlen);

SOCKFD is a socket descriptor

MY_ADDR is a pointer to a type of sockaddr containing information such as native IP address and port number;

addrlen=sizeof (struct sockaddr).

Return: Success = 0; failure =-1,errno= error number.

You can use the following assignment to automatically obtain a native IP address and randomly obtain a port number that is not occupied:

My_addr.sin_port = 0; /* System randomly select an unused port number * *

MY_ADDR.SIN_ADDR.S_ADDR = Inaddr_any; /* Fill in the local IP address * *

3.Connect:

Establish a TCP connection with the remote server (for clients)

int connect (int sockfd, struct sockaddr *serv_addr, int addrlen);

SOCKFD is the Sockt descriptor for the destination server

SERV_ADDR is a pointer that contains the destination computer's IP address and port number.

Return: Success = 0; failure =-1,errno= error number.

4, Listen:

Listen for service requests, after bind ()

int listen (int sockfd, int backlog);

SOCKFD is the socket descriptor returned by the socket system call;

Backlog Specifies the maximum number of requests allowed in the request queue, with a default value of 20.

Return: Success = 0; failure =-1,errno= error number.

5.accept:

Accept a request from a customer

int accept (int sockfd, void *addr, int *addrlen);

The SOCKFD is a listening socket descriptor,

Addr is a pointer to the SOCKADDR_IN variable, which holds the client's host information;

Addrten An integer pointer variable that points to a sizeof (struct sockaddr_in) value.

Return: A new socket descriptor was successfully returned for use by this new connection. Returns one-1 when an error occurs and sets the corresponding errno value.

6.Send:

Sending information in the connection (TCP) socket mode

int send (int sockfd, const void *msg, int len, int flags);

SOCKFD is the socket descriptor used to transmit data

MSG is a pointer to the data you want to send.

Len is the length of the data in bytes.

Flags are normally placed at 0.

7.RECV:

Receive data in the connection (TCP) socket mode

int recv (int sockfd,void *buf,int len,unsigned int flags);

SOCKFD is the socket descriptor that accepts data;

The BUF is a buffer that holds the receiving data;

Len is the length of the buffer.

The flags were also set to 0.

Returns: the number of bytes actually received, if the connection is aborted, returns 0. When an error occurs, return-1 and place the corresponding errno value.

8.sendto:

Send data in a connectionless (UDP) socket mode

int sendto (int sockfd, const void *msg,int len,unsigned int flags,const struct sockaddr *to, int tolen);

To represents the IP address and port number information of the target machine

tolen=sizeof (struct sockaddr).

Returns: The length of the data byte actually sent or the return of-1 when a send error occurs.

9.Recvfrom ()

Receive data in connectionless (UDP) socket mode

int recvfrom (int sockfd,void *buf,int len,unsigned int flags,struct sockaddr *from,int);

From Save the IP address and port number of the source machine.

fromlen=sizeof (struct sockaddr).

Return: The number of bytes of data actually deposited in from. Returns-1 when an error occurs and the corresponding errno is placed.

10.close ()

Release socket, stop any data operation

Close (SOCKFD);

11.shutdown:

One-way close connection

int shutdown (int sockfd,int how);

How can be set to the following values:

0-------is not allowed to continue receiving data

·1-------is not allowed to continue sending data

2-------does not allow you to continue sending and receiving data, all is allowed to call Close ()

Shutdown returns 0 when the operation succeeds, and returns 1 (and the corresponding errno) when an error occurs.

gethostbyname:

Conversion of domain name and IP address

struct hostent *gethostbyname (const char *name);

13.inet_pton function:

Converts a dotted decimal string into a network byte-order binary value that can be processed for both the IPV4 address and the IPV6 address.

int Inet_pton (int family,const char * strptr,void * addrptr);

The first argument can be Af_inet or Af_inet6: The second argument is a pointer to the dotted decimal string: The third parameter is a pointer to a binary value that points to the converted network byte order.

Returned: 1---Success 0---input is not a valid expression format-1---Failed

14.inet_ntop function:

In contrast to the Inet_pton function, the Inet_ntop function converts a network byte-order binary value into a dotted decimal string.

const char * inet_ntop (int family,const void * Addrptr,char * strptr,size_t len);

The first parameter can be af_inet or AF_INET6: The second parameter is a pointer to a binary value of the network byte order; The third parameter is a pointer to the converted dotted decimal string, and the fourth parameter is the size of the target, lest the function overflow its caller's buffer.

Return: Pointer to result---succeeded NULL---failed

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.