套接字绑定不会返回int [英] socket binding won't return an int

查看:563
本文介绍了套接字绑定不会返回int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程式码片段如下:

int descriptor = socket(AF_INET, SOCK_STREAM, 0);
if(descriptor < 0){
    cerr << "Error establishing socket connection." << endl;
    return -1;
}
int port = 3400;
struct sockaddr_in address;
char buffer[140];
address.sin_family = AF_INET;
address.sin_addr.s_addr = htons(INADDR_ANY);
address.sin_port = htons(port);
int size = sizeof(address);
if(bind(descriptor,(struct sockaddr*)&address,size) < 0){
    cerr << "Error binding socket." << endl;
}
cout << "Waiting for connection on " << INADDR_ANY << " on port " << port << ends;

每当我尝试编译这个,我得到以下错误:

whenever I try compiling this, I get the following error:

error: invalid operands to binary expression 
('__bind<int &, sockaddr *, int &>' and 'int')
if(bind(descriptor,(struct sockaddr*)&address,size) < 0){

有人知道这是什么意思吗? bind()应该返回一个整数,我想。我的导入如下所示:

Does anybody know what this could mean? bind() is supposed to return an integer or so I thought. My imports look like this:

#include <iostream>     
#include <string.h>   
#include <string>       
#include <sys/socket.h> 
#include <sys/types.h> 
#include <netinet/in.h>
#include <arpa/inet.h> 
#include <netdb.h>  
#include <unistd.h>
using namespace std;


$ b

谢谢!

Thanks!

推荐答案

使用namespace std; 结合太多的头标包含可能是这里的罪魁祸首 - 有一个原因为什么它在这里重复一遍又一遍 使用它。通过这样做,编译器看到 bind ,并认为你的意思是 std :: bind ; functions> ,而不是 :: bind 。所以要么做正确的事情,并审查,如果你真的需要包括所有这些头,摆脱使用声明,或使用 :: bind em>:或两者 - 使用 :: 来表示要使用全局命名空间中的一些标准API函数并不好)

using namespace std; combined with too much header inclusions is likely the culprit here - there's a reason why it has been repeated over and over again here on SO not to use it. By doing that, the compiler sees bind and thinks you mean std::bind from <functional>, not ::bind for sockets. So either do the right thing and review if you really need to include all those headers and get rid of that using declaration, or use ::bind (edit: or both - it's not bad to use :: to indicate you want to use some standard API function from the global namespace)

这篇关于套接字绑定不会返回int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