将客户端连接到服务器?

时间:2015-03-04 11:36:20

标签: c network-programming client server

我有一个简单的问题要问你。我正在尝试制作一个简单的客户端 - 服务器程序。我想将客户端连接到服务器,但我收到以下错误:无法连接到服务器。我是新手,这就是为什么我可以解决问题所在。请给我一些提示。这是我的客户端/服务器代码:

客户端:

#include<sys/socket.h>
#include<netinet/in.h>
#include<stdio.h>
#include<string.h>
#include<stdint.h>

int main(){
    int socketc;
    int connectnr;
    int c;
    struct sockaddr_in server;
    char buffer[256];

    socketc = socket(PF_INET, SOCK_STREAM, 0);
    if(socketc < 0){
        fprintf(stderr, "Error: Can't create client socket.\n");
        return 1;
    }

    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(4321);
    server.sin_addr.s_addr = inet_addr("127.0.0.1");

    connectnr = connect(c, (struct sockaddr *) & server, sizeof(struct    sockaddr_in));
    if(connectnr < 0){
        printf("connectnr %d: \n", connectnr);
        fprintf(stderr, "Error: Can't connect to the server.\n");
        return 1;
    }

    close(c);
}

服务器:

#include<sys/socket.h>
#include<netinet/in.h>
#include<stdio.h>
#include<string.h>
#include<stdint.h>
#include<signal.h>
#include<unistd.h>
#include<stdlib.h>

int c;

int main(){
    int connsocket;
    int bindcod;
    int l;
    struct sockaddr_in client, server;

connsocket = socket(PF_INET, SOCK_STREAM, 0);
if(connsocket < 0){
    fprintf(stderr, "Error: Can't create the server socket.\n");
    return 1;
}

memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(4321);
server.sin_addr.s_addr = INADDR_ANY;

bindcod = bind(connsocket, (struct sockaddr *) &server, sizeof(struct sockaddr_in));
if(bindcod < 0){
    fprintf(stderr, "Error: Con't establish the bind. Port is already used.\n");
    return 1;
}

listen(connsocket, 5);

while(1){
    memset(&client, 0, sizeof(client));
    l = sizeof(client);
    printf("Waiting for the client to connect,\n");
    c = accept(connsocket, (struct sockaddr *) &client, &l);
    printf("New client connected with address %s and port %d.\n", inet_ntoa(client.sin_addr), ntohs(client.sin_port));
}
}

1 个答案:

答案 0 :(得分:1)

您为连接功能提供了错误的套接字。

替换

  

connect(c,(struct sockaddr *)&amp; server,sizeof(struct sockaddr_in));

  

connect( socketc ,(struct sockaddr *)&amp; server,sizeof(struct sockaddr_in));