开发者

server-client programming problem

开发者 https://www.devze.com 2023-02-22 11:32 出处:网络
SERVER SIDE PROGRAM if(bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) <0) { error(\"Error in binding\");

SERVER SIDE PROGRAM

if(bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) <0)
{
    error("Error in binding");
}

/* added newly */

while(1)
{
   listen(sockfd,5);
   newsockfd = accept(sockfd, (struct serv_addr *) &client_addr,&client_len); /*this will actually receive the client address and the length of it*/
   printf("The client ip address is:");
   printf("%s\n", inet_ntoa(client_addr.sin_addr));
   PID=fork();
   if(!PID)
   { 
     printf("Forking the new child");        
      for(;;)
      {
      /* bzero(buffer,256);  */
      n = read(newsockfd,buffer,255);
      if (n < 0)
      error("ERROR reading from socket");
      printf("Here is the message: %s\n",buffer);
      n = write(newsockfd,"I got your message\n",18);
      if (n < 0) error("ERROR writing to socket");
       bzero(buffer,256);
      }
   }
}

CLIENT PROGRAM:

sockfd = socket(AF_INET, SOCK_STREAM, 0); 
if(sockfd<0)
{
    error("Error in opening of socket");
开发者_如何转开发}
/*  gets(ip_adr);*/
serv_addr.sin_addr.s_addr =inet_addr(ip_adr);           /* the obtained ip address which is a dotted string is converted to unsigned long.*/
serv_addr.sin_family = AF_INET;          /* this information we specify that it belongs to tcp or udp*/
serv_addr.sin_port = htons(port_no);      /*htons is used because we may need to change it to network byte order which is always big endian*/
/* We need not have a binding in this because we need not have to include a specified port*/
    if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)        /* same as accept here in the client we establish a connection */
    error("ERROR connecting");
    else
            printf("Connected");
    for(;;)
    {
     /* printf("\nPlease enter the message which u need to send:\n"); */
     /* bzero(buffer,256);                                          */
    fgets(buffer,255,stdin);                                            
    n = write(sockfd,buffer,strlen(buffer));                     
    if (n < 0)
    error("ERROR writing to socket");
    bzero(buffer,strlen(buffer));
    n = read(sockfd,buffer,255);
    if (n < 0)
    error("ERROR reading from socket");
    printf("%s",buffer);

   }
}   

When I try to connect some clients to server, server receives first message as blank message from the first client and it prints the first client ip as 127.0.0.1 and for other clients the server prints their ip address correctly and also receives message from the client? y is it so? y is the server receiving the first message as blank message from the first client? y is the server printing the ip address of first client as 127.0.0.0? Can some body help me.....

Thanks in advance.

regards, Sudharsanam.

0

精彩评论

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