运行客户代码后出现错误:
connection refused.
请问这是为什么?看了一些网站说是服务器端没有监听,可是服务器端运行正常啊。。。
主机:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <unistd.h>
#define SERVPORT 2121
#define BACKLOG 10
main()
{
int sockfd,client_fd,recv_client;
struct sockaddr_in my_addr;
struct sockaddr_in remote_addr;
char temp[100];
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket error"); exit(1);
}
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(SERVPORT);
my_addr.sin_addr.s_addr = inet_addr("192.168.1.103");// INADDR_ANY;
bzero(&(my_addr.sin_zero),8);
if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1)
{
perror("bind error");
exit(1);
}
if (listen(sockfd, BACKLOG) == -1)
{
perror("listen error");
exit(1);
}
while(1)
{
socklen_t sin_size = sizeof(struct sockaddr_in);
if ((client_fd = accept(sockfd, (struct sockaddr *)&remote_addr, &sin_size)) == -1)
{
perror("accept error");
continue;
}
printf("received a connection from %s\n", inet_ntoa(remote_addr.sin_addr));
if (!fork())
{
if((recv_client=recv(sockfd,temp,100,0))==-1)
{
perror("recv_client error");
exit(0);
close(client_fd);
}
if(strcmp(temp,"get")==0)
{
printf("get\n");
}
if(strcmp(temp,"put")==0)
{
printf("put\n");
}
else
{
printf("clinet requset error,check argv[2]\n");
exit(0);
}
}
}
}
客户:
#include<stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#define SERVPORT 3343
#define MAXDATASIZE 100
main(int argc, char *argv[])
{
int sockfd, recvbytes,host_fd;
char buf[MAXDATASIZE];
struct hostent *host;
struct sockaddr_in serv_addr;
if (argc < 2)
{
fprintf(stderr,"Please enter the server's hostname!\n");
exit(1);
}
if((host=gethostbyname(argv[1]))==NULL)
{
herror("gethostbyname error");
exit(1);
}
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket error");
exit(1);
}
serv_addr.sin_family=AF_INET;
serv_addr.sin_port=htons(SERVPORT);
serv_addr.sin_addr = *((struct in_addr *)host->h_addr);
bzero(&(serv_addr.sin_zero),8);
if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr)) == -1)
{
perror("connect error");
exit(1);
}
if((host_fd=send(sockfd,&argv[2],sizeof(&argv[2]),0))==-1)
{
perror("host_fd error");
exit(1);
}
close(sockfd);
}