tcp套接字服务器不发送

时间:2016-04-14 11:29:42

标签: c++ sockets

我有这个代码,我从同一台PC上的虚拟机运行客户端它可以连接,但它永远不会收到LOGIN消息,可能是什么原因?

不确定send flags参数是否设置正确。

static const char *LOGIN = "LOGIN\n";

int main()
{
    int s = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in addr;
    socklen_t addrlen = sizeof(addr);

    //initialize structure
    bzero(&addr, addrlen);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(6666);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);

    bind(s, (struct sockaddr *)&addr, addrlen);
    listen(s, 1);

    struct sockaddr_in client_addr;
    socklen_t client_addrlen = sizeof(client_addr);
    int c = accept(s, (struct sockaddr *)&client_addr, &client_addrlen);

    char *msg = new char[15];

        //print client address
        char * buf = new char[16];
        inet_ntop(AF_INET, &(client_addr.sin_addr.s_addr), buf, 16);
        cout << "Client connected: " << buf << endl;
        cout << "---------------------" << endl;

        send(c, LOGIN, sizeof(LOGIN), 0);

    close(c);
    close(s);
    return 0;
}

1 个答案:

答案 0 :(得分:3)

你必须改变:

static const char *LOGIN = "LOGIN\n";

为:

static const char LOGIN[] = "LOGIN\n";

和发送电话:

send(c, LOGIN, sizeof(LOGIN)-1, 0);

原始调用传递了4(如果在32位系统上),因为sizeof应用于指针而不是字符串。固定版本中的-1会从字符串中减去终止'0'