TCP programming functions and procedures

Source: Internet
Author: User

TCP ProgrammingServerThe general procedure is

1. Create a socket and use the function socket ();

2. Set the socket property. Use the setsockopt () function. * optional.

3. Bind the IP address, port, and other information to the socket, and use the function BIND ();

4. Enable the listener and use the listen () function ();

5. Use the accept () function to receive connections from the client ();

6. send and receive data. Use the send () and Recv () functions to read () and write ();

7. disable network connections;

8. Disable the listener;

TCP ProgrammingClientThe general steps are as follows:

1. Create a socket and use the function socket ();

2. Set the socket property. Use the setsockopt () function. * optional.

3. Bind the IP address, port, and other information to the socket. Use the BIND function (). * optional

4. Set the IP address and port of the Peer to be connected;

5. Connect to the server and use the function connect ();

6. send and receive data using the send () and Recv () functions, or read () and write () functions ();

7. disable network connections;

The general steps for UDP programming on the server side are:

1. Create a socket and use the function socket ();

2. Set the socket property. Use the setsockopt () function. * optional.

3. Bind the IP address, port, and other information to the socket, and use the function BIND ()

4. receive data cyclically. Use the recvfrom () function ();

5. disable network connections;

UDP ProgrammingClientThe general steps are as follows:

1. Create a socket and use the function socket ();

2. Set the socket property. Use the setsockopt () function. * optional.

3. Bind the IP address, port, and other information to the socket. Use the BIND function (). * optional

4. Set attributes such as the IP address and port of the peer;

5. Send data using the sendto () function ();

6. Disable the network connection;

common network commands:
netstat
command netstat is used to display network connections , network information such as route table and interface Statistics . netstat many options are commonly used: -An used to display the detailed network status . other options can be used for help.

Telnet
TelnetIs a remote controlProgram,However, we can use this program to debug our server program..For example, our server program is listening8888Port,We can useTelnet local host 8888To view the status of the server.

Data Structure
1 , Address Structure
Struct sockaddr_in {
Short int sin_family ;/* The address family is generally 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 Struct sockaddr Use the same size Memset () Or Bzero () To fill */
};

Struct sockaddr {
Unsigned short sa_family ;/*Address Family,Af_xxx */
Char sa_data [14];/* 14Byte Protocol address*/

};

2 , DNS Structure
Struct hostent {
Char * h_name ;/* Host Domain Name */
Char ** h_aliases ;/* A Null Host alias array at the end */
Int h_addrtype ;/*The type of the returned address, in Internet Environment is AF-INET */
Int h_length ;/* Length of the address in bytes */
Char ** h_addr_list ;/* A 0 Array at the end of the host, containing all the addresses of the host */
};

Operation Functions

1. Socket:

CreateSocketDescriptor

Int socket (INT domain, int type, int Protocol );
Domain = Af_inet , Socket Type, Type = Sock_stream Or Sock_dgram , Indicating TCP Connection and UDP Connection; Protocol = 0 .

Returns an integer.SocketDescriptor.

 
2. BIND:

SetSocketDescriptor is associated with a port on your local machine (for servers only)

Int BIND (INT sockfd, struct sockaddr * my_addr, int addrlen );

SockfdIs Socket Descriptor
My_addr Is a point to include a Local Machine IP Address, port number, and other information Sockaddr Type pointer ;
Addrlen = Sizeof (struct sockaddr) .
Return Value: Success = 0 ; Failed = -1 , Errno = Error code.
You can use the following assignment to automatically obtain the local machine. IP Address and random access to an unused Port Number:
My_addr.sin_port = 0 ;/* The system randomly selects an unused port number. */
My_addr.sin_addr.s_addr = inaddr_any ;/* Enter the Local Machine IP Address */

3. Connect:

