开发者

How do i print client address while running server code in socket

开发者 https://www.devze.com 2023-04-06 06:43 出处:网络
I am trying to modify a server code which is listening to different client ,now i want to print a line like \"got connection fromclinet address\".but how do i achieve this .this is the server code.

I am trying to modify a server code which is listening to different client ,now i want to print a line like "got connection from clinet address".but how do i achieve this .this is the server code.

  #include <stdio.h>
  #include <unistd.h>
  #include <stdlib.h>
  #include <string.h>
  #include <sys/types.h> 
  #include <sys/socket.h> 
  #include <netinet/in.h>

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


 int sockfd, newsockfd, portno, pid;开发者_开发问答

 socklen_t clilen;

 struct sockaddr_in serv_addr, cli_addr;

 if (argc < 2) {

     fprintf(stderr,"ERROR, no port provided\n");

     exit(1);
 }

 sockfd = socket(AF_INET, SOCK_STREAM, 0);

    if (sockfd < 0) 
    error("ERROR opening socket");

  bzero((char *) &serv_addr, sizeof(serv_addr));
  portno = atoi(argv[1]);
  serv_addr.sin_family = AF_INET;
  serv_addr.sin_addr.s_addr = INADDR_ANY;
  serv_addr.sin_port = htons(portno);
  if (bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) 

          error("ERROR on binding");

 listen(sockfd,5);

 clilen = sizeof(cli_addr);
    while (1) 
   {

    newsockfd = accept(sockfd,(struct sockaddr *) &cli_addr, &clilen);

     if (newsockfd < 0) 
         error("ERROR on accept");

   printf("got connection from %s",&cli_addr);

     pid = fork();

     if (pid < 0)

     error("ERROR on fork");

      if (pid == 0) 
     {

         close(sockfd);

         exit(0);
     }
     else

    close(newsockfd);

     } /* end of while */

   close(sockfd);

   return 0; /* we never get here */
     }

Printf("got connection from %s",&cli_addr);

In this particular line i have to prinnt client address


Use inet_ntoa function to convert binary ip address to dot notation.


Use inet_ntop to show the client address as following:

printf("Client Adress = %s",inet_ntop(AF_INET,&cli_addr.sin_addr,
                    clientname,sizeof(clientname)));
0

精彩评论

暂无评论...
验证码 换一张
取 消