コード例 #1
0
int main(int argc, char *argv[]) {

  if (argc != 3) // Test for correct number of arguments
    DieWithUserMessage("Parameter(s)",
        "<Server Address/Name> [<Server Port/Service>]");

  char *server = argv[1];     // First arg: server address/name
  char *service = argv[2]; 

  // Create a connected TCP socket
  int sock = SetupTCPClientSocket(server, service);
  if (sock < 0)
    DieWithUserMessage("SetupTCPClientSocket() failed", "unable to connect");

  FILE *str = fdopen(sock,"r+");
  char buffer[MAXSTRINGLENGTH];
  //while((scanf("%s",buffer) != EOF)){
  while(gets(buffer) && strlen(buffer) != 0){
      int sSize;
      int stringLen = strlen(buffer); // Determine input length
      if((sSize = PutMsg(buffer, stringLen, str)) < 0)
          DieWithSystemMessage("PutMsg() failed");
      //printf("Sending %d-byte..\n",sSize);
      /*
      GetNextMsg(str,buffer,MAXSTRINGLENGTH);
      printf("get echo\n");
      printf("%s\n",buffer);
      */
      memset(buffer,0,sizeof(buffer));
  }
  fclose(str);
  printf("quit.\n");
  return 0;
}
コード例 #2
0
int main(int argc, char *argv[]) {

  if (argc != 2) // Test for correct number of arguments
    DieWithUserMessage("Parameter(s)", "<Server Port/Service>");

  char *servPort = argv[1]; // First arg:  local port
  int servSock = SetupTCPServerSocket(servPort);
  if (servSock < 0)
    DieWithUserMessage("SetupTCPServerSocket() failed", "unable to establish");
  for (;;) { // Run forever
    int clntSock = AcceptTCPConnection(servSock);

    // Create separate memory for client argument
    struct ThreadArgs *threadArgs = (struct ThreadArgs *) malloc(
        sizeof(struct ThreadArgs));
    if (threadArgs == NULL)
      DieWithSystemMessage("malloc() failed");
    threadArgs->clntSock = clntSock;

    // Create client thread
    pthread_t threadID;
    int returnValue = pthread_create(&threadID, NULL, ThreadMain, threadArgs);
    if (returnValue != 0)
      DieWithUserMessage("pthread_create() failed", strerror(returnValue));
    printf("with thread %ld\n", (long int) threadID);
  }
  // NOT REACHED
}
コード例 #3
0
ファイル: GetAddrInfo.c プロジェクト: killinux/hello
int main(int argc, char *argv[]) {

    if (argc != 3) // Test for correct number of arguments
        DieWithUserMessage("Parameter(s)", "<Address/Name> <Port/Service>");

    char *addrString = argv[1];   // Server address/name
    char *portString = argv[2];   // Server port/service

    // Tell the system what kind(s) of address info we want
    struct addrinfo addrCriteria;                   // Criteria for address match
    memset(&addrCriteria, 0, sizeof(addrCriteria)); // Zero out structure
    addrCriteria.ai_family = AF_UNSPEC;             // Any address family
    addrCriteria.ai_socktype = SOCK_STREAM;         // Only stream sockets
    addrCriteria.ai_protocol = IPPROTO_TCP;         // Only TCP protocol

    // Get address(es) associated with the specified name/service
    struct addrinfo *addrList; // Holder for list of addresses returned
    // Modify servAddr contents to reference linked list of addresses
    int rtnVal = getaddrinfo(addrString, portString, &addrCriteria, &addrList);
    if (rtnVal != 0)
        DieWithUserMessage("getaddrinfo() failed", gai_strerror(rtnVal));

    // Display returned addresses
    for (struct addrinfo *addr = addrList; addr != NULL; addr = addr->ai_next) {
        PrintSocketAddress(addr->ai_addr, stdout);
        fputc('\n', stdout);
    }

    freeaddrinfo(addrList); // Free addrinfo allocated in getaddrinfo()

    exit(0);
}
コード例 #4
0
void HandleTCPClient(int clntSocket) {
  char buffer[BUFSIZE]; // Buffer for echo string

  // Receive message from client
  ssize_t numBytesRcvd = recv(clntSocket, buffer, BUFSIZE, 0);
  if (numBytesRcvd < 0)
    DieWithSystemMessage("recv() failed");

  // Send received string and receive again until end of stream
  while (numBytesRcvd > 0) { // 0 indicates end of stream
    // Echo message back to client
    ssize_t numBytesSent = send(clntSocket, buffer, numBytesRcvd, 0);
    if (numBytesSent < 0)
      DieWithSystemMessage("send() failed");
    else if (numBytesSent != numBytesRcvd)
      DieWithUserMessage("send()", "sent unexpected number of bytes");

    // See if there is more data to receive
    numBytesRcvd = recv(clntSocket, buffer, BUFSIZE, 0);
    if (numBytesRcvd < 0)
      DieWithSystemMessage("recv() failed");
  }

  close(clntSocket); // Close client socket
}
コード例 #5
0
 int main(int argc, char *argv[])
 {
 	if(argc < 4 || argc > 5)
 	{
 		DieWithUserMessage("Parameter(s)", "<Server-Address/Name> <Cmd Idx> <Echo Word> [<Server Port/Service>]");
 	}

 	char *server = argv[1];					/* First argument : Server address */
 	char *echoString = argv[3];				/* Second argument : Echo string */
 	char *port = argv[4];					/* Third argument (Optional): port/service number */
 	FILE *fp;
 	static CLNTARG clntArgs;
 	static PMSG pmsg;
 	static CMDARG cmdArg;
 	static char cmdArgs[MAX_NUM_PARAMS][MAX_PARAM_BUFFER_SIZE];
  	
  	/* Copy Echo string */
  	strcpy(cmdArgs[0], argv[3]);

 	/* Create a connect TCP socket */
 	int sock = SetupTCPClientSocket(server, port);
 	if(sock < 0)
 	{
 		DieWithUserMessage("SetupTCPClientSocket() failed", "unable to connect");
 	}

 	/* Open file stream using socket */
 	fp = fdopen(sock, "r+");
 	if(fp == NULL)
 	{
 		DieWithSystemMessage("fopen: NULL Pointer");
 	}
 

 	clntArgs.cmdIdx = atoi(argv[2]);
 	clntArgs.argv = (char (*)[MAX_PARAM_BUFFER_SIZE])cmdArgs;
 	clntArgs.filePtr = fp;

 	/* Invode Client Handler */
 	TCPClientHandler((void *)&pmsg, (void *)&clntArgs, (void *)&cmdArgs);


	/* Close the socket */
 	close(sock);										
 	exit(0);
 }
