Accept a connection at a socket .accept() yes c Network programming language is an important function ,windows The system is in #include<winsock.h> , and linux The system is in #include <sys/socket.h> in .
Foreign name
accept()
File contains
#include <sys/socket.h>
primary      type
SOCKET PASCAL accept
Return value
Failure to return -1

Expression Introduction edit

int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
Parameters
sockfd: socket descriptor , The socket is in listen() Post listening connection .
addr:( Optional ) The pointer , Point to a buffer , Where the address of the connection entity known to the communication layer is received .Addr The actual format of the parameter is determined by the address family generated when the socket is created .
addrlen:( Optional ) The pointer , Input parameters , coordination addr Use it together , Point to being addr Integer number of address length .

Example (c++) edit

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#ifndef UNICODE
     #defineUNICODE
#endif
#include <winsock2.h>
#include <stdio.h>
#include <windows.h>
//NeedtolinkwithWs2_32.lib
#pragmacomment(lib,"Ws2_32.lib")
int  wmain( void )
{
     //----------------------
     //InitializeWinsock.
     WSADATAwsaData ;
     intiResult=WSAStartup(MAKEWORD(2,2),&wsaData);
     if (iResult!=NO_ERROR)
     {
         wprintf(L  "WSAStartupfailedwitherror:%ld\n" ,iResult);
         return  1 ;
     }
     //----------------------
     //CreateaSOCKETforlisteningfor
     //incomingconnectionrequests.
     SOCKETListenSocket ;
     ListenSocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
     if (ListenSocket==INVALID_SOCKET)
     {
         wprintf(L  "socketfailedwitherror:%ld\n" ,WSAGetLastError());
         WSACleanup();
         return  1 ;
     }
     //----------------------
     //Thesockaddr_instructurespecifiestheaddressfamily,
     //IPaddress,andportforthesocketthatisbeingbound.
     sockaddr_inservice ;
     service.sin_family=AF_INET ;
     service.sin_addr.s_addr=inet_addr( "127.0.0.1" );
     service.sin_port=htons(27015);
     if (bind(ListenSocket,
     (SOCKADDR*)&service, sizeof (service))==SOCKET_ERROR)
     {
         wprintf(L "bindfailedwitherror:%ld\n" ,WSAGetLastError());
         closesocket(ListenSocket);
         WSACleanup();
         return  1 ;
     }
     //----------------------
     //Listenforincomingconnectionrequests.
     //onthecreatedsocket
     if (listen(ListenSocket,1)==SOCKET_ERROR)
     {
         wprintf(L "listenfailedwitherror:%ld\n" ,WSAGetLastError());
         closesocket(ListenSocket);
         WSACleanup();
         return  1 ;
     }
     //----------------------
     //CreateaSOCKETforacceptingincomingrequests.
     SOCKETAcceptSocket ;
     wprintf(L  "Waitingforclienttoconnect...\n" );
     //----------------------
     //Accepttheconnection.
     AcceptSocket=accept(ListenSocket,NULL,NULL);
     if (AcceptSocket==INVALID_SOCKET)
     {
         wprintf(L  "acceptfailedwitherror:%ld\n" ,WSAGetLastError());
         closesocket(ListenSocket);
         WSACleanup();
         return  1 ;
     }
     else 
     wprintf(L  "Clientconnected.\n" );
     //Nolongerneedserversocket
     closesocket(ListenSocket);
     WSACleanup();
     return  0 ;
}

notes edit

This function starts from s Extract the first connection from the waiting connection queue of , Create a and s New socket of the same kind and return handle . If there is no waiting connection in the queue , And the socket is blocked , be accept() Block the calling process until a new connection appears . If the socket is non blocking and there is no waiting connection in the queue , be accept() Returns an error code . A socket that has accepted a connection cannot be used to accept a new connection , The original socket remains open .
addr Parameter is a return parameter , The address of the connection entity known to the communication layer is filled in .addr The actual format of the parameter is determined by the address family generated during communication .addrlen Parameter is also a return parameter , Initialize to... On call addr Refers to the address space ; At the end of the call, it contains the length of the address actually returned ( In bytes ). The function and SOCK_STREAM Type of connection oriented sockets . If addr And addrlen One of them is zero NULL, Will not return any information about the remote address of the socket accepted .
Return value :
If there are no errors , be accept() Returns a description of the accepted package SOCKET Type value . Otherwise , return INVALID_SOCKET error , The application program can call WSAGetLastError() To get a specific error code .
addrlen The integer number initially contains addr The size of the address space referred to , On return, it contains the byte length of the actual return address .

Error code edit

WSANOTINITIALISED: In the use of this API You should first successfully call WSAStartup().
WSAENETDOWN:WINDOWS Socket implementation detects network subsystem failure .
WSAEFAULT:addrlen The parameter is too small ( Less than socket Size of structure ).
WSAEINTR: Through one WSACancelBlockingCall() To cancel a ( Obstructed ) call .
WSAEINPROGRESS: A blocked WINDOWS The socket call is running .
WSAEINVAL: stay accept() Not activated before listen().
WSAEMFILE: call accept() Time queue is empty , No descriptors available .
WSAENOBUFS: No buffer space available .
WSAENOTSOCK: The descriptor is not a socket .
WSAEOPNOTSUPP: The socket type does not support connection oriented services .
WSAEWOULDBLOCK: The socket is non blocking and has no connection to accept .
WSAECONNRESET: After accepting the connection in accept Before returning , Disconnected by a remote client .
See :

