C语言 C中的套接字编程(客户端服务器示例)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18489271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:18:13  来源:igfitidea点击:

Socket Programming in C(Client Server Example)

csocketsunixclient-server

提问by user2725511

I am completely new to programming in unix and have written the following code for client and server programming. When I try to run the client code it says "Connection refused". Could somebody please tell me what could be the reason of it.

我对 unix 编程完全陌生,并为客户端和服务器编程编写了以下代码。当我尝试运行客户端代码时,它显示“连接被拒绝”。有人可以告诉我可能是什么原因。

Server Code :

服务器代码:

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include <errno.h>
#include<string.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(void)
{
    int sockid,newsockid;
    socklen_t addr_size;
    char *msg="What a beautiful morning!";
    int len, bytes_sent;
    sockid=socket(AF_INET,SOCK_STREAM,0);
    if(sockid==-1)
    {
        perror("socket");
        exit(1);
    }
    else
        printf("created");
    struct sockaddr_in serveraddr,clientaddr;
    bzero((char *)&serveraddr,sizeof(serveraddr));
    serveraddr.sin_family=AF_INET;
    serveraddr.sin_port=htons(7400);
    serveraddr.sin_addr.s_addr=INADDR_ANY;

    if(bind(sockid,(struct sockaddr *)&serveraddr,sizeof(serveraddr))<0)
    {
        perror("bind");
        return -1;
    }

    listen(sockid,5);
    addr_size=sizeof(clientaddr);
    newsockid=accept(sockid,(struct sockaddr *)&clientaddr,&addr_size);
    len = strlen(msg);
    bytes_sent = send(sockid, msg, len, 0);
    close(sockid);
}

Client Code :

客户代码:

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include <errno.h>
#include<string.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(void)
{
    int byte_count;
    struct sockaddr_in serveraddr;
    char *servername;
    char buf[256];
    socklen_t addr_size;
    int sockfd;

    sockfd=socket(AF_INET,SOCK_STREAM,0);
    bzero(&serveraddr,sizeof(serveraddr));
    serveraddr.sin_family=AF_INET;
    serveraddr.sin_port=htons(11378);
    servername=gethostbyname("localhost");
    inet_pton(AF_INET,servername,&serveraddr.sin_addr);

    addr_size=sizeof(serveraddr);
    if(connect(sockfd,(struct sockaddr *)&serveraddr,addr_size)==-1)
    {
        perror("connect");
        exit(1);
    }

    byte_count = recv(sockfd, buf, sizeof buf, 0);
    printf("recv()'d %d bytes of data in buf\n", byte_count);

    close(sockfd);
}

An early help would be appreciated. Thanks.

早期的帮助将不胜感激。谢谢。

采纳答案by nouney

sockfd=socket(AF_INET,SOCK_STREAM,0);
bzero(&serveraddr,sizeof(serveraddr));
serveraddr.sin_family=AF_INET;
serveraddr.sin_port=htons(7400);
inet_pton(AF_INET,servername,&serveraddr.sin_addr); // here

You're passing servernameto inet_pton()but it is not initialized ! So inet_pton()will fail. You should check its return value.

您正在传递servernameinet_pton()但未初始化!所以inet_pton()会失败。您应该检查它的返回值。

servername=gethostbyname(); //here
addr_size=sizeof(serveraddr);

The second problem is that you're not using gethostbyname()correctly.Take a look at the manpage, you will see that gethostbyname()is taken arguments and it returns a pointer to a struct hostent, not a pointer to charlike you did. Your compiler doesn't warn you about this because you don't include netdb.h.

第二个问题是你没有gethostbyname()正确使用。看看手册,你会看到它gethostbyname()被接受了参数,它返回一个指向 a 的指针struct hostent,而不是char像你那样指向的指针。您的编译器不会就此警告您,因为您没有包含netdb.h.

You should check the return values of all the functiond that you are using, it's avoid problems like that. You should enable some flags of your compiler (like alksaid in the question comments, -W -Wextra -Wall -pedanticare really great flags).

你应该检查你正在使用的所有函数的返回值,避免这样的问题。您应该启用编译器的一些标志(如问题评论中的alk所说,-W -Wextra -Wall -pedantic是非常棒的标志)。

回答by Jeyamaran

check the port. server port is 7400 but the client try to connect with port number 11378 so only connection has been refused.

检查端口。服务器端口是 7400,但客户端尝试使用端口号 11378 进行连接,因此只有连接被拒绝。

回答by NeilBlue

Make sure to include errno.h in your program.
Add line printf("%s", strerr(errno));in your program after any failure. Any system call failure sets correct errno making it simple to diagnose the problem.

确保在您的程序中包含 errno.h。任何失败后在程序中
添加行 printf("%s", strerr(errno));。任何系统调用失败都会设置正确的 errno,从而使诊断问题变得简单。

回答by user2699113

Well, you have to be sure that your server is running and listening on proper port (7400). Just check with: "netstat -tanp" if there is something listening on port 7400 and then try to connect.

好吧,您必须确保您的服务器正在运行并侦听正确的端口 (7400)。只需检查:“netstat -tanp”是否有东西在端口 7400 上侦听,然后尝试连接。