服务器端程序
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);
}
}
}
客户计划:
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);
}
}
当我尝试将某些客户端连接到服务器时,服务器从第一个客户端接收第一条消息作为空白消息,并将第一个客户端IP打印为127.0.0.1,对于其他客户端,服务器正确打印其IP地址并接收消息来自客户?是这样吗? y是从第一个客户端接收第一条消息作为空白消息的服务器? y是服务器打印第一个客户端的IP地址为127.0.0.0?有些人可以帮助我......
提前致谢。
的问候, Sudharsanam。