Basic TCP Set Interface programming (http://www.fanqiang.com) __ Programming

Source: Internet
Author: User
Tags new set
Basic TCP set interface programming a
This article originates from: Http://sunsland.top263.net Author: (2001-10-22-12:00:00)

Overview

Socket ()--Gets the file descriptor.

Bind ()--which port we are on.

Connect ()--hello.

Listen ()-Did someone call me?

Accept ()--"Thank for calling Port 3490."

Send () and recv ()--talk to me, baby!

SendTo () and Recvfrom ()--talk to me, Dgram-style

Close () and shutdown ()--fuck off.

Getpeername ()-who are you?

GetHostName ()--who I am.

DNS--You say "White House", I Say "198.137.240.100" socket function

Features: Specifying protocol types

Defined:
#include <sys/types.h>
#include <sys/socket.h>
int socket (int family, int type, int protocol);

return value

Error:-1
Success: Set interface Descriptor (socket file descriptor) (socket) SOCKFD

The socket function specifies the protocol family (IPV4, IPv6, or Unix) and the Set interface type (byte stream, datagram, or original

Initial socket interface). However, there is no local protocol address or remote protocol address specified.

Understanding sockets

The way the socket uses the Unix file descriptor (file descriptor) and other programs to communicate.

When Unix programs perform any form of I/O, the program is reading or writing a file descriptor.

A file descriptor is just an integer associated with an open file.

This file may be a network connection, FIFO, pipe, terminal, file on disk or whatever else

of things. All the things in Unix are files. So, when you communicate with other programs on the Internet,

To be through a file descriptor. Use the system call socket () to get the file descriptor for network traffic. He returned

Set interface Descriptor (socket descriptor), and then call Send () and recv () through him.

So why not use the general call read () and write () to communicate through a socket interface.

The simple answer is: You can use a generic function.

The detailed answer is: Use Send () and recv () to allow you to better control the data transfer. Connect function

Function: Establish a connection to the TCP server

Defined:

#include <sys/types.h>
#include <sys/socket.h>

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

SOCKFD is the set interface file descriptor returned by the system call socket ()

SERV_ADDR is the data structure that holds the destination port and IP address struct SOCKADDR

Addrlen set to sizeof (struct sockaddr)

The three-way handshake process of connect excitation TCP

The server must be ready to accept foreign connections.

This is done by calling the Socket,bind and 1isten functions, called passive-open (passive open)

The client opens actively (active OPN) by calling Connect.

This causes client TCP to send a SYN section (indicating synchronization), which tells the server that the customer will be in (to be established)

The initial serial number of the data sent in the connection.

The server must acknowledge the customer's SYN and send a SYN section to it that contains the server

The firmware sequence number of the data sent in the same connection. The server sends SYN to the customer in a single section and to the customer

SYN's ACK. The customer must confirm the SYN for the server.

return when connect error

Cause of error: No SYN response received (server timeout, 75s)

return value: Etimedout

Client output: Connection time out.

Cause of error: Received RST response (Hard error) SYN arrives at the server, but the server does not have this port service

return value: Econnrefuse

Client output: Connection refused

Cause of Error: ICMP error: Soft error (Destination unreachable)

return value: Ehostunreach

Client output: Enetunreach No route to host bind function

Function: Assign a local protocol address to the socket interface

Defined:

#include <sys/types.h>
#include <sys/socket.h>

int bind (int sockfd, const struct SOCKADDR *my_addr, int addrlen);

SOCKFD is the file descriptor returned by calling the socket.

MY_ADDR is a pointer to the data structure struct sockaddr, which holds the address (that is, port and IP address) information.

Addrlen is set to sizeof (struct sockaddr).

Back: 0-Success,-1---Error

Let the kernel process address IP and port ports automatically

My_addr.sin_port = 0; /* Choose a unused port at random * *
MY_ADDR.SIN_ADDR.S_ADDR = Inaddr_any; /* Use I IP address * *

Bind () Select the appropriate port yourself: Assign 0 to My_addr.sin_por.

Automatically fill in the IP address of the machine on which he is running: my_addr.sin_addr.s_addr set to Inaddr_any.
Listen function

Function: Converts a disconnected active socket interface into a passive sleeve interface, indicating that the kernel accepts a connection request to that socket interface.

CLOSED--? LISTEN

Defined:

#include <sys/socket.h>

int listen (int sockfd, int backlog);

SOCKFD is the set interface file descriptor returned by calling the socket ().

Backlog is the number of connections allowed in the Enter queue.

Two queues for a listening sleeve interface

Connection queue not completed (incompleted connection queue): SYN_RECV

Completed connection queue (completed connection queue): Established

When a client's SYN arrives, as both queues are full, TCP ignores the section and does not send the RST ACCEPT function

Function: Returns the next completed connection at the completed queue header

Defined

#include <sys/socket.h>

int accept (int sockfd, struct sockaddr *cliaddr, int* Addrlen);

When the call succeeds, it returns: 1. CLIADDR: The protocol address and address size of the client process is 2. New set of interface descriptors

(Connected set interface Descriptor)

Listener Sleeve Interface Descriptor listening Socket descriptor

A given server often generates only one listener socket and persists until the server is shut down.

Connection sleeve Interface Descriptor connected Socket descriptor

The kernel creates a connected set of interfaces for each accepted client connection. When the server completes a customer's service,

Closes the connected sleeve interface.

Ports under 1024: Superuser uses the fork function

Function: Derive new process

Defined:
#include <sys/unistd.h>

pid_t fork (void);

Returns 0 in a subprocess, returning the process ID of the child process in the parent process

Returns –1 when an error occurs, called once two times

Typical applications of fork:

1. A process can create a copy of itself. When a copy handles an operation, other copies can be

Perform other tasks. This is a very typical network server.

2. A process wants to execute other programs, because the only way to create a new process is to invoke fork, which first

Call fork to generate a copy, and then one copy (usually a subprocess) invokes exec to replace itself

To execute the new program.
(http://www.fanqiang.com)

--------------------------------------------------------------------------------------------------------------- --------------

--------------------------------------------------------------------------------------------------------------- --------------

Concurrent Server

Iteration Server iterative Server single process

Concurrent Server Concurrent Server multi-process

When the connection is established, accept returns, the server invokes the fork

The child processes provide services to the customer (through CONNFD have been connected to the sleeve interface),

The parent process waits for another connection (through the LISTENFD Listener sleeve interface).

When a child process starts processing a new customer, the parent process closes the connected sleeve interface.

Each file or set interface has an access count that is maintained in a file table entry that represents the current

The number of open descriptive words to the file or socket interface.

When returned from sock, the file table entry count value associated with LISTENFD is 1.

When returned from accept, the access count value of the file table entry associated with CONNFD is also 1.

When Fork returns, two descriptors are shared between the parent process and the subprocess (duplicated) and two sockets

The access count values for the file table entries are 2.

When the parent process closes CONNFD, only the access count value is reduced from 2 to 1. The descriptive word only reaches 0 o'clock when the access count value is reached

is actually closed, which is encountered when the child process closes CONNFD at some point in the following time.
Close function

Function: Put the socket on the "closed tag" and immediately return to the process.

The access counter for the socket descriptor is reduced by 1.

When the access counter value is 0 o'clock, a TCP four packet connection termination sequence is thrown, shutting down the socket interface.

Defined:
#include <sys/unistd.h>
int close (int sockfd);
getsockname and Getpeername functions

Function:

GetSockName: Return to local protocol address

Getpeername: Return to remote Protocol address

Defined:

#include <sys/unistd.h>

int getsockname (int sockfd, struct sockaddr *localaddr, int *addrlen);
int getpeername (int sockfd, struct sockaddr *peeraddr, int *addrlen); An example program:

#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#define MYPORT 3490/* The port users would be connecting to/*
#define BACKLOG/* How many pending connections queue would hold * *
Main ()
{
int SOCKFD, NEW_FD; /* Listen on SOCK_FD, new connection on NEW_FD * *
struct sockaddr_in my_addr; /* My Address information * *
struct sockaddr_in their_addr; /* connector ' s address information * *
int sin_size;
SOCKFD = socket (af_inet, sock_stream, 0); /* Do some error checking! */
my_addr.sin_family = af_inet; /* Host byte order * *
My_addr.sin_port = htons (MyPort); /* short, network byte order * *
MY_ADDR.SIN_ADDR.S_ADDR = Inaddr_any; /* Auto-fill with my IP */
Bzero (& (My_addr.sin_zero), 8); /* Zero the rest of the struct * *
/* don ' t forget your error checking for calls: *
Bind (SOCKFD, (struct sockaddr *) &my_addr, sizeof (struct sockaddr));
Listen (SOCKFD, BACKLOG);
sin_size = sizeof (struct sockaddr_in);
NEW_FD = Accept (SOCKFD, &their_addr, &sin_size);
. . . . . . . . . . . . .


(http://www.fanqiang.com)

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.