0

我正在尝试在本地主机上的 Ubuntu 11.04 中实现 TCP 回显服务器和客户端程序。但是,我陷入了绑定功能。这是我的代码。

TCP服务器

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

struct sockaddr_in serv_addr,cli_addr;
int listenfd,r,w,connfd,val,cli_addr_len;
unsigned short serv_port=30000;
char serv_ip[]="127.0.0.1";
char rbuff[128];
char sbuff[128];

int main()
{
    bzero(&serv_addr,sizeof(serv_addr));
    serv_addr.sin_family=AF_INET;
    serv_addr.sin_port=htons(serv_port);
    inet_aton(serv_ip,(&serv_addr.sin_addr));
    printf("\nTcp Echo server.\n");
    //creating socket

    if(listenfd=socket(AF_INET,SOCK_STREAM,0)<0)
    {
        printf("\nServer Error:Cannot create socket.\n");
        exit(1);
    }
    if(bind(listenfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr))<0)
    {
        printf("\nServer Error:cannot Bind.\n");
        close(listenfd);
        exit(1);
    }
    if((listen(listenfd,5))<0)
    {
        printf("\nServer Error:Cannot listen.\n");
        close(listenfd);
        exit(1);
    }
    cli_addr_len=sizeof(cli_addr);
    for(;;)
    {
        printf("\nServer:listening for clients.... Press Control +C to stpo echo server :\n");
        if((connfd=accept(listenfd,(struct sockaddr*)&cli_addr,&cli_addr_len))<0)
        {
            printf("\nServer Error:Cannot accept client connections.\n");
            close(listenfd);
            exit(1);
        }
        printf("\nServer:connection from client %s accepted.\n",inet_ntoa(cli_addr.sin_addr));
        if((r=read(connfd,rbuff,128))<0)
            printf("\nServer Error:Cannot receive message from client.\n");
        else
        {
            rbuff[r]='\0';
            if((w=write(connfd,rbuff,128))<0)
                printf("\nServer Error:cannot send message to the client.\n");
            else
                printf("Echoed back %s to %s.\n",rbuff,inet_ntoa(cli_addr.sin_addr));
        }
    }
}

在 ubuntu 中的 GCC 中编译后,我遇到了绑定错误。我只上传了整个代码,因为我自己没有收到任何错误并且需要帮助。

4

1 回答 1

1

就在代码的错误下方:

if(listenfd=socket(AF_INET,SOCK_STREAM,0)<0)
{
    printf("\nServer Error:Cannot create socket.\n");
    exit(1);
}

“=”的优先级低于“<”,修改如下,你的程序就ok了:

if( (listenfd = socket(AF_INET,SOCK_STREAM,0)) < 0)
{
    printf("\nServer Error:Cannot create socket.\n");
    exit(1);
}
于 2012-05-16T07:26:46.603 回答