简体   繁体   English

TCP套接字服务器不发送

[英]tcp socket server not sending

I have this code, I run client from virtual machine on same PC it can connect but it will never receive LOGIN message, what could be the cause? 我有这段代码,我从可以连接的同一台PC上的虚拟机运行客户端,但是它永远不会收到LOGIN消息,这可能是什么原因?

Not sure about send flags argument is set right. 不确定关于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;
}

You have to change: 您必须更改:

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

to: 至:

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

and the send call to: 并将呼叫发送至:

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

The original call passed 4 (if on 32-bit system) because the sizeof was applied on pointer rather than on the string. 最初的调用传递了4(如果在32位系统上),因为sizeof应用于指针而不是字符串。 The -1 in the fixed version subtracts the terminating '0' from the string. 固定版本中的-1从字符串中减去结尾的'0'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM