在Linux中将客户端连接到服务器

时间:2018-12-11 07:23:25

标签: c linux sockets server client

我正在尝试将客户端连接到远程服务器上的服务器。我们被告知任何允许超过8 000的端口号,因此我认为这不是问题。但是,我尝试连接时收到错误连接超时。我读过的所有内容似乎都表明该端口有问题。

Client.c

char sendbuff[1024];
char getbuff[1024];
int newsocket = 0;
int prt       = 9345;
//struct hostent *server;

int main( int argc, char** argv )
{
    struct sockaddr_in serv_addr;
    struct hostent *hp;
    if( ( newsocket=socket(AF_INET, SOCK_STREAM,0 ) ) < 0 )
    {
        printf( "ERROR: can't create socket" );
    }
    char *hostname = argv[1];

    hp = gethostbyname( hostname );
    memcpy( ( void* )&serv_addr.sin_addr, hp->h_addr_list[0], hp->h_length );
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port   = htons(prt);

    while( connect( newsocket,( struct sockaddr*  )&serv_addr, sizeof( serv_addr ) ) < 0 )
    {
        perror( "ERROR%" );
        sleep( 3 );
    }
    memset( getbuff,'\0',sizeof ( getbuff ) );
    recv( newsocket, getbuff, sizeof( getbuff ), 0 );
    printf( "test%s\n",getbuff );
    return 0;
}

Server.C

char sendbuff[1024];
char getbuff[1024];
int prt = 9345;
int main( int argc, char** argv )
{
    printf( "server testing\n" );
    bank = newBank();

    pthread_t listenforclients; /* listen for clients*/
    if( pthread_create( &listenforclients, 0, listenforclients_thread, 0 ) != 0 )
    {
        printf("error\n");
    }
    pthread_join(listenforclients,NULL);
    return 0;
}

void* listenforclients_thread( void* arg )
{
    char buffer[1025];
    int listening=0;
    int accepted=0;
    listening=socket( AF_INET, SOCK_STREAM, 0 );

    struct sockaddr_in serv_addr;
    memset( &serv_addr, '0', sizeof( serv_addr ) );
    memset( buffer,'\0', sizeof buffer ) );

    serv_addr.sin_family      = AF_INET;
    serv_addr.sin_addr.s_addr = htonl( INADDR_ANY );
    serv_addr.sin_port        = htons( prt );
    printf( "test before bind\n" );
    bind( listening, ( struct sockaddr* )&serv_addr,  sizeof( serv_addr ) );


    if( listen( listening, 10 ) == -1 )
    {
        printf("ERROR:listen errpr\n");
        return NULL;
    }

    while ( 1 )
    {
        if(  listen( listening, 10 ) == -1 )
        {
            printf( "ERROR,Listen error\n" );
        }

        printf( "servertest2\n" );
        accepted = accept( listening,( struct sockaddr* )NULL, NULL );
        memset( sendbuff, '\0', sizeof( sendbuff ) );
        sprintf( sendbuff, "Server Connection Succesful" );
        send( accepted, sendbuff, strlen( sendbuff ), 0 );
        pthread_t talk_to_client;
        if( pthread_create( &talk_to_client, 0, clientopening, 0 ) != 0 )
        {
            printf( "error" );    
        }
    }
    return NULL;
}

我更改了端口号以查看是否有任何作用,但得到的结果相同。 arg [1]是我转换为IP地址的主机名。超时的原因可能是什么?

0 个答案:

没有答案