Linux Network Programming-socket (socket) Primer

Source: Internet
Author: User
Tags set socket stub

1. basic structure of sockets

struct SOCKADDR

This structure is used to store socket addresses.

Data definition:

struct SOCKADDR {

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

Char sa_data[14]; /* Protocol address for bytes */

};

Sa_family in general, are "afinet".

Sa_data contains the number of addresses, ports, and sockets for some remote computers, and the data inside it is mixed in one cut.

To deal with Struct sockaddr, the programmer builds another similar struct sockaddr_in:

struct sockaddr_in ("in" stands for "Internet")

struct SOCKADDR_IN {

short int sin_family; /* Internet address family */

unsigned short int sin_port; /* Port number */

struct IN_ADDR sin_addr; /* Internet address */

unsigned char sin_zero[8]; /* Add 0 (same size as struct sockaddr) */

};

This structure provides a convenient means to access each element in the socket address (struct SOCKADDR) structure

2. List of socket byte converters:

L htons ()--"host to network short" hosts byte order converted to net byte order (operation on unsigned stub 4 bytes)

L htonl ()--"host to Network Long" hosts byte order converted to net byte order (operation on unsigned long type 8 bytes)

L Ntohs ()--"network to host short" net byte order converted to host byte order ( operation on a no-symbol stub 4 bytes)

L Ntohl ()--"network to host Long" net byte order converted to host byte order (operation on unsigned long type 8 bytes)


3. IP Address Translation

Linux system provides and many functions for converting IP addresses. First, suppose you have a struct sockaddr_in ina, and your IP is 166.111.69.52, and you want to store your IP in INA. You can use the function: Inet_addr (), which can put a table with numbers and dots

The IP address string is converted to an unsigned long integer. You can use it as follows:

INA.SIN_ADDR.S_ADDR = inet_addr ("166.111.69.52");

Attention:

L inet_addr () The address returned is already a network byte order, and you don't have to call the htonl () function again.

Conversely, if you have a struct in_addr and you want to print out the IP address it represents (in terms of numbers, numbers, formats of numbers), then you can use the function Inet_ntoa () ("Ntoa" for "Network to ASCII"), It will in_addr the network address stored in the struct to a number. number. The format of numbers.

L Inet_ntoa () uses struct in_addr as a parameter, not a long integer value.

4. Basic Socket Invocation

socket () function

Get socket descriptor The definition of the socket function is as follows:

#include

#include

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

bind () function

The bind () function helps you specify a port to use for a socket. when you use the socket () function to get a socket descriptor, you may need to bind the socket to the previous the port on the machine.

When you need to perform a port monitoring listen () operation and wait for a connection request to be accepted, this step is generally required . For example, network mud (MUD), Telnet a.b.c.d 4000.

If you just want to connect to a server, which is the Connect () operation, this step is not necessary.

The system invocation declarations for bind () are as follows:

#include

#include

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

Parameter description:

L SOCKFD is the socket descriptor returned by the socket () function.

L MY_ADDR is a pointer to a struct SOCKADDR that contains information about your address: name, port, and IP address.

L Addrlen can be set to sizeof (struct sockaddr).

Connect () function

Let's take a moment to assume that you are a telnet application. Your user commands you to create a socket descriptor. You follow the command and call the socket (). The user then tells you to connect to "166.111.69.52"

23 Port (standard Telnet port)?? What should you do?

You're lucky: The Telnet app, what you're reading now is the socket's Network Connection section:

Connect ().

The Connect () function is defined like this:

#include

#include

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

The three parameters of Connect () have the following meanings:

L SOCKFD: Socket file descriptor, returned by the socket () function.

L SERV_ADDR is a structure that stores the IP address and port information of a remote computer.

L Addrlen should be sizeof (struct sockaddr).

Listen () function

The Listen () function is a function that waits for someone else to connect and make a system listen request. When someone connects you, you have two steps to do: Wait for the connection request through the Listen () function, and then use the Accept () function to handle it. (Accept () function

described below).

The Listen () function call is very simple. The function declaration is as follows:

#include

int listen (int sockfd, int backlog);

The parameter meanings of the Listen () function are as follows:

L SOCKFD is a socket descriptor that is obtained by the socket () system call.

The backlog is the maximum number of non-processed connection request queues that can be accommodated.

What does the backlog specifically mean? Each incoming request is entered into a queue of incoming requests, and the program that waits for listen calls the Accept () function, which is described below, to receive the connection. When the system has not yet

When calling the Accept () function, if there are many connections, the maximum number of local waits is the value of the backlog . You can set it to a value between 5 and 10.

