The 1th chapter of Network Programming Fundamentals (2)--socket programming principle

Source: Internet
Author: User
Tags htons

Socket Programming Principle

A socket is an abstraction of the endpoint of a network communication that provides a mechanism for sending and receiving data.

    • Stream Sockets (Sock_stream): bidirectional, ordered, no duplicates, and no record boundaries
    • Datagram Sockets (SOCK_DGRAM): bidirectional, preserving record boundaries

Connection-oriented operations are less efficient than non-connected operations, but the data is more secure.

Socket Communication Process

IP Address flag host, port number flag process, IP plus port number to determine connection destination.

One network connection requires the following 5 kinds of information:

    1. Local protocol port: Indicates the process of receiving a message or data.
    2. Local Host Address: Indicates the host on which the packet was received.
    3. Remote protocol port: Indicates the destination process or form.
    4. Remote Host Address: Indicates the destination host.
    5. Protocol: The protocol used to indicate when a program transmits data over a network.
Socket function (Winsock)

1.Socket: Used to create a socket socket.

socket Socket (int af,          // the protocol family    used int type,        //socket type int Protocol     // protocol address used ) ;

The socket protocol family is represented as an integer in the computer and can be valued af_inet

There are two types of sockets: Sock_stream and Sock_dgram represent stream sockets and datagram sockets

If the function succeeds, returns a socket descriptor, otherwise, returns Invalid_socket.

Socket s = socket (Af_inet,sock_stream,0);

2.Connect: Used to attempt to establish a socket connection with the remote.

int    Connect (socket s,                          //Socket    Descriptor conststruct sockaddr* name, // the address of the remote int Namelen                        // length of the remote address );        

The remote address is a SOCKADDR structure.

struct sockaddr_in ( short sin_family,                                 // Socket Family u_short sin_port,                                 // port struct in_addr sin_addr,/                          / IP Address Char sin_zero[8]                                  // structure length );                                    

function returns 0 if the connection succeeds, otherwise returns SOCKET_ERROR. For a non-blocking mode socket connection, the returned result is usually socket_error, and the error code is Wsaewouldblock, which indicates that the connection is in progress, not a real error.

Establishing a connection is typically a client making a connection request:

SOCKET S; Sockaddr_in serveraddr; serveraddr.sin_family=af_inet; Serveraddr.sin_port=htons (port); ServerAddr.sin_addr.s_addr=inte_addr ("127.0.0.1"); Connect (s, (sockaddr *) &serveraddr,sizeof(serveraddr));

3.Send: Used to send data to the far end on a socket

int Send (socket s,  //    socket Socket Constchar// buffer to store send data 
    int len,  // data length to be sent int// additional parameters used when sending );

If the send succeeds, the return value is the number of bytes sent successfully, otherwise socket_error is returned.

4.RECV: corresponding to the sending data is to receive data, function RECV for the receiving end of the data sent, the function prototype is:

int recv (socket s,      //socket Socket Char* buf,     // buffer    to store received data)  int len,       // data length to be received int flags      //Receive  Additional parameters when used );

The received data succeeds, the function returns the number of bytes received, otherwise, returns SOCKET_ERROR.

5.Closesocket: Used to close sockets that are no longer needed

int        closesocket (SOCKET s;  //socket    socket);

Closes successfully, returns 0, otherwise returns SOCKET_ERROR.

6.Listen: Used to establish a listener on a socket

int Listen (socket s,      //socket Socket int backlog    // Cache Queue Length ) ;

Returns 0 if the listener is set up successfully; Socket_reeor

Backlog parameter. Set to Somaxconn, which represents the maximum value of the system connection.

7.Accept: Used to receive a new connection.

socket (socket s),/ /socketstruct sockaddr* addr in the Listener,//  Pointer int* Addrlen// address structure body length ) representing the address structure;

The function executes successfully, returns 0; otherwise, returns SOCKET_ERROR.

8.Bind: Used to assign a local protocol address to a socket socket

int bind (socket s,//socket Socket conststruct socketaddr* name,// pointer representing the address structure body int Namelen// address structure body length );

The function executes successfully, returns 0; otherwise, returns SOCKET_ERROR.

9.Select: Used to detect socket state, mainly used for advanced network communication model

int Select (int Nfds,///WINSOCJ This parameter is meaningless fd_set* Readfds,//  Socketfd_set* Writefds for readable detection,// socketfd_set* Exceptfds for writable detection, // socket for anomaly detection Const struct timeval* timeout// non-blocking mode to set the maximum wait time );

The function executes successfully, returns 0; otherwise, returns SOCKET_ERROR.

IP Address Translation
    • unsigned integer: 127.0.0.1
    • ASCII address: "127.0.0.1"
    • Domain name: localhost

ASCII address, Integer address

#include <arpa/inet.h>int Inet_aton (constChar* straddr,struct in_addr* ADRP);

Returns: 0 indicates that the conversion was unsuccessful; 1 indicates a successful conversion.

Integer address->ascii Address

#include <arpa/inet.h>char *inet_ntoa (struct in_addr inaddr);

return: null the programmatic conversion was unsuccessful, and the other return value indicates a successful conversion.

Domain address, integer address

#include <netdb.h>struct hostent *gethostname (constchar *name);

Integer address, domain name address

#include <netdb.h>struct hostent *gethostbyaddr (constchar *addr,int len, int family);

BYTE conversion

Format of storage bytes:

    • Network byte order: High byte in front (Big Endian)
    • Native byte order: low byte in front (Little Endian)

Function naming law:

h represents the byte order (native order), and N represents the network order (networks)

// Local bytes converted to network byte order (Long Integer) u_long PASCAL far htonl (in U_long hostlong); // Local bytes converted to network byte order (short integer) u_short PASCAL far htons (in U_short hostshort); // Network bytes converted to local byte order (Long Integer) u_long PASCAL far Ntohl (in U_long netlong); // Network bytes converted to local byte order (short integer)u_short PASCAL far ntohs (in U_short netshort);

The 1th chapter of Network Programming Fundamentals (2)--socket programming principle

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.