我正在学习套接字编程,当我尝试在我的客户端和服务器之间创建连接时,只有当我如下设置时
客户端.cpp:
serAdd.sin_addr.s_addr=htol(INADDR_ANY);
服务器.cpp:
serAdd.sin_addr.s_addr=htol(INADDR_ANY);
bind(server,(const sockaddr *)&serAdd,sizeof(serAdd);
可以建立连接,如果我把INADDR_ANY改成127.0.0.1,就无法建立连接,下面是我的程序:
客户端.cpp:
#define portNum 6666
int main()
{
int client,i;
sockaddr_in serAdd;
char *ip="127.0.0.1";
client=socket(AF_INET,SOCK_STREAM,0);
if(client<0)
{
cout<<"Fail to create socket..."<<endl;
return 0;
}
cout<<"Creating connection..."<<endl;
serAdd.sin_family=AF_INET;
serAdd.sin_addr.s_addr=htonl(*ip);
serAdd.sin_port=htons(portNum);
if(connect(client,(const sockaddr *)&serAdd,sizeof(serAdd))==0)
{
cout<<"Connected!"<<endl;
cin>>i;
}
else
{
cout<<"Connect failed..."<<endl;
cin>>i;
}
}
服务器.cpp:
#define portNum 6666
int main()
{
int client,server;
sockaddr_in serAdd,
cliAdd;
char *ip="127.0.0.1";
server=socket(AF_INET,SOCK_STREAM,0);
if(server<0)
{
cout<<"Fail to create socket..."<<endl;
return 0;
}
cout<<"Binding..."<<endl;
serAdd.sin_family=AF_INET;
serAdd.sin_addr.s_addr=htonl(INADDR_ANY);
serAdd.sin_port=htons(portNum);
if(bind(server,(const sockaddr *)&serAdd,sizeof(serAdd))==0)
{
cout<<"Binding succed!..."<<endl;
}
else
{
cout<<"Binding failed..."<<endl;
return 0;
}
if(listen(server,1)==0)
{
cout<<"Listening..."<<endl;
}
else
{
cout<<"Listening failed..."<<endl;
return 0;
}
socklen_t size=sizeof(cliAdd);
while(1)
{
if(accept(server,(sockaddr *)&cliAdd,&size)>=0)
cout<<"Connection created!"<<endl;
else
{
cout<<"accept failed..."<<endl;
return 0;
}
}
}
最佳答案
使用 inet_addr()
从“字符串”设置 IPv4 地址:
serAdd.sin_addr.s_addr = inet_addr("127.0.0.1");
或
inet_aton("127.0.0.1", &serAdd.sin_addr);
要支持 IPv6 或您真正想要使用的其他可能即将出现的地址模式 inet_pton()
.
在您的 IPv4 情况下,这可能看起来像这样:
inet_pton(AF_INET, "127.0.0.1", &serAdd.sin_addr);
If I changed INADDR_ANY to 127.0.0.1
做这样的事情
... = htol("127.0.0.1");
应该让编译器发出警告。认真对待警告。
作为noted通过 Chris Dodd在这种分配环回地址 (127.0.0.1
) 的特殊情况下,您可以通过执行以下操作来简化此操作
serAdd.sin_addr.s_addr = INADDR_LOOPBACK;
关于c++ - 与 127.0.0.1 和 INADDR_ANY 绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37376903/