2011-08-18 81 views
0

我从Andy Tanenbaum的书中得到了这段代码。我正在尝试运行它。它编译并等待连接。但是当我输入localhost:886时,我在浏览器或终端中看不到任何效果。 (它应该按照代码回显一个新的连接字符串)。Linux服务器编程

#define  SERVER_PORT   886  /* The port at which the server listens */ 
#define  BUF_SIZE  64032  /* The size of buffer for request and response */ 
#define  QUEUE_SIZE  10  /* Block transfer size */ 


int main (int argc, char* argv[]) { 

    int  sock = 0, bnd = 0, lst = 0, fd = 0, sa = 0, bytes = 0, on = 1, conn_count = 0; 
    char buf[BUF_SIZE]; 
    struct sockaddr_in channel;   /* IP address holder */ 

    /* The address structure that binds with the socket */ 

    memset (&channel, 0, sizeof(channel)); 

    channel.sin_family  = AF_INET; 
    channel.sin_addr.s_addr  = htonl (INADDR_ANY); 
    channel.sin_port  = htons (SERVER_PORT); 

    /* Parital opening of the socket, while waiting for connection */ 

    sock    = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); /* Creates a new socket */ 
    if (sock < 0) 
     printf ("Partial opening of the socket failed! Error: %d", sock); 

    setsockopt (sock, SOL_SOCKET, SO_REUSEADDR, (char *) &on, sizeof(on)); 

    bnd    = bind (sock, (struct sockaddr *) &channel, sizeof(channel)); 
    if (bnd < 0) 
     printf ("Binding failure! Error: %d", bnd); 

    lst    = listen (sock, QUEUE_SIZE); 
    if (lst < 0) 
     printf ("Unable to listen on the socket! Error: %d", lst); 

    /* The socket has been set-up. Wait for the connection and process it. */ 

    while (1) { 

     conn_count  += 1; 
     printf ("Received connection: %d", conn_count); 
     sa   = accept (sock, 0, 0); 
     if (sa < 0) 
      puts ("Unable to accept the socket opened for connection."); 

     read (sa, buf, BUF_SIZE); 

     puts (buf);  /* Output the string to the screen */ 

     close (sa); 
    } 
} 
+0

尝试'远程登录本地主机的所有端口:886'在命令行上。 –

+0

您可以通过'netstat'确认您的程序是否实际正在侦听适当的端口。 –

+0

'netstat -tlnp' – Flavius

回答

5

你是以sudo/root身份运行吗?您的bind()可能会因为使用特权端口而失败。


[更新自评:]

特权端口是1024以下

+0

嗯。让我试试sudo – john

+0

并结合缺少\ n你还没有看到失败的绑定的错误消息。 –

+0

就是这样。测试程序绑定到1024以上的某个随机端口(我的一个启动时为36969),当连接到端口并发送一个字符串时,它输出:'绑定失败!错误:-1Received连接:1test'。我猜,-1是'EACCES'。 – ulidtko

1

尝试将断行 '\ n' 你

printf ("Received connection: %d\n", conn_count); 

行的末尾。

否则stdout不会直接刷新,你什么都看不到。

+0

对于其他行也这样做,否则你将看不到错误信息:/ –

0

而不是使用printf()stdout,尝试所有的输出转变为fprintf()stderr它没有缓冲......让他们立即输出所谓的,而不是由缓冲的时候我会做同样的错误消息以及stdout

最后,如果您想查看错误消息的含义,请使用strerror()和错误编号。所以,你可以这样类似:

if (bnd < 0) 
{ 
    fprintf(stderr, "Binding failure! Error: %s", strerror(bnd)); 
    exit(1); 
} 

确保为strerror()你也做一个include<string.h>在某处你的代码模块的开始。

+0

也是,错误后退出,没有理由继续......这似乎是一个小玩具服务器,你不应该'用于生产。检查http://www.unpbook.com/更严重的东西。 –

+0

@Jason现在我得到这个帮助:绑定失败!错误:-1接收连接:1 ** **'我有点困惑,它无法绑定套接字,但它仍然功能! – john

+0

它不起作用。但是一个简单的printf不会停止你的程序,你需要一些退出/返回或其他东西来打印错误信息。 –