我正在尝试在我的本地主机上的Ubuntu 11.04中实现TCP echo服务器和客户端程序。但是,我陷入了绑定功能。 这是我的代码。
TCPSERVER
#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中编译后我收到绑定错误..我上传了整个代码,因为我自己没有收到任何错误,需要帮助。
答案 0 :(得分:1)
正好在代码错误之下:
if(listenfd=socket(AF_INET,SOCK_STREAM,0)<0)
{
printf("\nServer Error:Cannot create socket.\n");
exit(1);
}
“=”的优先级低于“&lt;”,修改如下,你的程序就可以了:
if( (listenfd = socket(AF_INET,SOCK_STREAM,0)) < 0)
{
printf("\nServer Error:Cannot create socket.\n");
exit(1);
}