Socket network Extraction

Source: Internet
Author: User
Tags htons

I. Basic socket Functions
In Linux, network programming is performed by providing sockets. Network socket data transmission is a special type of I/O, and socket is also a file descriptor. Socket also has
Open File function: socket (), call socket (), this function returns an integer socket descriptor, subsequent connection establishment, data transmission and other operations are also implemented through this socket.
1. Socket Functions
Syntax:
Int socket (INT domain, inttype, int Protocol );
Function Description:
If the call succeeds, the socket file descriptor is returned; if the call fails,-1 is returned, and errno is set.
Parameter description:
Domain indicates the protocol family used, usually pf_inet, indicating the TCP/IP protocol;
The type parameter specifies the socket type. There are basically three types: data stream socket, datagram socket, and original socket.
Protocol is usually assigned "0 ".
A network connection between two network programs includes five types of information: communication protocol, local Protocol address, local host port, remote host address, and remote protocol port. The socket data structure contains these five types of information.
2. Bind Functions
Syntax:
Int BIND (INT sock_fd, structsockaddr_in * my_addr, int addrlen );
Function Description:
Connect the socket to the specified port. 0 is returned. Otherwise,-1 is returned and errno is set.
Parameter description:
Sock_fd is the return value of the socket function,
My_addr is a sockaddr pointer that points to information such as the local IP address and port number;
The struct sockaddr_in structure type is used to save socket information:
Struct sockaddr_in {
Short int sin_family;
Unsigned short int sin_port;
Struct in_addr sin_addr;
Unsigned char sin_zero [8];
};
Addrlen is the length of sockaddr.
3. Connect Function
Syntax:
Intconnect (INT sock_fd, struct sockaddr * serv_addr, int addrlen );
Function Description:
The client sends a service request. 0 is returned. Otherwise,-1 is returned and errno is set.
Parameter description:
Sock_fd is the socket descriptor returned by the socket function; serv_addr is a pointer containing the IP address and port number of the remote host; addrlen is the length of the sockaddr_in structure.
4. Listen Function
Syntax:
Int listen (INT sock_fd, intbacklog );
Function Description:
Wait for the client connection to appear on the specified port. If the call is successful, 0 is returned. Otherwise,-1 is returned and errno is set.
Parameter description:
Sock_fd is the return value of the socket () function;
Backlog specifies the maximum number of requests allowed in the Request queue
5. accecpt Function
Syntax:
Int accept (INT sock_fd, structsockadd_in * ADDR, int addrlen );
Function Description:
This interface is used to accept service requests from the client. A new socket descriptor is returned successfully. If a socket descriptor fails,-1 is returned and errno is set.
Parameter description:
Sock_fd is the socket descriptor monitored,
ADDR is usually a pointer to the sockaddr_in variable,
Addrlen is the length of the sockaddr_in structure.
6. Write Functions
Syntax:
Ssize_twrite (int fd, const void * Buf, size_t nbytes)
Function Description:
The Write function writes the nbytes bytes in the Buf to the file descriptor FD. The number of written bytes is returned when the Buf is successful.-1 is returned if the Buf fails. The errno variable is set.
In network programs, there are two possibilities when we write to the socket file descriptor:
1) the return value of write is greater than 0, indicating that some or all data is written.
2) If the returned value is less than 0, an error occurs. You need to handle the error based on the error type.
If the error is eintr, an interruption error occurs during write.
If the error is epipe, the network connection is faulty.
7. Read Functions
Syntax:
Ssize_tread (int fd, void * Buf, size_t nbyte)
Function Description:
The READ function reads content from Fd. when the read succeeds, read returns the actual number of bytes read. If the returned value is 0, it indicates that the object has been read, and if it is smaller than 0, it indicates that an error has occurred.
If the error is eintr, it indicates that the read is caused by an interruption,
If the error is econnrest, the network connection is faulty.
8. Close Function
Syntax:
Int close (sock_fd );
Note:
After all data operations are completed, you can call the close () function to release the socket and stop any data operations on the socket:
If the function runs successfully, 0 is returned. Otherwise,-1 is returned.