Accept () function

The function accept () is somewhat difficult to understand. When it is called, the approximate process is the following:

L have someone try to call connect () from far and far away to connect to a port on your machine (of course you are already in listen).

L His connection will be listen join the wait queue to wait for the call of the Accept () function (the maximum number of join waiting queues is determined by the second parameter backlog that calls the Listen () function).

L You call the Accept () function and tell him that you are ready to connect.

The Accept () function returns a new socket descriptor, which represents the connection! Well, at this point you have two socket descriptors, and the one returned to you is the connection to the remote computer, and

The first socket descriptor is still listen () on the original port on your machine. The new socket descriptor you get will be able to perform the send () operation and the recv () operation.

The following is the declaration of the Accept () function:

#include

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

The parameters of the Accept () function have the following meanings:

L SOCKFD is a socket descriptor that is being listen ().

L addr is generally a pointer to a struct SOCKADDR_IN structure, which stores remote connections.

Computer information (such as the IP address and port of the remote computer)

Send () , recv () function

These two functions are the most basic of the functions that communicate through a connected socket stream.

Declaration of the Send () function:

#include

#include

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

The parameters of send have the following meanings:

L SOCKFD is a socket descriptor that represents your connection to a remote program.

L MSG is a pointer to the address of the message you want to send.

L Len is the length of the message you want to send.

L Flags send tokens. Generally set to 0

The function recv () call is similar to send () in many ways, and the following is the declaration of the Recv () function:

#include

#include

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

The parameters of recv () have the following meanings:

L SOCKFD is the socket descriptor that you want to read data from.

L BUF is a pointer to the memory cache area where you can store data.

L len is the maximum size of the buffer.

L flags is a flag of the recv () function, which is generally 0 (refer to recv () for the specific other values and meanings.

Man pages).

Recv () returns the length of the data it actually receives

sendto () and Recvfrom () functions

These two functions are used for non-connected UDP traffic. With these two functions, the data is transferred on a network that has no connection established. Because the datagram socket is unable to connect to the remote host, think about our

What do you need to know before sending data? That 's right! is the IP address and port of the remote host!

The following is the declaration of the SendTo () function and the Recvfrom () function:

#include

#include

int sendto (int sockfd, const void *msg, int len, unsigned int flags,

const struct SOCKADDR *to, int tolen);

As you can see, this function is basically the same as the Send () function.

L SOCKFD is a socket descriptor that represents your connection to a remote program.

L MSG is a pointer to the address of the message you want to send.

L Len is the length of the message you want to send.

L Flags send tokens. is generally set to 0. (You can view the man pages of Send to get additional parameter values and understand what each parameter means)

l to is a pointer to a struct SOCKADDR structure that contains the IP address and port data of the remote host .