コード例 #6
0
ファイル: TCPServerUtility.c プロジェクト: sla16/CS3516_prog3
int SetupTCPServerSocket(const char *service) {
  // Construct the server address structure
  struct addrinfo addrCriteria;                   // Criteria for address match
  memset(&addrCriteria, 0, sizeof(addrCriteria)); // Zero out structure
  addrCriteria.ai_family = AF_UNSPEC;             // Any address family
  addrCriteria.ai_flags = AI_PASSIVE;             // Accept on any address/port
  addrCriteria.ai_socktype = SOCK_STREAM;         // Only stream sockets
  addrCriteria.ai_protocol = IPPROTO_TCP;         // Only TCP protocol



  struct addrinfo *servAddr; // List of server addresses
  int rtnVal = getaddrinfo(NULL, service, &addrCriteria, &servAddr);
  if (rtnVal != 0)
    DieWithUserMessage("getaddrinfo() failed", gai_strerror(rtnVal));



  int servSock = -1;
  for (struct addrinfo *addr = servAddr; addr != NULL; addr = addr->ai_next) {
    // Create a TCP socket
    servSock = socket(addr->ai_family, addr->ai_socktype,
        addr->ai_protocol);
    if (servSock < 0)
      continue;       // Socket creation failed; try next address



    // Bind to the local address and set socket to listen
    if ((bind(servSock, addr->ai_addr, addr->ai_addrlen) == 0) &&
        (listen(servSock, MAXPENDING) == 0))
    {
      // Print local address of socket
      struct sockaddr_storage localAddr;
      socklen_t addrSize = sizeof(localAddr);


      if (getsockname(servSock, (struct sockaddr *) &localAddr, &addrSize) < 0)
        DieWithSystemMessage("getsockname() failed");


      fputs("Binding to ", stdout);
      PrintSocketAddress((struct sockaddr *) &localAddr, stdout);
      fputc('\n', stdout);

      break;       // Bind and listen successful
    }

    close(servSock);  // Close and try again
    servSock = -1;
  }

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

  return servSock;
}
コード例 #7
0
int Inet_pton(int domain, const char *src, void *dst){
	int n;
	n = inet_pton(domain, src, dst);
	if(n==0)
		DieWithUserMessage("inet_pton() failed", "invalid address string");
	else if(n<0)
		DieWithSystemMessage("inet_pton failed");
	return n;
}
コード例 #8
0
ssize_t Send(int socket, const void *msg, size_t msgLength, int flags){
	ssize_t n;
	n = send(socket, msg, msgLength, flags);
	if(n<0)
		DieWithSystemMessage("send() failed");   
	else if(n!=msgLength)
		DieWithUserMessage("send()", "sent unexpected number of bytes");
	return n;                                                                                                                                    
}
コード例 #9
0
ファイル: chat_help.c プロジェクト: dcc635/chat
void chat_send(int sock, char *str) {
  size_t strLen = strlen(str); // Determine input length

  // Send the string to the server
  ssize_t numBytes = send(sock, str, strLen, 0);
  if (numBytes < 0)
    DieWithSystemMessage("send() failed");
  else if (numBytes != strLen)
    DieWithUserMessage("send()", "sent unexpected number of bytes");
}
コード例 #10
0
//Function: get Server IP using the Server Name
char *getIPbyHostName(char *servName, char *addr)
{
	struct hostent *host;
	char **p;
	if ((host=gethostbyname(servName))==NULL)
		DieWithUserMessage("gethostbyname()", "host connection failed");
	p=host->h_addr_list;
	inet_ntop(AF_INET, *p, addr, INET_ADDRSTRLEN);//Just get the first IP address of address list
	return addr;
}
コード例 #11
0
int main(int argc, char *argv[]) {
  if (argc != 2) // Test for correct number of arguments
    DieWithUserMessage("Parameter(s)", "<Server Port/Service>");

  int servSock = SetupTCPServerSocket(argv[1]);
  // servSock is now ready to use to accept connections

  for (;;) { // Run forever

    // Wait for a client to connect
    int clntSock = AcceptTCPConnection(servSock);

    // Create an input stream from the socket
    FILE *channel = fdopen(clntSock, "r+");
    if (channel == NULL)
      DieWithSystemMessage("fdopen() failed");

    // Receive messages until connection closes
    int mSize;
    uint8_t inBuf[MAX_WIRE_SIZE];
    VoteInfo v;
    while ((mSize = GetNextMsg(channel, inBuf, MAX_WIRE_SIZE)) > 0) {
      memset(&v, 0, sizeof(v)); // Clear vote information
      printf("Received message (%d bytes)\n", mSize);
      if (Decode(inBuf, mSize, &v)) { // Parse to get VoteInfo
        if (!v.isResponse) { // Ignore non-requests
          v.isResponse = true;
          if (v.candidate >= 0 && v.candidate <= MAX_CANDIDATE) {
            if (!v.isInquiry)
              counts[v.candidate] += 1;
            v.count = counts[v.candidate];
          } // Ignore invalid candidates
        }
        uint8_t outBuf[MAX_WIRE_SIZE];
        mSize = Encode(&v, outBuf, MAX_WIRE_SIZE);
        if (PutMsg(outBuf, mSize, channel) < 0) {
          fputs("Error framing/outputting message\n", stderr);
          break;
        } else {
          printf("Processed %s for candidate %d; current count is %llu.\n",
              (v.isInquiry ? "inquiry" : "vote"), v.candidate, v.count);
        }
        fflush(channel);
      } else {
        fputs("Parse error, closing connection.\n", stderr);
        break;
      }
    }
    puts("Client finished");
    fclose(channel);
  } // Each client
  // NOT REACHED
}
コード例 #12
0
ファイル: chat_help.c プロジェクト: dcc635/chat
void chat_client_send(int sock, char *username, char *str) {
  char message[MSG_SIZE*2];
  sprintf(message, "%s: %s", username, str);
  size_t strLen = strlen(message); // Determine input length


  // Send the string to the server
  ssize_t numBytes = send(sock, message, strLen, 0);
  if (numBytes < 0)
    DieWithSystemMessage("send() failed");
  else if (numBytes != strLen)
    DieWithUserMessage("send()", "sent unexpected number of bytes");
}
コード例 #13
0
void HandleTCPClient(int clntSocket, char* clntName) {
	char buffer[BUFSIZE]; // Buffer for echo string

	// Receive message from client
	ssize_t numBytesRcvd = recv(clntSocket, buffer, BUFSIZE, 0);
	if (numBytesRcvd < 0) {
		DieWithSystemMessage("recv() failed");
	}
	buffer[numBytesRcvd] = '\0';
	printf("Number of bytes received: %d\n", (int)numBytesRcvd);

  	// Send received string and receive again until end of stream
	while (numBytesRcvd > 0) { // 0 indicates end of stream
		// Echo message back to client
		ssize_t numBytesSent = send(clntSocket, buffer, numBytesRcvd, 0);
		if (numBytesSent < 0)
			DieWithSystemMessage("send() failed");
		else if (numBytesSent != numBytesRcvd)
			DieWithUserMessage("send()", "sent unexpected number of bytes");
		
		// Give the message to Napster's parser
		char* filename = malloc((numBytesRcvd-1)*sizeof(char));
		printf("Received string: %s\n", buffer);
		memmove(filename, &buffer[1], numBytesRcvd-1);
		filename[numBytesRcvd-1] = '\0';

		switch (buffer[0] - '0')
		{
			case ADDFILE: addFile(filename, clntName);
					break;
			case DELETEFILE: printf("Status of delete: %d\n",deleteFile(filename, clntName));
					break;
			case LISTFILES: viewFiles(clntSocket);
					break;
		}

		free(filename);

		// See if there is more data to receive
		printf("Waiting for more data from client...\n");
		numBytesRcvd = recv(clntSocket, buffer, BUFSIZE, 0);
		buffer[numBytesRcvd] = '\0';    // Terminate the string!
		if (numBytesRcvd < 0) {
			DieWithSystemMessage("recv() failed");
		}
		printf("Processing data recieved, \"%s\"...\n", buffer);
		printf("Number of bytes received (currently) : %d\n",(int)numBytesRcvd);
  	}

	close(clntSocket); // Close client socket
}
コード例 #14
0
int SetupTCPServerSocket(const char *service)
{
	/* Construct the server address structure */
	struct addrinfo addrCriteria;
	memset(&addrCriteria, 0, sizeof(addrCriteria));	/* Zero out all the unused fields */
	addrCriteria.ai_family = AF_UNSPEC;				/* Accept both v4 and v6 */
	addrCriteria.ai_socktype = SOCK_STREAM;			/* Only Stream type */
	addrCriteria.ai_flags = AI_PASSIVE;				/* Accept on any address */
	addrCriteria.ai_protocol = IPPROTO_TCP;			/* Accept only TCP protocol */
	
	struct addrinfo *servAddr;						/* List of server addresses */
	int rtnVal = getaddrinfo(NULL, service, &addrCriteria, &servAddr);
	if(rtnVal != SUCCESS)
	{
		DieWithUserMessage("getaddrinfo() failed", gai_strerror(rtnVal));
	}	
	int servSock = -1;								/* Initialize descriptor for server socket */
	struct addrinfo *addr;
	for(addr = servAddr; addr != NULL; addr = addr->ai_next)
	{
		servSock = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
		if(servSock < 0)
		{
			/* Socket creation failed, retry with next entry */
			continue;
		}
		/* Bind to local address and set socket to listen */
		if((bind(servSock, addr->ai_addr, addr->ai_addrlen) == SUCCESS) &&
				(listen(servSock, MAXPENDING) == SUCCESS))
		{
			/* Print the local address of the socket */
			struct sockaddr_storage localAddr;
			socklen_t addrSize = sizeof(localAddr);
			if(getsockname(servSock, (struct sockaddr *)&localAddr, &addrSize) < 0)
			{
				DieWithSystemMessage("getsockname() failed");
			}
			fputs("Binding to ", stdout);
			PrintSocketAddress((struct sockaddr *)&localAddr, stdout);
			fputc(NEW_LINE, stdout);
			break;
		}
		close(servSock);
		servSock = -1;
	}

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

	return servSock;
}
コード例 #15
0
ファイル: TCPEchoServer6.c プロジェクト: lyhopq/zh
int main(int argc, char *argv[])
{
    if(argc != 2)   // Test for corrent number of arguments
        DieWithUserMessage("Parameter(s)", "<Server Port>");

    in_port_t servPort = atoi(argv[1]);     // First arg: local port

    // Create socket for incoming connections
    int servSock = socket(AF_INET6, SOCK_STREAM, IPPORT_TCP);
    if(sockSock < 0)
        DieWithSystemMessage("socket() failed");

    // Construct local address structure
    struct sockaddr_int servAddr;   // Local address
    memset(&servAddr, 0, sizeof(servAddr));     // Zero out structure
    servAddr.sin6_family = AF_INET6;    // Zero out structure
    servAddr.sin6_addr = in6addr_any;   // IPv6 address family
    servAddr.sin6_port = htons(servPort); // Local port

    // Bind to the local address
    if(bind(servSock, (struct sockaddr *)&servAddr, sizeof(servAddr)) < 0)
        DieWithSystemMessage("bind() failed");

    // Mark the socket so ti will listen for incoming connections
    if(listen(servSock, MAXPENDING) < 0)
        DieWithSystemMessage("listen() failed");

    for(;;)     // Run forever
    {
        struct sockaddr_in6 clntAddr;   // Client address
        // Set length of client address structure (in-out parameter)
        socklen_t clntAddrLen = sizeof(clntAddr);

        // Wait for a client to connect
        int clntSock = accept(servSock, (struct sockaddr *)&clntAddr, &clntAddrLen);
        if(clntSock < 0)
            DieWithSystemMessage("accept() failed");

        // clntSock is connected to a client!

        char clntName[INET6_ADDRSTRLEN];    // Array to contain client address string
        if(inet_ntop(AF_INET6, &clntAddr.sin6_addr.s6_addr, clntName,
                sizeof(clntName)) != NULL)
            printf("Handing client %s/%d\n", clntName, ntohs(clntAddr.sin6_port));
        else
            puts("Unable to get client address");

        HandleTCPClient(clntSock);
    }
    // NOT REACHED
}
コード例 #16
0
ファイル: recvImage_ok_close.c プロジェクト: Team-Arca/Server
int main(int argc, char* argv[]) {

    in_port_t servPort = 4547;
    //연결 요청을 처리하는 소켓 생성
    int servSock;
    if((servSock = socket(PF_INET, SOCK_STREAM, 0)) < 0 )
        DieWithUserMessage("socket() failed");

    // 지역 주소 구조체 생성
    struct sockaddr_in servAddr;					// 지역 주소
    memset(&servAddr, 0, sizeof(struct sockaddr_in));			// 0으로 구조체 초기화
    servAddr.sin_family = AF_INET;					// IPv4 주소 패밀리
    servAddr.sin_addr.s_addr = htonl(INADDR_ANY);	// 호스트의 어떠한 IP로도 연결 요청 수락
    servAddr.sin_port = htons(servPort);	// 지역포트

    // 지역 주소에 바인드
    if(bind(servSock, (struct sockaddr*) &servAddr, sizeof(servAddr)) < 0)
        DieWithUserMessage("bind() failed");

    // 소켓이 들어오는 요청을 처리할 수 있도록 설정
    if(listen(servSock, MAXPENDING) < 0)
        DieWithUserMessage("listen() failed");

    while(1) { // 무한 반복
        struct sockaddr_in clientAddr;
        printf("wait accept\n");
        socklen_t clientAddrlen = sizeof(clientAddr);

        //클라이언트의 연결을 기다림
        int clientSock = accept(servSock, (struct sockaddr *) &clientAddr, &clientAddrlen);
        if( clientSock <0 )
            DieWithUserMessage("accept() failed");
        printf("client accept!!\n");
        HandleTCPClient(clientSock);
    }
}
コード例 #17
0
ファイル: TCPServerUtility.c プロジェクト: sla16/CS3516_prog3
int sendFrame(uint16_t seq, char ft, int clntSock)
{
    char buffer[10];
    ssize_t numBytesSent;
    static int frame_num = 0;

    // format message
    *(uint16_t *) buffer = seq;    /* Sequence number */
    buffer[2] = ft;               /* Frame type */
    *(uint16_t *)(buffer + 3) = seq;
    buffer[5] = '\0';


    if(ft == ACK_FRAME)
    {
        if(((frame_num + 1) % 11) == 0)
        {
            buffer[3] ^= 0x7;
        }
        frame_num++;
    }


    // send message
    numBytesSent = send(clntSock, buffer, 5, 0);

    // check for send errors
    if (numBytesSent < 0)
      DieWithSystemMessage("send() failed");
    else if (numBytesSent != 5)
      DieWithUserMessage("send()", "sent unexpected number of bytes");

    // print event to log file
    if(ft == ACK_PACKET)
    {
        printf("sending packet ack\n");
        fprintf(log_file, "sent packet ACK,(%" PRIu16 ")\n", seq);
    }
    else if(ft == ACK_FRAME)
    {
        printf("sending frame ack\n");
        fprintf(log_file, "sent frame ACK, (%" PRIu16 ")\n", seq);
    }

    fflush(log_file);

    return 0;
}
コード例 #18
0
ファイル: TCPServerUtility.c プロジェクト: rbrowngt/OldCode
char * HandleTCPClient(int clntSocket) {
   static char buffer[BUFSIZE]; // Buffer for echo string
    char *dlMode = "ttweet_REQUEST";
    // Receive message from client
    //printf("About to recv\n");
    ssize_t numBytesRcvd = recv(clntSocket, buffer, BUFSIZE, 0);
   // printf("Just recv'd recv\n");
    if (numBytesRcvd < 0)
        DieWithSystemMessage("recv() failed");
    
    //For Testing
    buffer[numBytesRcvd] = '\0';
    
    if(strcmp(dlMode, buffer)==0) {
	//same string
	//close(clntSocket);
	return buffer;
      
    }
    else {
    //fputs("Server recieved: ", stdout);
    //fputs(buffer, stdout);  
    // Send received string and receive again until end of stream
    while (numBytesRcvd > 0) { // 0 indicates end of stream
        // Echo message back to client
        ssize_t numBytesSent = send(clntSocket, buffer, numBytesRcvd, 0);
        if (numBytesSent < 0)
            DieWithSystemMessage("send() failed");
        else if (numBytesSent != numBytesRcvd)
            DieWithUserMessage("send()", "sent unexpected number of bytes");
        
        // See if there is more data to receive
        numBytesRcvd = recv(clntSocket, buffer, BUFSIZE, 0);
	//printf("%i\n", numBytesRcvd);
        if (numBytesRcvd < 0)
            DieWithSystemMessage("recv() failed");
    }
    //printf("Closing now\n");
    close(clntSocket); // Close client socket
    return buffer;
    }
}
コード例 #19
0
void HandleTCPClient(int clntSocket) {
  char     buffer[BUFSIZE]; // Buffer for echo string
  ssize_t  numBytesRcvd = 0;
  struct tm * timeinfo;
  time_t rawtime;
  ssize_t  bytesToSent = 0;
  // Receive message from client
  ssize_t totalBytes = recv(clntSocket, buffer, BUFSIZE, 0);
  if (totalBytes < 0)
    DieWithSystemMessage("recv() failed");

  // Send received string and receive again until you have recieved 4 bytes
  while (totalBytes < 4) { // 0 indicates end of stream
    numBytesRcvd = recv(clntSocket, buffer+totalBytes, BUFSIZE, 0);
    if(numBytesRcvd < 0)
      DieWithSystemMessage("recv() failed");

    totalBytes += numBytesRcvd;
  }

  buffer[totalBytes] = '\0';

  if(strcmp("date", buffer) == 0 ){
    time(&rawtime);
    timeinfo = localtime(&rawtime);
    strftime(buffer,80, "%T", timeinfo);
  }
  else if(strcmp("time", buffer) == 0){
    time(&rawtime);
    timeinfo = localtime(&rawtime);
    strftime(buffer,80, "%F", timeinfo);
  }

   ssize_t numBytesSent = send(clntSocket, buffer, strlen(buffer), 0);
   if (numBytesSent < 0)
      DieWithSystemMessage("send() failed");
   else if (numBytesSent != strlen(buffer))
      DieWithUserMessage("send()", "sent unexpected number of bytes");

  close(clntSocket); // Close client socket
}
コード例 #20
0
void GUtility::PrintLocalForeignAddress(int socket,FILE* stream)
{
    if (socket<0)
    {
        DieWithUserMessage("PrintLocalForeignAddress() failed","invalid socket");
    }
    
    // print client address
    sockaddr_storage temp_addr;
    socklen_t   temp_addr_len = sizeof(temp_addr);
    memset(&temp_addr, 0, sizeof(temp_addr));
    getsockname(socket, (struct sockaddr *)&temp_addr, &temp_addr_len);
    fputs("==local info==\n",stream);
    GUtility::PrintSocketAddress((struct sockaddr *)&temp_addr, stream);
    fputc('\n', stream);
    
    // print foreign address
    getpeername(socket, (struct sockaddr *)&temp_addr, &temp_addr_len);
    fputs("==server info==\n",stream);
    GUtility::PrintSocketAddress((struct sockaddr *)&temp_addr, stream);
    fputc('\n', stream);
}
コード例 #21
0
// Create, bind, and listen a new TCP server socket
int SetupTCPServerSocket(const char *service) {
	// Construct the server address structure
	struct addrinfo addrCriteria;
	memset(&addrCriteria, 0, sizeof(addrCriteria));
	addrCriteria.ai_family = AF_UNSPEC;
	addrCriteria.ai_flags = AI_PASSIVE;
	addrCriteria.ai_socktype = SOCK_STREAM;
	addrCriteria.ai_protocol = IPPROTO_TCP;

	struct addrinfo *servAddr;	// List of server addresses
	int rtnVal = getaddrinfo(NULL, service, &addrCriteria, &servAddr);
	if (rtnVal != 0)
		DieWithUserMessage("getaddrinfo() failed", gai_strerror(rtnVal));

	int servSock = -1;
	struct addrinfo *addr = servAddr;
	for ( ; addr != NULL; addr = addr->ai_next) {
		// Create a TCP socket
		servSock = socket(addr->ai_family, addr->ai_socktype,
				addr->ai_protocol);
		if (servSock < 0)
			continue;

		// Bind to the local address and set socket to listen
		if ((bind(servSock, addr->ai_addr, addr->ai_addrlen) == 0) &&
				(listen(servSock, MAXPENDING) == 0)) {
			break;
		}

		close(servSock);	// Close and try again
		servSock = -1;
	}

	// Free address list allocated by get addrinfo()
	freeaddrinfo(servAddr);

	return servSock;
}
コード例 #22
0
ファイル: TCPEchoServer4.c プロジェクト: khmacdonald/Misc
void HandleTCPClient ( int clntSocket )
{
    ssize_t numBytesRcvd, numBytesSent;
    char buffer[BUFSIZE];

    /* Receive from client */
    numBytesRcvd = recv(clntSock,buffer,BUFSIZE,0);
    if ( numBytesRcvd < 0 )
    {
        DieWithSystemMessage("recv() failed");
    }

    /* Send received string and receive again until end of stream */
    while ( numBytesRecv > 0 )
    {
        /* Echo back to client */
        numBytesSent = send(clntSocket,buffer,numBytesRcvd,0);
        if ( numBytesSent <  0 )
        {
            DieWithSystemMessage("send() failed");
        }
        else if ( numBytesSent != numBytesRcvd )
        {
            DieWithUserMessage("send()","sent unexpected number of bytes");
        }

        /* See if there is more date to receive */
        numBytesRcvd = recv(clntSocket,buffer,BUFSIZE,0);
        if ( numBytesRcvd < 0 )
        {
            DieWithSystemMessage("recv() failed");
        }
    } /* while */

    close(clntSocket); /* Close client socket */
}
コード例 #23
0
void HandleTCPClient(int clntSocket, char* clientIP) {
	char buffer[BUFSIZE]; // Buffer for echo string

	if(DEBUG) printf("[NapsterServerUtility] Handling TCP Client %s\n",clientIP);
	// Receive message from client
	ssize_t numBytesRcvd = recv(clntSocket, buffer, BUFSIZE, 0);
	if (numBytesRcvd < 0)
		DieWithSystemMessage("recv() failed");
	buffer[numBytesRcvd] = '\0';
	if(DEBUG) printf("[NapsterServerUtility] Received: %s\n",buffer);

	state = malloc(sizeof(char*));
	strncpy(state,buffer,1);
	char* idleState = "0";
	char* addState = "1";
	char* listState = "2";

	// Send received string and receive again until end of stream
	while (numBytesRcvd > 0) { // 0 indicates end of stream
			// Echo message back to client
			if(DEBUG) printf("[NapsterServerUtility] echoing %s\n",buffer);
			ssize_t numBytesSent = send(clntSocket, buffer, numBytesRcvd, 0);
			if(DEBUG) printf("[NapsterServerUtility] Message Echoed\n");
			if (numBytesSent < 0)
				DieWithSystemMessage("send() failed");
			else if (numBytesSent != numBytesRcvd)
				DieWithUserMessage("send()", "sent unexpected number of bytes");

		if(strncmp(addState,state,1)==0){
			memmove(buffer,buffer+1,strlen(buffer));
			buffer[strlen(buffer)] = '\0';
			if(DEBUG) printf("[NapsterServerUtility] Line in %s: %d\n",filename,file_line);
			if(DEBUG) printf("[NapsterServerUtility] Previous file line: %s\n",list[file_line-1].filename);


			//write the data to the file
			int file_add = addFile(buffer,clientIP);
			if(!file_add){
				DieWithSystemMessage("addFile() failed");
			}

			if(DEBUG) printf("[NapsterServerUtility] Echo message back to client %s\n", list[file_line-1].filename);


			state = idleState;
		}
		else if(strncmp(listState,state,1)==0){
			if(DEBUG) printf("[NapsterServerUtility] Listing files!\n");
			char length[BUFSIZE];
			int list_size = sizeof(list);
			sprintf(length,"%d",list_size);
			if(DEBUG) printf("[NapsterServerUtility] Data to Send: %d %s\n",list_size,length);

			//sending file size to client
			if(DEBUG) printf("[NapsterServerUtility] sending file size to client\n");
			ssize_t numBytesSent = send(clntSocket,length,strlen(length),0);

			if (numBytesSent < 0)
				DieWithSystemMessage("send() failed");
			else if (numBytesSent != numBytesRcvd)
				DieWithUserMessage("send()", "sent unexpected number of bytes");

			//recv ack
			char ackbuffer[BUFSIZE];
			ssize_t numBytesAck1 = recv(clntSocket,ackbuffer,BUFSIZE, 0);

			if(numBytesAck1 < 0){
				DieWithSystemMessage("recv() failed");
			}

			char* file_list;
			file_list = malloc(file_line*sizeof(char*));
			sprintf(file_list,"%s %s\n",list[0].origin_ip_address,list[0].filename);
			int i;
			for(i = 1; i<file_line;i++){
				if(DEBUG) printf("[NapsterServerUtility] %d %s %s\n",i,list[i].origin_ip_address,list[i].filename);
				strcat(file_list,list[i].origin_ip_address);
				strcat(file_list," ");
				strcat(file_list,list[i].filename);
				strcat(file_list,"\n");
			}

			if(DEBUG) printf("[NapsterServerUtility]\n%s\n",file_list);
			if(DEBUG) printf("[NapsterServerUtility] sending file to client\n");
			//sending file to client
			ssize_t numBytesSentList = send(clntSocket,list,strlen(file_list),0);
			if(numBytesSentList<0)
				DieWithSystemMessage("send() failed");
			if(DEBUG) printf("[NapsterServerUtility] filelist sent\n");

			state = idleState;
		}
		else if(state == idleState){
		// See if there is more data to receive
			if(DEBUG) printf("[NapsterServerUtility] waiting for more data\n");
			numBytesRcvd = recv(clntSocket, buffer, BUFSIZE, 0);
			buffer[numBytesRcvd] = '\0';
			if(DEBUG) printf("[NapsterServerUtility] done waiting for more data received: %s numBytesRcvd  %zu\n",buffer,numBytesRcvd);
			if (numBytesRcvd < 0)
				DieWithSystemMessage("recv() failed");
			state = malloc(sizeof(char*));
			strncpy(state,buffer,1);
			if(DEBUG) printf("[NapsterServerUtility] state after recv: %s\n",state);
		//		printf("[NapsterServerUtility] Leaving HandleTCPClient()\n");
		//		
		}
	}

	  close(clntSocket); // Close client socket
}
コード例 #24
0
void HandleTCPClient(int clntSocket, char *trigAcptPort, int PrintStatus)
{

  unsigned char sndBuffer[SNDBUFSIZE];/* Buffer for data string to be sent */
  memset(sndBuffer,73,sizeof(sndBuffer));
  /***************************************/
  //  Signal receiver port(SERVER) 
  /***************************************/
  // Definition
  if(PrintStatus==1)
    printf("FakeCluster1 : Trigger receive port is set to # %s\n",trigAcptPort);
  //tell the system what kinds of address we want
  //**************
  // ai_family  
  //  AF_UNSPEC :Any address family
  //  AF_INET   :IPv4 address family
  //  
  // ai_flags
  //  AI_PASSIVE    :Accept on any address/port */ 
  //  AI_NUMERICHOST:Accept only on numeric address/port
  //  
  //  
  //**************
  struct addrinfo addrCriteria;                     // Criteria for address
  memset(&addrCriteria, 0, sizeof(addrCriteria));   // Zero out structure
  addrCriteria.ai_family   = AF_INET;               // IPv4 address family
  addrCriteria.ai_flags    = AI_PASSIVE;            // Accept on any address/port */
  addrCriteria.ai_socktype = SOCK_DGRAM;            // Only datagram socket
  addrCriteria.ai_protocol = IPPROTO_UDP;           // Only UDP socket
  /***GETADDRINFO***/
  struct addrinfo *servAddr;                        // List of server addresses
  int rtnVal = getaddrinfo(NULL, trigAcptPort, &addrCriteria, &servAddr);
  if (rtnVal != 0)
    DieWithUserMessage("getaddrinfo() failed", gai_strerror(rtnVal));
  /***SOCKET***/
  int trigSock = socket(servAddr->ai_family, servAddr->ai_socktype,
      servAddr->ai_protocol);
  if (trigSock < 0)
    DieWithSystemMessage("socket() failed");

  int yes =1;
  if(setsockopt(trigSock, SOL_SOCKET, SO_REUSEADDR, (const char *)&yes,
		sizeof(yes))<0)
    DieWithSystemMessage("setsockopt() failed");
  /***BIND***/
  if (bind(trigSock, servAddr->ai_addr, servAddr->ai_addrlen) < 0)
    DieWithSystemMessage("bind() failed");
  
  // Free address list allocated by getaddrinfo()
  freeaddrinfo(servAddr);


  /***************************************/
  //  Handling process
  /***************************************/
  for(;;)
    {
      /***preparation for trigger acception***/
      // Client address
      struct sockaddr_storage clntAddr; 
      // Set Length of client address structure (in-out parameter)
      socklen_t clntAddrLen = sizeof(clntAddr);
      // Size of trigger signal message
      char buffer[MAXSTRINGLENGTH]; // I/O buffer

      /***trigger acception***/
      // (Block until receive message from a client)
      ssize_t numBytesRcvd = recvfrom(trigSock, buffer, MAXSTRINGLENGTH, 0,
				      (struct sockaddr *) &clntAddr, &clntAddrLen);
      if (numBytesRcvd < 0)
	DieWithSystemMessage("recvfrom() failed");
      
      /***trigger acception message***/
      if(PrintStatus==1)
	{
	  fputs("Trigger signal is accepted from ", stdout);
	  PrintSocketAddress((struct sockaddr *) &clntAddr, stdout);
	  fputc('\n', stdout);
	}
      /***sending data***/   
      if(send(clntSocket, sndBuffer, sizeof(sndBuffer), 0)<0)
	break;//DieWithError("Send error \n");
    }
  /* Close client socket */
  close(trigSock);      
  close(clntSocket);    
}
コード例 #25
0
void viewFiles(int clntSock)
{
	FILE* fp = fopen(FILE_LIST, "rt");
	char line[80];
	char* list = malloc(1024 * sizeof(char)); 
	
	if (fp != NULL)
	{
		while (fgets(line, 1024, fp) != NULL)
		{
			strcat(list, line);
		}
		printf("Current line: %s\n", list);
	}
	char* buffer = "SIZE VALUE";

	// Send size
	ssize_t numBytesSent = send(clntSock, buffer, strlen(buffer), 0);
	if (numBytesSent < 0)
		DieWithSystemMessage("send() failed");
	else if (numBytesSent != strlen(buffer))
		DieWithUserMessage("send()", "sent unexpected number of bytes");

	// Receive Acknowledgement
	ssize_t numBytesRcvd = 0;
	char str[5];
	while (numBytesRcvd == 0)
	{
		printf("Waiting for acknowledgement from client (handshake)...\n");
		printf("Receiving acknowledgement\n");
		numBytesRcvd = recv(clntSock, str, 5, 0);
		if (numBytesRcvd < 0) {
			DieWithSystemMessage("recv() failed");
		}
		str[numBytesRcvd] = '\0';
		printf("Acknowledgement received...\n");
	}
	if (strcmp(str, "ACK") == 0)
	{
		// Send the file list
		FILE* fp = fopen(FILE_LIST, "rt");
		char line[80];
		char* list = malloc(1024 * sizeof(char)); 
		
		if (fp != NULL)
		{
			while (fgets(line, 1024, fp) != NULL)
			{
				strcat(list, line);
			}
		}

		if (strcmp(list,"") == 0)
			list = "Central server file list is empty!";

		numBytesSent = send(clntSock, list, strlen(list), 0);
		if (numBytesSent < 0)
			DieWithSystemMessage("send() failed");
		else if (numBytesSent != strlen(list))
			DieWithUserMessage("send()", "sent unexpected number of bytes");
	}
	else
		printf("Error listing files\n");
}
コード例 #26
0
ファイル: TCPEchoServer4.c プロジェクト: khmacdonald/Misc
int main ( int argc, char * argv[] )
{
    in_port_t servPort = atoi(argv[1]); /* First arg: local port */
    int servSock; /* Socket descriptor for server */
    struct sockaddr_in servAddr;
    struct sockaddr_in clntAddr;
    socklen_t clntAddrLen = sizeof(clntAddr);
    int clntSock = -1;
    char clntName[INET_ADDRSTRLEN];

    if ( 2!=argc )
    {
        /* Test for correct number of arguments */
        DieWithUserMessage("Parameter(s)","<Server Port>");
    }

    /* Create socket for incoming connections */
    if ( (servSock = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)) > 0 )
    {
        DieWithSystemMessage("socket() failed");
    }

    /* Construct local address structure */
    memset(&servAddr,0,sizeof(servAddr));   /* Zero out structure */
    servAddr.sin_family = AF_INET;          /* IPv4 address family */
    servAddr.sin_addr.s_addr = htonl(INADDR_ANY);   /* Any incoming interface */
    servAddr.sin_port = htons(servPort);    /* Local port */

    /* Bind to the local address */
    if ( bind(servSock,(struct sockaddr*)&servAddr,sizeof(servAddr)) < 0 )
    {
        DieWithSystemMessage("bind() failed");
    }

    /* Mark the socket so it will listen for incoming connections */
    if ( listen(servSock,MAXPENDING) < 0 )
    {
        DieWithSystemMessage("listen() failed");
    }

    /* Run forever */
    for ( ;; )
    {
        clntSock = accept(servSock,(struct sockaddr*)&clntAddr,&clntAddrLen);
        if ( clntSock < 0 )
        {
            DieWithSystemMessage("accept() failed");
        }

        /* clntSock is connected to a client */
        if ( inet_ntop(AF_INET,&clntAddr.sin_addr.s_addr,clntName,sizeof(clntName))!=NULL )
        {
            printf("Handling clinet %s/%d\n",clntName,ntohs(clntAddr.sin_port));
        }
        else
        {
            puts("Unable to get client address");
        }
        HandleTCPClient(clntSock); /* Need code from page 12 */
    }
    /* Not Reached */

    return 0;
}
コード例 #27
0
ファイル: testget.c プロジェクト: calebpriester/SimpleHTTP
int main(int argc, char **argv) {

   char *url;
   char *httpServName = "127.0.0.1";
   char *toGet = argv[1];
   struct hostent *host;
   struct in_addr hostAddr;
   char *hostIP;
   int servPort = 8080;
   char *filename;
   FILE *output;
   int fileSpecified = 0;
   char httpMessage[10000];

   if(argc%2 != 0) {
      DieWithUserMessage("Parameter(s)",
         "<URL> [-p <Port>] [-o <Filename>]");
   }

   url = argv[1];
   
   int i;
   for(i = 2; i < argc && argv[i][0] == '-'; i++) {
      if(argv[i][1] == 'p') servPort = atoi(argv[++i]);
      else if(argv[i][1] == 'o') {
         filename = argv[++i];
	 fileSpecified = 1;
      }
   }

   if(fileSpecified) output = fopen(filename, "w");

//   httpServName = (char *)malloc(sizeof(url));
//   toGet = (char *)malloc(sizeof(url));

//   httpServName = strtok(url, "/");
//   httpServName = strtok(NULL, "/");
//   toGet = strtok(NULL, "\0");

//printf("%s\t%s\n", httpServName, toGet);
   strcpy(httpMessage, "GET /");
   strcat(httpMessage, toGet);
//strcat(httpMessage, "/index.html");
   strcat(httpMessage, " HTTP/1.1\r\nHost: ");
   strcat(httpMessage, httpServName);
   strcat(httpMessage, "\r\n\r\n");

//   printf("%s", httpMessage);

   host = gethostbyname(httpServName);
   bcopy(host->h_addr, (char *)&hostAddr, sizeof(hostAddr));

   hostIP = inet_ntoa(hostAddr);

printf("%s\n", hostIP);

//if(fileSpecified) fprintf(output, "%s\t%d\t%s\n", url, servPort, filename);
//else              printf("%s\t%d\t%s\n", url, servPort, filename);
   

   int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
   if(sock < 0) {
      DieWithSystemMessage("socket() failed");
   }

   struct sockaddr_in servAddr;
   memset(&servAddr, 0, sizeof(servAddr));
   servAddr.sin_family = AF_INET;
   int rtnVal = inet_pton(AF_INET, hostIP, &servAddr.sin_addr.s_addr);
   //int rtnVal = inet_pton(AF_INET, "127.0.0.1", &servAddr.sin_addr.s_addr);
   if(rtnVal == 0) {
      DieWithUserMessage("inet_pton() failed", "invalid address string");
   }
   else if(rtnVal < 0) {
      DieWithSystemMessage("inet_pton() failed");
   }
   servAddr.sin_port = htons(servPort);

   if(connect(sock, (struct sockaddr *)&servAddr, sizeof(servAddr)) < 0) {
      DieWithSystemMessage("connect() failed");
   }

   size_t httpMessageLen = strlen(httpMessage);

   ssize_t numBytes = send(sock, httpMessage, httpMessageLen, 0);
   if(numBytes < 0) {
      DieWithSystemMessage("send() failed");
   }
   else if(numBytes != httpMessageLen) {
      DieWithUserMessage("send()", "sent unexpected number of bytes");
   }
   unsigned int totalBytesRcvd = 0;
   int firstIter = 0;
   while(1) {
      char buffer[1000000];

      numBytes = recv(sock, buffer, 1000000 - 1, 0);
      if(numBytes < 0) {
         DieWithSystemMessage("recv() failed");
      }
      if(numBytes == 0) break;
      totalBytesRcvd += numBytes;
      buffer[numBytes] = '\0';
      if(firstIter) {
         if(fileSpecified) fputs(strstr(buffer, "\r\n\r\n")+4, output);
         else fputs(strstr(buffer, "\r\n\r\n")+4, stdout);
         firstIter = 0;
      }
      else{
         if(fileSpecified) fputs(buffer, output);
         else fputs(buffer, stdout);
      }
   }

   fputc('\n', stdout);

   close(sock);
   exit(1);

}
コード例 #28
0
ファイル: recvImage_ok_close.c プロジェクト: Team-Arca/Server
void HandleTCPClient(int clientSock) {
    unsigned char buffer[BUFFSIZE];
    int image_file;
    int total_recv=0;
    int image_size;
    int flag = 0;
    int numByteRcvd=0;
    int numByteSent=0;
    int connect_state =1;
    int store_state =0;
    while(connect_state) {
        switch(flag) {
        case 0:

            bzero(buffer,BUFFSIZE);
            numByteRcvd = read(clientSock, buffer, 20);
            if(numByteRcvd <=0) {
                printf("don't read data \n");
                connect_state =0;
                break;
            }

            image_size = atoi(buffer);
            printf("image size : %d\n",image_size);

            if( !(image_size == 0 || image_size > 10000)) { // if image_size ie wrong value cloase socket
                if(store_state)
                    image_file = open("ready_img0.jpg", O_WRONLY | O_CREAT | O_TRUNC , S_IRWXU | S_IRWXG | S_IRWXO);
                else
                    image_file = open("ready_img1.jpg", O_WRONLY | O_CREAT | O_TRUNC , S_IRWXU | S_IRWXG | S_IRWXO);
                flag = 1;
            }
            break;
        case 1:
            if(total_recv == image_size) {
                store_state = (store_state+1) %2;
                total_recv =0;
                flag = 2;
                close(image_file);
                printf("success recv image\n");
                pid_t pid = fork();
                if(pid == 0) {
                    printf("name change\n");
                    if(store_state)
                        execlp("mv","mv","ready_img1.jpg","robot_view.jpg",NULL);
                    else
                        execlp("mv","mv","ready_img0.jpg","robot_view.jpg",NULL);
                    exit(0);
                }
                //wait(&state);
            }
            else {
                bzero(buffer,image_size);
                numByteRcvd = read(clientSock, buffer, image_size - total_recv);
                if(numByteRcvd <=0) {
                    printf("recv data error\n");
                    connect_state =0;
                    break;
                }
                total_recv += numByteRcvd;
                numByteSent = write(image_file, buffer, numByteRcvd);
                printf("write data size : %d\n",numByteRcvd);
            }
            break;

        default:
            flag = 0;
            numByteSent = write(clientSock, "OK", 20);
            if(numByteRcvd <=0) {
                printf("send Ack error\n");
                connect_state =0;
                break;
            }
            connect_state =0;
            break;

        }
        if(numByteRcvd < 0)
            DieWithUserMessage("recv() failed");
    }
    printf("Close socket\n");
    close(clientSock); // 클라이언트 소켓 종료
}
コード例 #29
0
ファイル: client.c プロジェクト: jsjessen/school
// *** CLIENT ***
int main(int argc, char* argv[])
{
    // Get server address and port from commandline arguments
    if(argc < 2 || argc > 3)
        DieWithUserMessage("Parameter(s)", "<Server Address> [<Server Port>]");
    char* servIP = argv[1]; // server IP address (dotted quad)
    in_port_t servPort = (argc == 3) ? atoi(argv[2]) : 51717;

    // Create a reliable, stream socket using TCP
    int sock;
    if((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
        DieWithError(sock, "socket() failed");

    // Construct server address structure
    struct sockaddr_in servAddr; 
    memset(&servAddr, 0, sizeof(servAddr));
    servAddr.sin_family      = AF_INET;            // Internet address family
    servAddr.sin_addr.s_addr = inet_addr(servIP);  // Server IP address
    servAddr.sin_port        = htons(servPort);    // Server port

    // Connect to server 
    if(connect(sock, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0)
        DieWithError(sock, "connect() failed");

    // Listen for welcome message
    char* welcomeMsg = recv_termed(sock);
    puts(welcomeMsg);
    if(strcmp(welcomeMsg, "Welcome") != 0)
        DieWithError(sock, "Not Welcome :("); // let OS free msg
    free(welcomeMsg);

    // Prompt user for ID, send to server (assuming non-malicious user)
    char myID[32];
    printf("Enter ID: ");
    scanf("%s", myID);
    send_termed(sock, myID);

    // Prompt user Name, send to server (assuming non-malicious user)
    char myName[32];
    printf("Enter Name: ");
    scanf("%s", myName);
    send_termed(sock, myName);

    // Wait for server validation response
    char* validation = recv_termed(sock);
    printf("Validation(%s)\n", validation);
    if(strcmp(validation, "Success") != 0)
        DieWithError(sock, "Invalid ID/Name");
    free(validation);

    // Prompt user of Password, send to server (assuming non-malicious user)
    char myPwd[32];
    printf("Enter Password: "******"%s", myPwd);
    send_sized(sock, myPwd);

    // Wait for server password response
    char* response = recv_sized(sock);
    printf("%s\n", response);
    free(response);

    // Close the connection
    close(sock);
    return 0;
}
コード例 #30
0
int main(int argc, char *argv[]) {
	FILE * inputFile;
	if (argc < 2 || argc>3) 
		DieWithUserMessage("Parameter(s)","<Server Name> [LClient.txt]");
	if(argc==3)
	{
		inputFile = fopen (argv[2] , "r");
		if (inputFile == NULL)
			DieWithSystemMessage("File Open Error!");
	}
	if(argc==2)
	{
		inputFile =stdin;
	}
	char *servName = argv[1];
	char *servIP=getIPbyHostName(servName, addr);//Get Server IP by Server Name

	FILE *fp;
	if((fp=fopen("LClient.log","w"))==NULL)
		DieWithSystemMessage("File Open Error!");

	//===========Deal with Login Command============
	char _CMDString[MAXLEN_CMD];
	char *CMDString=_CMDString;

	beforeLogin:fputs("Please use login command to connect to the server first as [login <name>]:\n", stdout);

	if(fgets(CMDString,MAXLEN_CMD,inputFile)== NULL)
		DieWithSystemMessage("Input Error!");
	//printf("string length:\t%d\n",strlen(CMDString));
	while((Login(CMDString))!=1)
	{
		fputs("\nLogin again:\n", stdout);
		if(fgets(CMDString,MAXLEN_CMD,inputFile)== NULL)
			DieWithSystemMessage("Input Error!");
	}

	//===========End of dealing with Login Command, and Get the name=========


	//===========initiate the socket =====================	
	in_port_t servPort =atoi("5000");// Set server port (numeric) 5000	
	int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);// Create a reliable, stream socket using TCP
	if (sock < 0)
		DieWithSystemMessage("socket() failed");	
	struct sockaddr_in servAddr;// Construct the server address structure
	memset(&servAddr, 0, sizeof(servAddr)); // Zero out structure
	servAddr.sin_family = AF_INET;			   // IPv4 address family
	// Convert address
	int rtnVal = inet_pton(AF_INET, servIP, &servAddr.sin_addr.s_addr);
	if (rtnVal == 0)
		DieWithUserMessage("inet_pton() failed", "invalid address string");
	else if (rtnVal < 0)
		DieWithSystemMessage("inet_pton() failed");
	servAddr.sin_port = htons(servPort);		// Server port
	//===========END initiate the socket =====================




	//===========Establish the connection to the echo server=============
	if (connect(sock, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0)
		DieWithSystemMessage("connect() failed");
	IsLogined=1;  //Connection Established, and this means someone logined successfully
	char buffer[BUFSIZE];

	int IsListCmd=0;

	//char IsListDone[5]="Done";
	char QUIT[2]="*";
	char _EOF[2]="$";
	int IsReLogin=0;
	for(;;)
	{		
		//puts(CMDString);
		ssize_t numBytes = send(sock, CMDString, strlen(CMDString), 0);
		if (numBytes < 0)
			DieWithSystemMessage("send() failed");
		else if (numBytes != strlen(CMDString))
				DieWithUserMessage("send()", "sent unexpected number of bytes");

		if(IsListCmd==0)
		{
			bufferClean(buffer);
			numBytes = recv(sock, buffer, BUFSIZE - 1, 0);
			if (numBytes < 0)
				DieWithSystemMessage("recv() failed");
			buffer[numBytes] = '\0';// Terminate the string!	
			if(strncmp(buffer,QUIT,1)==0)
			{
				fputs(buffer, fp);
				fputs("\r\n",fp);
				labelQUIT:close(sock);
				goto beforeLogin;
			}

			if(strncmp(buffer,_EOF,1)==0)
			{
				fputs(buffer, fp);
				fputs("\r\n",fp);
				labelEOF:close(sock); 
				if(argc==3)
					fclose(fp);
				fclose(inputFile);
				exit(0);
			}
			if(IsReLogin!=1)
			{
				fputs(buffer, stdout);
				fputs("\n",stdout);
				fputs(buffer, fp);
				fputs("\r\n",fp);
			}
		}
		else
		{	
			int i=0;
			while(IsListCmd==1)
			{
				bufferClean(buffer);
				numBytes = recv(sock, buffer, BUFSIZE - 1, 0);
				if (numBytes < 0)
					DieWithSystemMessage("recv() failed");

				for(i=0;i<strlen(buffer);i++)
				{
					int buffer_Length=strlen(buffer);
					if(buffer[i]=='#')
					{
						buffer[i]='\0';
						fputs(buffer, stdout);
						fputs(buffer, fp);
						/*if(i<buffer_Length)
						{
							i++;
							for(;i<buffer_Length;i++)
							{
								if(buffer[i]=='*')
								{
									puts("QUIT Here!");
									goto labelQUIT;
								}
								if(buffer[i]=='$')
									goto labelEOF;
								fputc(buffer[i],stdout);
								fputc(buffer[i],fp);
							}
						}*/
						IsListCmd=0;
						fputs("\n",stdout);
						//goto ListDone;
						break;
					}
				}
				if(IsListCmd==0)
					break;
				fputs(buffer, stdout);
				fputs(buffer, fp);

			}
		}
		bufferClean(buffer);
		for(;;)
		{
			int IsInputLegal=0;
			bufferClean(CMDString);

//ListDone:
			if(fgets(CMDString,MAXLEN_CMD,inputFile)== NULL)
				DieWithSystemMessage("Input Error!");
			CMDString=trimRight(CMDString);
			//gets(CMDString);    //input another Command
			switch(CommandCheckAndReturncmdCode(CMDString))
			{
				case 1: if(IsLogined==1)
							{
								fputs("You have logined already. Please quit first!\n", stdout);
								IsInputLegal=0;
							} 
							else 
							{
								if(Login(CMDString)==1) 
									IsInputLegal=1;
							}
							break;
				case 2: if(Add(CMDString)==1) IsInputLegal=1; break;
				case 3: if(Remove(CMDString)==1) IsInputLegal=1; break;
				case 4: if(List(CMDString)==1) {IsInputLegal=1;IsListCmd=1;} break;
				case 5: if(Quit(CMDString)==1) {IsInputLegal=1;IsLogined=0;}; break;
				default:IsInputLegal=0;break;
			}
			if(IsInputLegal==1)
				break;
			else
				continue;
		}

	}
	
}