CreateTCPConnection (for client)
Int connect (INT sockfd, struct sockaddr * serv_addr, int addrlen );
SockfdTarget ServerSocktDescriptor
Serv_addrIs containing the target machineIPThe pointer to the address and port number.
Return Value: Success =0; Failed =-1,Errno= Error code.

4 , listen :

whether the listener has service requests, used for BIND () later
int listen (INT sockfd , int backlog );
sockfd Yes socket returned by a system call socket descriptor;
backlog specify the maximum number of requests allowed in the Request queue, the default value is 20 .
return value: Success = 0 ; failed = -1 , errno = error code.

5. Accept :

accept requests from customers
int accept (INT sockfd, void * ADDR, int * addrlen);
sockfd monitored socket descriptor,
ADDR Yes sockaddr_in variable pointer, which stores information about the client host.
addrten point to sizeof (struct sockaddr_in) integer pointer variable.
return: A New socket descriptor for this new connection. An -1 and set the corresponding errno value.

6. Send:

In Connection(TCP)OfSend messages in Socket mode
Int send (INT sockfd, const void * MSG, int Len, int flags );
SockfdIs used to transmit dataSocketDescriptor
MSGIs a pointer to the data to be sent.
LenThe length of data in bytes.
FlagsUsually set0.

7. Recv:

In Connection(TCP)OfReceive data in Socket mode

Int Recv (INT sockfd, void * Buf, int Len, unsigned int flags );
SockfdAccept dataSocketDescriptor;
BufIs the buffer zone for storing received data;
LenIs the buffer length.
FlagsAlso set0.
Return: the number of actually received bytes. If the connection is terminated, return0,.If an error occurs-1AndErrnoValue.

8. sendto:

In the connectionless(UDP)OfSocketMethod to send data
Int sendto (INT sockfd, const void * MSG, int Len, unsigned int flags, const struct sockaddr * To, int tolen );
ToIndicatesIPAddress and port number information
Tolen = sizeof (struct sockaddr).
Return: the length of data bytes actually sent or returned when a sending error occurs.-1.

9. recvfrom ()

(UDP) socket method to receive data
int recvfrom (INT sockfd, void * Buf, int Len, unsigned int flags, struct sockaddr * From, int * fromlen );
from Save the source machine Ip address and port number.
fromlen = sizeof (struct sockaddr) .
return: actually saved to from the number of data bytes. If an error occurs, -1 , and errno .

10. Close ()

ReleaseSocketTo stop any data operations.
Close (sockfd );

11. Shutdown:

One-way close connection
Int Shutdown (INT sockfd, int how );
HowIt can be set to the following values:
· 0 -------You are not allowed to continue receiving data.
· 1 -------Data cannot be sent again.
· 2 -------No data can be sent or received.Close ()
ShutdownReturn if the operation is successful0, Returns an error when an error occurs.-1(SameErrno).

12. gethostbyname:

Domain Name andIPAddress Conversion
Struct hostent * gethostbyname (const char * Name );

13. inet_ptonFunction:

Converts a dot-decimal string to a binary value in the byte sequence of the network.IPv4Address andIPv6All addresses can be processed.
Int inet_ton (INT family, const char * strptr, void * addrptr );

The first parameter can beAf_inetOrAf_inet6: The second parameter is a pointer to the dot-decimal string. The third parameter is a pointer to the binary value of the converted network in the byte sequence.
Return Value:1--- Success0--- The input is not a valid expression format.-1--- Failed

14. inet_ntopFunction:

AndInet_ptonThe opposite is true for functions,Inet_ntopThe function is to convert the binary values in the byte sequence of the network to a dotted-decimal string.
Const char * inet_ntop (INT family, const void * addrptr, char * strptr, size_t Len );

The first parameter can beAf_inetOrAf_inet6: The second parameter is a pointer to the binary value in the byte sequence of the network. The third parameter is a pointer to the converted dot-decimal string. The fourth parameter is the target size, to avoid function overflow from the caller's buffer.
Return: pointer to the result --- successNull--- Failed

Transferred from:

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.