accept() More articles about

  1. How to accept Track changes in Microsoft Word 2010?

    "Track changes" is wonderful and remarkable tool of Microsoft Word 2010. The feature allow ...

  2. GJM : Interrupt by Socket.Accept Blocked threads

    Original address :http://blog.csdn.net/kingfox/article/details/7233350 Original author : Fox Emperor Just learning C#, When writing a network communication program , There's a little bit of trouble . Listening code ...

  3. Linux Interprocess communication ( 8、 ... and ): Stream Socket socket()、bind()、listen()、accept()、connect()、read()、write()、close()

    The communication between processes mentioned above , All the processes communicated are on the same computer , While using socket The process that communicates can be a process on the same computer , It can also be processes on different computers connected through a network . Usually we use socket Network editing ...

  4. &lt;input type=&quot;file&quot; id=&quot;camera&quot; multiple=&quot;multiple&quot; capture=&quot;camera&quot; accept=&quot;image/*&quot;&gt; To upload pictures , Phone calls albums and cameras

    <input type="file" id="camera" multiple="multiple" capture="ca ...

  5. debugging zeromq Find out accept Dead cycle

    cause : One of the students in the group said to use  zeromq There's something wrong with it , The problem is described as follows “router After connecting more than 100000 clients , And then put router Kill , restart , Now zeromq A thread of 99% Of cpu, It's stuck , No more ...

  6. UNIX Network programming - Non blocking connect And non blocking accept

    1. Non blocking connect After reading a lot of information , My own understanding is : stay socket When you initiate a connection , It takes a while to finish the three handshakes , If the network situation is not good or some other situation , This process takes a long time ...

  7. High performance network programming ( One )----accept Establishing a connection

    When writing a server , Many programmers are used to using high-level components . middleware ( for example OO( object-oriented ) Open source components encapsulated layer upon layer ), Compared to the efficiency of the server , They pay more attention to the efficiency of program development , The pursuit of faster completion of the project function point . Hope the application code doesn't matter at all ...

  8. According to TLD or attribute directive in tag file, attribute test does not accept any expressions

    HTTP Status 500 - /WEB-INF/views/emp/list.jsp (line: 30, column: 4) According to TLD or attribute di ...

  9. input[file] Labeled accept=”image/*” The solution to slow property response

    from :http://blog.csdn.net/lx583274568/article/details/52983693 input[file] Labeled accept Property can be used to specify the  MIME type ...

  10. Socket accept failed

    start-up tomcat The following error is displayed : java.net.SocketException: select failed at java.net.PlainSocketImpl.socketAccept(Nat ...

Random recommendation

  1. ASP.NET Encrypt and decrypt database connection strings

    As we all know , Database operations in applications require connection strings , And if there is no connection string , We won't be able to retrieve the data in the application , Create a series of database operations such as data . When someone wants to access the database information in your program , The first thing he might see is We ...

  2. jQuery .css color rewrite :hover The pattern is gone

    $("#quickSqlDiv a").css({"color":"red"}); $("#course a").css ...

  3. python PIL install

    PIL:Python Imaging Library, It's already Python In fact, the image processing standard library of the platform .PIL Very powerful , but API It's very easy to use . install PIL stay Debian/Ubuntu Linux ...

  4. Linux Next use Magent+Memcached Cache server cluster deployment

    1. Compilation and installation libevent  cd /root/soft_hhf/  wget http://cloud.github.com/downloads/libevent/libevent/libeven ...

  5. VS Solution directory structure settings

    The configuration involved : Intermediate directory for project compilation : Output directory of project links : After the project is compiled , Copy generated dll and lib To the specified directory : After the project is compiled , Copy what you need dll Go to the output directory : Set the working directory of the project : ...

  6. &lt;pages validateRequest=&quot;false&quot;/&gt; stay .net4.0 The problem of ineffectiveness

    Again web.config Set in <pages validateRequest="false"/> stay .net4.0 The problem of ineffectiveness Solution : <system.web> ...

  7. hdu 4679 Trees dp

    Ideas : We just need to enumerate each edge , Just find the minimum . First dfs When we calculate each node as the root , The longest path of its subtree , And the longest path through the node , Second in command , The third long path . And then in the second dfs Enumeration to find a cut-off edge , Find out that the two endpoints of this edge are children ...

  8. C# SqlConnection

    public static ArrayList Connect(string connectionString, string commandText) { ArrayList retValList ...

  9. Chapter 6 Decoration mode

    Embellishment mode , In the field of object-oriented programming , A design pattern for dynamically adding new behaviors to a class . In terms of function , Decorating patterns are more flexible than subclassing , This adds some functionality to an object rather than the entire class . for example :DataOutputStrea ...

  10. Ruby on Rails, One to many connection (One-to-Many)

    In the last article , We know through has_one and belongs_to Method defines a one-to-one relationship . And then there's the more common case , One to many connection . For example, the relationship between teachers and the courses they teach , One teacher is in charge of many courses . In other words, the relationship between objects is : An old man ...