L Tolen just indicates the size of the struct sockaddr in memory sizeof (struct sockaddr). like Send (), sendto () returns the number of bytes it really sends (as well as Send (), which is really

The number of bytes sent may be less than the number of bytes of data you have given it. When the error occurs, it also returns –1, and the global variable errno stores the error code. Similarly, the recv () function and the recvfrom () function are basically identical.

The declaration of Recvfrom () is:

#include

-156-linux Network programming

#include

int recvfrom (int sockfd, void *buf, int len, unsigned int flags

struct sockaddr *from, int *fromlen);

The parameters have the following meanings:

L SOCKFD is the socket descriptor that you want to read data from.

L BUF is a pointer to the memory cache area where you can store data.

L len is the maximum size of the buffer.

L flags is a flag of the recv () function, which is generally 0 (refer to recv () for the specific other values and meanings.

Man pages).

L from is a local pointer to a struct SOCKADDR structure (which contains the source IP address and the end

Number of ports).

L Fromlen is a pointer to an int data, and its size should be sizeof (struct sockaddr). When the function returns, the data that Formlen points to is the actual sockaddr of the struct that the form points to.

Size

Recvfrom () returns the number of bytes it receives, and if an error occurs, it returns-1

Close () and Shutdown () functions

After the program has been transferred to the network, you need to close the connection represented by this socket descriptor. To implement this non- trivial, just use the standard shutdown file function:
Close (). How to use:

Close (SOCKFD);

After close () is executed, the socket will not be allowed to read and write operations. Any operation that reads and writes to the socket descriptor will receive an error.

If you want to further the closure of a network socket, you can use the function shutdown (). It allows you to do a one-way shutdown or disable it all.

The declaration of Shutdown () is:

#include

int shutdown (int sockfd, int how);

Its parameters have the following meanings:

L SOCKFD is a socket descriptor that you want to close.

L How can I take the following values? 0 indicates that subsequent data reception is not allowed, 1 indicates that subsequent data is not allowed to be sent, and 2 means that no subsequent operations (including receiving, sending data) are allowed, as with close ()

Shutdown () If the execution succeeds returns 0, if an error occurs during the call, it returns –1, and the error code is stored in the full-board variable errno.

If you use the shutdown () function on an disconnected datagram socket (remember that you can connect () to datagram socket UDP? ), it will do nothing.

setsockopt () and GetSockOpt () functions

The socket library provided by Linux contains an error (bug). This error manifests as you cannot enable the same port number for a socket re- new, even after you gracefully close the socket. For example, say, you write a service

The program that waits on a socket. It is no problem for the server to open the socket and listen on it. In any case, there are always some reasons (whether normal or abnormal) to make your program need to be restarted. However , restart

You can't bind it to the original port after you move it. The error code returned from the bind () system call always reports that the port you are trying to connect to is already bound by another process.

The problem is that the Linux kernel never marks a port as unused after the end of a bound socket process. In most Linux/unix systems, the port can be reused by a process and can even be used by other processes.

The way to circumvent this problem in Linux is to set an option on it with the setsockopt () system call when the socket is open but not yet connected. SetSockOpt () Call Set options and getsockopt ()

Gets the option from the given socket.

Here is the syntax for these calls:

#include

#include

int getsockopt (int sockfd, int level, int name, char *value, int *optlen);

int setsockopt (int sockfd, int level, int name, char *value, int *optlen);

The following is a description of the parameters of the two calls:

L SOCKFD must be an open socket.

The level is the protocol standard used by the function (protocol level) (the TCP/IP protocol uses the IPPROTO_TCP, socket standard option utility Sol_socket).

The L name option is described in detail in the Socket Specification (man page).

L value points to the value obtained for the getsockopt () function, the address of the value set by the setsockopt () function.

The L Optlen pointer points to an integer that contains the length of the argument in bytes.

Now let's go back to the Linux bug. When you open a socket, you must also call the setsockopt () function with the following code snippet:

/* Set parameter values */

opt = 1; len = sizeof (opt);

/* Set SOCKET Properties */

SetSockOpt (Sockfd,sol_socket,so_reuseaddr,&opt,&len);

getpeername () function

This function can obtain a remote information (such as an IP address and port) of a socket that is already connected, telling you who is connecting to you remotely.

It is declared as:

#include

int getpeername (int sockfd, struct sockaddr *addr, int *addrlen);

Here is the parameter description:

L SOCKFD is the socket descriptor for which you want to obtain remote information.

L addr is a pointer to a struct sockaddr (or struct sockaddr_in).

L Addrlen is a pointer to int, which should be assigned to the size of sizeof (struct sockaddr).

If an error occurs during the execution of the function, the function returns –1, and the error code is stored in the global variable errno. When you have the IP address of a remote connected user, you can use Inet_ntoa () or gethostbyaddr () to lose

Information or to do further processing.

gethostname () function

The GetHostName () function can obtain information about the local host. It is easier to use than getpeername (). it returns the name of the computer that is executing it. The name returned can be used by the gethostbyname () function,

This allows you to obtain the IP address of the local host.

The following is its declaration:

#include

int GetHostName (char *hostname, size_t size);

The parameters are described as follows:

l hostname is a pointer to a character array, and when the function returns, the data inside it is the

The host name of the ground.

L size is the length of the array that hostname points to.

If the function executes successfully, it returns 0, and if an error occurs, it returns –1, and the global variable errno is stored in the wrong

Error code.

Read (32) | Comments (0) | Forwards (0) |0

Previous: SSH Framework consolidation Example

Next post: Samba porting to Android process

Related Popular articles
    • SOFTROCE/RDMA Installation and testing ...
    • SSH connection to Linux is maintained and reused ...
    • Welcome to Linuxsocket in Chinaunix bo ...
    • Strongswan Linux kernel configuration ...
    • Welcome to Socketmould in Chinaunix bo ...
    • Common Linux Service ports
    • Xmanager 2.0 for Linux configuration
    • "Rootfs build" BusyBox httpd ...
    • OpenWrt in Luci study notes
    • What is a shell?
    • Linux DHCP Peizhi ROC
    • Soft links to Unix files
    • What does this command mean, I'm new ...
    • What does sed-e "/grep/d" mean ...
    • Who can help me solve Linux 2.6 10 ...
Leave something to the owner! ~~ Comment on the hot topic

Linux Network Programming-socket (socket) Primer

Related Article

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.