Вы находитесь на странице: 1из 2

#include

#include
#include
#include
#include
#include

<stdio.h>
<sys/socket.h>
<arpa/inet.h>
<stdlib.h>
<string.h>
<unistd.h>

#define MAXPENDING 5
#define RCVBUFSIZE 32

/*
/*
/*
/*
/*
/*

for
for
for
for
for
for

printf() and fprintf() */


socket(), bind(), and connect() */
sockaddr_in and inet_ntoa() */
atoi() and exit() */
memset() */
close() */

/* Maximum outstanding connection requests */


/* Size of receive buffer */

int main(int argc, char *argv[])


{
int servSock;
int clntSock;
struct sockaddr_in echoServAddr;
struct sockaddr_in echoClntAddr;
unsigned short echoServPort;
unsigned int clntLen;
int totalBytesRcvd;
char echoBuffer[RCVBUFSIZE];
int recvMsgSize;

/*
/*
/*
/*
/*
/*

Socket descriptor for server */


Socket descriptor for client */
Local address */
Client address */
Server port */
Length of client address data structure */
/* Buffer for echo string */
/* Size of received message */

/* Create socket for incoming connections */


if ((servSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
printf("socket() failed\n");
/* Construct local address structure */
memset(&echoServAddr, 0, sizeof(echoServAddr));
/* Zero out structure */
echoServAddr.sin_family = AF_INET;
/* Internet address family */
echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */
echoServAddr.sin_port = htons(1100);
/* Local port */
/* Bind to the local address */
if (bind(servSock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0)

{
printf("bind() failed\n");
exit(1);
}
/* Mark the socket so it will listen for incoming connections */
if (listen(servSock, MAXPENDING) < 0)
printf("listen() failed\n");
/* Set the size of the in-out parameter */
clntLen = sizeof(echoClntAddr);
/* Wait for a client to connect */
if ((clntSock = accept(servSock, (struct sockaddr *) &echoClntAddr,
&clntLen)) < 0)
printf("accept() failed\n");
/* clntSock is connected to a client! */
printf("Handling client %s\n", inet_ntoa(echoClntAddr.sin_addr));
/* Receive message from client */
if ((recvMsgSize = recv(clntSock, echoBuffer, RCVBUFSIZE, 0)) < 0)
printf("recv() failed\n");
else {
echoBuffer[recvMsgSize] = '\0'; /* Terminate the string! */
printf("recvMsg %s\n",echoBuffer);
}
close(clntSock);
}

Вам также может понравиться