首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Linux服务器编程

Linux服务器编程
EN

Stack Overflow用户
提问于 2011-08-18 23:32:46
回答 3查看 481关注 0票数 0

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

代码语言:javascript
复制
#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);
    }
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-08-18 23:55:10

您是否以sudo/root身份运行此应用程序?您的bind()可能会失败,因为它正在使用特权端口。

来自评论的更新:

特权端口是1024以下的所有端口。

票数 5
EN

Stack Overflow用户

发布于 2011-08-18 23:44:36

尝试将换行符'\n‘放在您的

代码语言:javascript
复制
 printf ("Received connection: %d\n", conn_count); 

线路。

否则,不会直接刷新stdout,您将什么也看不到。

票数 1
EN

Stack Overflow用户

发布于 2011-08-18 23:49:32

与其使用printf()stdout,不如尝试将所有输出更改为没有缓冲的fprintf()stderr……我也会对错误消息执行同样的操作,以便它们在被调用时立即输出,而不是由stdout缓冲。

最后,如果您想了解错误消息的含义,可以使用带有错误号的strerror()。所以你可以这样做:

代码语言:javascript
复制
if (bnd < 0)
{
    fprintf(stderr, "Binding failure! Error: %s", strerror(bnd));
    exit(1);
}

确保对于strerror(),您还在代码模块开头的某个位置执行了include<string.h>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7110059

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档