c_cpp tcp server.c

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp tcp server.c相关的知识,希望对你有一定的参考价值。

// Prepare a description of server address criteria.
struct addrinfo addrCriteria;
memset(&addrCriteria, 0, sizeof(addrCriteria));
addrCriteria.ai_family = AF_INET;
addrCriteria.ai_flags = AI_PASSIVE;
addrCriteria.ai_socktype = SOCK_STREAM;
addrCriteria.ai_protocol = IPPROTO_TCP;

// Lookup a list of matching addresses
struct addrinfo *servAddr;
if ( getaddrinfo( NULL, PORT_NUMBER, &addrCriteria, &servAddr) )
  printf( "Can't get address info\n" );

// Try to just use the first one.
if ( servAddr == NULL )
  printf( "Can't get address\n" );

// Create a TCP socket
int servSock = socket( servAddr->ai_family, servAddr->ai_socktype,
                       servAddr->ai_protocol);
if ( servSock < 0 )
  printf( "Can't create socket\n" );

// Bind to the local address
if ( bind(servSock, servAddr->ai_addr, servAddr->ai_addrlen) != 0 )
  printf( "Can't bind socket\n" );

// Tell the socket to listen for incoming connections.
if ( listen( servSock, 5 ) != 0 )
  printf( "Can't listen on socket\n" );

// Free address list allocated by getaddrinfo()
freeaddrinfo(servAddr);

// Wait for a client to connect
struct sockaddr_storage clntAddr; // Client address
// Set length of client address structure (in-out parameter)
socklen_t clntAddrLen = sizeof(clntAddr);

int sock = accept( servSock, (struct sockaddr *) &clntAddr, &clntAddrLen);
if ( sock < 0 )
  printf( "Can't accept on socket\n" );

// Buffer to receive into, but we never really use it.
char buffer[ BLOCK_SIZE ];
// Try to read all want from the socket.
int count = read( sock, buffer, bytesToRecv );

close( sock );
close( servSock );

以上是关于c_cpp tcp server.c的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp server.c

c_cpp select_server.c

c_cpp TCP链接.C

c_cpp TCP链接.C

c tcp sockt server client -- demo

c_cpp tcp_server