最近因为课程需要学习socket网络编程,运行的时候客户端无法与服务器建立连接,请原谅菜鸟没有积分,希望各位大佬给点帮助,解决下问题
这个是运行报错的截图
以下是按照课本上编写的代码
客户端client.c
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#define PROTOPORT 5188
extern int errno;
char localhost[] = "localhost";
int main(int argc, char* argv[])
{
struct hostent *ptrh;
struct sockaddr_in servaddr;
int sockfd;
int port;
char* host;
int n;
char buf[1000];
memset((char*)&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
if(argc > 2){
port = atoi(argv[2]);
}else{
port = PROTOPORT;
}
if(port > 0){
servaddr.sin_port = htons((uint16_t)port);
}else{
fprintf(stderr, " bad port number %s\n", argv[2]);
exit(1);
}
if(argc > 1){
host = argv[1];
}else{
host = localhost;
}
ptrh = gethostbyname(host);
if((char*)ptrh == NULL){
fprintf(stderr, " invalid host: %s\n", host);
exit(1);
}
memcpy(&servaddr.sin_addr, ptrh->h_addr_list[0], ptrh->h_length);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd > 0){
fprintf(stderr, " socket creation failed\n");
exit(1);
}
//请求连接到服务器
if(connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr))){
fprintf(stderr, "connect failed\n");
exit(1);
}
//从服务器读取数据,显示到用户屏幕上
n = recv(sockfd, buf, sizeof(buf), 0);
while(n > 0){
write(1, buf, n);
n = recv(sockfd, buf, sizeof(buf), 0);
}
//关闭连接
close(sockfd);
//退出
exit(0);
return 0;
}
服务器端server.c
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <string.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdlib.h>
#include <unistd.h>
#define PROTOPORT 5188
#define QLEN 6
int visits = 0;
int main(int argc, char * argv[])
{
struct sockaddr_in servaddr; //存放服务器网络地址结构
struct sockaddr_in clientaddr; //存放客户机网络地址结构
int listenfd;
int clientfd;
int port;
int alen;
char buf[1000];
memset((char*)& servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = INADDR_ANY;
if(argc >1){
port = atoi(argv[1]);
}else{
port = PROTOPORT;
}
if(port > 0){
servaddr.sin_port = htons((uint16_t)port);
}else{
fprintf(stderr, " bad port nuber %s\n", argv[1]);
exit(1);
}
listenfd = socket(AF_INET, SOCK_STREAM, 0);
if(listenfd < 0){
fprintf(stderr, "socket creation failed\n");
exit(1);
}
if(bind(listenfd, (struct sockaddr*) & servaddr, sizeof(servaddr)) < 0){
fprintf(stderr, " bind failed\n");
exit(1);
}
if(listen(listenfd, QLEN) < 0){
fprintf(stderr, "listen filed\n");
exit(0);
}
while(1)
{
alen = sizeof(clientaddr);
if((clientfd = accept(listenfd, (struct sockaddr*) & clientaddr, (socklen_t*)&alen)) < 0){
fprintf(stderr, "accept failed\n");
exit(1);
}
visits++;
sprintf(buf, "this server has been contacted %d time \n", visits);
send(clientfd, buf, strlen(buf), 0);
close(clientfd);
}
return 0;
}