Ii. Other functions of socket programming
1. Network byte sequence and its conversion functions
1) network byte sequence
Each machine has a different storage order for the variable bytes, and the data transmitted over the network must be in a unified order. Therefore, machines with different internal bytes and network bytes are represented in different order,
Data must be converted. In terms of program portability requirements, the data conversion function should be called before data transmission, even if the internal byte representation sequence of the local machine is the same as the network byte sequence,
So that the program can be correctly executed after being transplanted to other machines. Whether the conversion is true or not depends on the system function.
2) related conversion functions
* Unsigned short int htons (unsigned short int hostshort ):
The host bytes are converted to the network byte order, and the unsigned short type is operated by 4 bytes.
* Unsigned long int htonl (unsigned long int hostlong ):
Host bytes are converted to network bytes in sequence, and 8 bytes are operated on the unsigned long type.
* Unsigned short int ntohs (unsigned short int netshort ):
The Network bytes are converted to the host byte order, and the unsigned short type is operated by 4 bytes.
* Unsigned long int ntohl (unsigned long int netlong ):
The Network bytes are converted to the host byte sequence, and the unsigned long type is operated by 8 bytes.
Note: The above function is defined in netinet/in. h.
2. IP address conversion
There are three functions that convert string IP addresses expressed in the form of digits to binary IP addresses in the 32-bit network byte order.
(1) unsigned long int inet_addr (const char * CP): This function converts a string of IP addresses represented by numbers and points into an unsigned long integer, such as struct sockaddr_inina
Ina. sin_addr.s_addr = inet_addr ("202.206.17.101 ")
If the function is successful, the conversion result is returned. If the function fails, the constant inaddr_none is returned. The constant =-1. The unsigned integer-1 in binary is equivalent to limit 255. This is a broadcast address, therefore, when calling iner_addr () in a program, you must manually handle the call failure. Because this function cannot process broadcast addresses, you should use the inet_aton () function in the program ().
(2) int inet_aton (const char * CP, struct in_addr * indium): This function converts an IP address in string format to a binary IP address. If it succeeds, 1 is returned; otherwise, 0 is returned, the converted IP address is stored in the parameter "p.
(3) char * inet_ntoa (struct in-addrin): converts a 32-bit binary IP address to an IP address in the numerical point format. The result is returned in the return value of the function, returns a pointer to a string.
3. byte processing functions
The socket address is multi-byte data and does not end with a null character, which is different from the string in C language. Linux provides two groups of functions to process multi-byte data. One group starts with B (byte) and is compatible with the BSD system. The other group starts with MEM (memory, is a function provided by ansic.
Functions starting with B include:
(1) void bzero (void * s, INTN): sets the first n Bytes of the memory specified by parameter S to 0, which is usually used to clear the socket address 0.
(2) void bcopy (const void * SRC, void * DEST, INTN): copy the specified number of bytes from the memory area specified by the SRC parameter to the memory area specified by the Dest parameter.
(3) int bcmp (const void * S1, const void * S2, INTN): Compares the memory region specified by parameter S1 with the first n Bytes of the memory region specified by parameter S2, if the values are the same, 0 is returned. Otherwise, non-0 is returned.
Note: The prototype of the above function is defined in strings. h.
Functions starting with mem include:
(1) void * memset (void * s, int C, size_tn): set the first n Bytes of the memory area specified by parameter S to the content of parameter C.
(2) void * memcpy (void * DEST, const void * SRC, size_tn): function is the same as bcopy (), difference: function bcopy () if the regions specified by the SRC and DEST parameters overlap, memcpy () cannot.
(4) int memcmp (const void * S1, const void * S2, size_tn): Compares the content of the first n bytes in the specified region of the parameter S1 and parameter S2. if the content is the same, 0 is returned, otherwise, a non-0 value is returned.
Note: The prototype of the preceding function is defined in string. h.

Ii. Procedures
This protocol is used for communication. The server listens and sends data to the client after receiving the connection from the client. After receiving the data, the client prints the data and closes it.
1. Client. c

# Include <stdlib. h>
# Include <sys/types. h>
# Include <stdio. h>
# Include <sys/socket. h>
# Include <netinet/in. h>
# Include <string. h>

Int main ()
{
Int CFD;
Int recbytes;
Int sin_size;
Charbuffer [1024] = {0 };
Struct sockaddr_in s_add, c_add;
Unsigned short portnum = 0x8888;

Printf ("Hello, welcome to client! \ R \ n ");

CFD = socket (af_inet, sock_stream, 0 );
If (-1 = CFD)
{
Printf ("socket fail! \ R \ n ");
Return-1;
}
Printf ("socket OK! \ R \ n ");

Bzero (& s_add, sizeof (struct sockaddr_in ));
S_add.sin_family = af_inet;
S_add.sin_addr.s_addr = inet_addr ("192.168.1.2 ");
S_add.sin_port = htons (portnum );
Printf ("s_addr =%# X, Port: % # x \ r \ n", s_add.sin_addr.s_addr, s_add.sin_port );


If (-1 = connect (CFD, (struct sockaddr *) (& s_add), sizeof (struct sockaddr )))
{
Printf ("Connect fail! \ R \ n ");
Return-1;
}
Printf ("Connect OK! \ R \ n ");

If (-1 = (recbytes = read (CFD, buffer, 1024 )))
{
Printf ("readdata fail! \ R \ n ");
Return-1;
}
Printf ("read OK \ r \ nrec: \ r \ n ");

Buffer [recbytes] = '\ 0 ';
Printf ("% s \ r \ n", buffer );

Getchar ();
Close (CFD );
Return 0;
}
2. server. c

# Include <stdlib. h>
# Include <sys/types. h>
# Include <stdio. h>
# Include <sys/socket. h>
# Include <netinet/in. h>
# Include <string. h>

Int main ()
{
Int SFP, NFP;
Struct sockaddr_in s_add, c_add;
Int sin_size;
Unsigned short portnum = 0x8888;

Printf ("Hello, welcome to my server! \ R \ n ");
SFP = socket (af_inet, sock_stream, 0 );
If (-1 = SFP)
{
Printf ("socket fail! \ R \ n ");
Return-1;
}
Printf ("socket OK! \ R \ n ");


Bzero (& s_add, sizeof (struct sockaddr_in ));
S_add.sin_family = af_inet;
S_add.sin_addr.s_addr = htonl (inaddr_any );
S_add.sin_port = htons (portnum );

If (-1 = BIND (SFP, (struct sockaddr *) (& s_add), sizeof (struct sockaddr )))
{
Printf ("bindfail! \ R \ n ");
Return-1;
}
Printf ("bind OK! \ R \ n ");

If (-1 = listen (SFP, 5 ))
{
Printf ("Listen fail! \ R \ n ");
Return-1;
}
Printf ("Listen OK \ r \ n ");

While (1)
{
Sin_size = sizeof (struct sockaddr_in );

Nfp = accept (SFP, (struct sockaddr *) (& c_add), & sin_size );
If (-1 = NFP)
{
Printf ("Accept fail! \ R \ n ");
Return-1;
}
Printf ("Accept OK! \ R \ nserver start get connect from % # X: % # x \ r \ n ", ntohl (c_add.sin_addr.s_addr), ntohs (c_add.sin_port ));


If (-1 = write (nfp, "Hello, welcome to my server \ r \ n", 32 ))
{
Printf ("Write fail! \ R \ n ");
Return-1;
}
Printf ("Write OK! \ R \ n ");
Close (NFP );

}
Close (SFP );
Return 0;
}

In cygwin, the GCC command is compiled as follows:
Gcc-O Server server. c
Gcc-O client. c
Then run the program:
./Server
./Client

Server:
Hello, welcome to my server!
Socket OK!
Bind OK!
Listen OK
Accept OK!
Server start get connect from 0xc0a80102: 0xc927
Write OK!
The client performs the following operations:
Hello, welcome to client!
Socket OK!
S_addr = 0x201a8c0, Port: 0x8888
Connect OK!
Read OK
REC:
Hello, welcome to my server

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.