客户端请求连接时,服务器不接受连接

时间:2013-03-18 09:10:02

标签: c sockets

我的服务器不接受客户端发送的连接请求,客户端从中收到任何内容。当客户端请求它时我的服务器停机。 我的代码如下: 服务器代码:

*#include<sys/socket.h>
#include<netinet/in.h>
#include<stdio.h>
#include<sys/types.h>
#include<string.h>
int main()
{
    int sock,bnd,con,lis,size,clilen;
    char *msg="WELCOME!!!!!";
    struct sockaddr_in sockadd,cliadd;
    //Socket Created.....
    sock=socket(AF_INET,SOCK_STREAM,0);
    if(sock!=-1)
    printf("socket created");
    else
    printf("Not created");

        // defining  Address of sockets
    sockadd.sin_family=AF_INET;
    sockadd.sin_port=htons(5001);
    sockadd.sin_addr.s_addr=htonl(INADDR_ANY);
    bnd=bind(sock,(struct sockaddr *) &sockadd,sizeof(sockadd));
    if(bnd==-1)
    printf("NOT BOUND");
    else
    printf("BOUND");

    lis=listen(sock,10);
    if(lis!=-1)
    printf("listning");
    else
    printf("not listening");
    printf("\nWaiting for connection at %s port no %d\n",inet_ntoa(sockadd.sin_addr),ntohs(sockadd.sin_port));
    while(1)
    {
        clilen=sizeof(cliadd);
        con=accept(sock,(struct sockaddr *) &cliadd, &clilen);
        if(con==-1)
        printf("connected not");
        else
        printf("conneted");
        size=send(sock,msg,sizeof(msg),0);
        if(size==-1)
        printf("not sent");
        else
        printf("BYTES SENT: %d",size);
        close(con);
        sleep(2);
    }
    return(0);*

和客户端代码是:

    int sock,bnd,con,lis,size;
    char msg[35];
    struct sockaddr_in sockadd;
    //Socket Created.....
    sock=socket(AF_INET,SOCK_STREAM,0);
    if(sock!=-1)
    printf("socket created");
    else
    printf("Not created");
    //return(0);        
        // defining  Address of sockets
    sockadd.sin_family=AF_INET;
    sockadd.sin_port=htons(5001);
    sockadd.sin_addr.s_addr=inet_addr("10.3.5.172");
    /*puts(sockadd.sin_family);
    puts(sockadd.sin_port); 
    puts(sockadd.sin_addr.s_addr);      
    if(inet_pton(AF_INET, argv[1], &sockadd.sin_addr)<=0)
       {
         printf("\n inet_pton error occured\n");
            return 1;
        } */
    con=connect(sock, (struct sockaddr *)&sockadd, sizeof(sockadd)) ;
    if(con==-1)
        {
        printf("\n Error : Connect Failed \n");
             return 1;
        } 
    else
    printf("successful");
    size=recv(sock,msg,sizeof(msg),0);
    printf("msg recieved:%s",msg);
    printf("bytes recieved:%d",size);
}*

1 个答案:

答案 0 :(得分:2)

您正尝试发送服务器套接字!

  size=send(sock,msg,sizeof(msg),0); // ERROR, this is a server socket!

尝试发送新连接:

  size=send(con,msg,sizeof(msg),0);